Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/unit/unit1300.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curlcheck.h" #include "llist.h" static struct Curl_llist llist; static struct Curl_llist llist_destination; static void test_Curl_llist_dtor(void *key, void *value) { /* used by the llist API, does nothing here */ (void)key; (void)value; } static CURLcode unit_setup(void) { Curl_llist_init(&llist, test_Curl_llist_dtor); Curl_llist_init(&llist_destination, test_Curl_llist_dtor); return CURLE_OK; } static void unit_stop(void) { } UNITTEST_START { int unusedData_case1 = 1; int unusedData_case2 = 2; int unusedData_case3 = 3; struct Curl_llist_element case1_list; struct Curl_llist_element case2_list; struct Curl_llist_element case3_list; struct Curl_llist_element case4_list; struct Curl_llist_element *head; struct Curl_llist_element *element_next; struct Curl_llist_element *element_prev; struct Curl_llist_element *to_remove; size_t llist_size = Curl_llist_count(&llist); /** * testing llist_init * case 1: * list initiation * @assumptions: * 1: list size will be 0 * 2: list head will be NULL * 3: list tail will be NULL * 4: list dtor will be NULL */ fail_unless(llist.size == 0, "list initial size should be zero"); fail_unless(llist.head == NULL, "list head should initiate to NULL"); fail_unless(llist.tail == NULL, "list tail should intiate to NULL"); fail_unless(llist.dtor == test_Curl_llist_dtor, "list dtor should initiate to test_Curl_llist_dtor"); /** * testing Curl_llist_insert_next * case 1: * list is empty * @assumptions: * 1: list size will be 1 * 2: list head will hold the data "unusedData_case1" * 3: list tail will be the same as list head */ Curl_llist_insert_next(&llist, llist.head, &unusedData_case1, &case1_list); fail_unless(Curl_llist_count(&llist) == 1, "List size should be 1 after adding a new element"); /*test that the list head data holds my unusedData */ fail_unless(llist.head->ptr == &unusedData_case1, "head ptr should be first entry"); /*same goes for the list tail */ fail_unless(llist.tail == llist.head, "tail and head should be the same"); /** * testing Curl_llist_insert_next * case 2: * list has 1 element, adding one element after the head * @assumptions: * 1: the element next to head should be our newly created element * 2: the list tail should be our newly created element */ Curl_llist_insert_next(&llist, llist.head, &unusedData_case3, &case3_list); fail_unless(llist.head->next->ptr == &unusedData_case3, "the node next to head is not getting set correctly"); fail_unless(llist.tail->ptr == &unusedData_case3, "the list tail is not getting set correctly"); /** * testing Curl_llist_insert_next * case 3: * list has >1 element, adding one element after "NULL" * @assumptions: * 1: the element next to head should be our newly created element * 2: the list tail should different from newly created element */ Curl_llist_insert_next(&llist, llist.head, &unusedData_case2, &case2_list); fail_unless(llist.head->next->ptr == &unusedData_case2, "the node next to head is not getting set correctly"); /* better safe than sorry, check that the tail isn't corrupted */ fail_unless(llist.tail->ptr != &unusedData_case2, "the list tail is not getting set correctly"); /* unit tests for Curl_llist_remove */ /** * case 1: * list has >1 element, removing head * @assumptions: * 1: list size will be decremented by one * 2: head will be the head->next * 3: "new" head's previous will be NULL */ head = llist.head; abort_unless(head, "llist.head is NULL"); element_next = head->next; llist_size = Curl_llist_count(&llist); Curl_llist_remove(&llist, llist.head, NULL); fail_unless(Curl_llist_count(&llist) == (llist_size-1), "llist size not decremented as expected"); fail_unless(llist.head == element_next, "llist new head not modified properly"); abort_unless(llist.head, "llist.head is NULL"); fail_unless(llist.head->prev == NULL, "new head previous not set to null"); /** * case 2: * removing non head element, with list having >=2 elements * @setup: * 1: insert another element to the list to make element >=2 * @assumptions: * 1: list size will be decremented by one ; tested * 2: element->previous->next will be element->next * 3: element->next->previous will be element->previous */ Curl_llist_insert_next(&llist, llist.head, &unusedData_case3, &case4_list); llist_size = Curl_llist_count(&llist); fail_unless(llist_size == 3, "should be 3 list members"); to_remove = llist.head->next; abort_unless(to_remove, "to_remove is NULL"); element_next = to_remove->next; element_prev = to_remove->prev; Curl_llist_remove(&llist, to_remove, NULL); fail_unless(element_prev->next == element_next, "element previous->next is not being adjusted"); abort_unless(element_next, "element_next is NULL"); fail_unless(element_next->prev == element_prev, "element next->previous is not being adjusted"); /** * case 3: * removing the tail with list having >=1 element * @assumptions * 1: list size will be decremented by one ;tested * 2: element->previous->next will be element->next ;tested * 3: element->next->previous will be element->previous ;tested * 4: list->tail will be tail->previous */ to_remove = llist.tail; element_prev = to_remove->prev; Curl_llist_remove(&llist, to_remove, NULL); fail_unless(llist.tail == element_prev, "llist tail is not being adjusted when removing tail"); /** * case 4: * removing head with list having 1 element * @assumptions: * 1: list size will be decremented by one ;tested * 2: list head will be null * 3: list tail will be null */ to_remove = llist.head; Curl_llist_remove(&llist, to_remove, NULL); fail_unless(llist.head == NULL, "llist head is not NULL while the llist is empty"); fail_unless(llist.tail == NULL, "llist tail is not NULL while the llist is empty"); Curl_llist_destroy(&llist, NULL); Curl_llist_destroy(&llist_destination, NULL); } UNITTEST_STOP
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/unit/unit1611.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curlcheck.h" #include "curl_md4.h" static CURLcode unit_setup(void) { return CURLE_OK; } static void unit_stop(void) { } UNITTEST_START #ifndef CURL_DISABLE_CRYPTO_AUTH const char string1[] = "1"; const char string2[] = "hello-you-fool"; unsigned char output[MD4_DIGEST_LENGTH]; unsigned char *testp = output; Curl_md4it(output, (const unsigned char *) string1, strlen(string1)); verify_memory(testp, "\x8b\xe1\xec\x69\x7b\x14\xad\x3a\x53\xb3\x71\x43\x61\x20\x64" "\x1d", MD4_DIGEST_LENGTH); Curl_md4it(output, (const unsigned char *) string2, strlen(string2)); verify_memory(testp, "\xa7\x16\x1c\xad\x7e\xbe\xdb\xbc\xf8\xc7\x23\x10\x2d\x2c\xe2" "\x0b", MD4_DIGEST_LENGTH); #endif UNITTEST_STOP
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/unit/unit1309.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curlcheck.h" #include "splay.h" #include "warnless.h" static CURLcode unit_setup(void) { return CURLE_OK; } static void unit_stop(void) { } static void splayprint(struct Curl_tree *t, int d, char output) { struct Curl_tree *node; int i; int count; if(!t) return; splayprint(t->larger, d + 1, output); for(i = 0; i<d; i++) if(output) printf(" "); if(output) { printf("%ld.%ld[%d]", (long)t->key.tv_sec, (long)t->key.tv_usec, i); } for(count = 0, node = t->samen; node != t; node = node->samen, count++) ; if(output) { if(count) printf(" [%d more]\n", count); else printf("\n"); } splayprint(t->smaller, d + 1, output); } UNITTEST_START /* number of nodes to add to the splay tree */ #define NUM_NODES 50 struct Curl_tree *root, *removed; struct Curl_tree nodes[NUM_NODES*3]; size_t storage[NUM_NODES*3]; int rc; int i, j; struct curltime tv_now = {0, 0}; root = NULL; /* the empty tree */ /* add nodes */ for(i = 0; i < NUM_NODES; i++) { struct curltime key; key.tv_sec = 0; key.tv_usec = (541*i)%1023; storage[i] = key.tv_usec; nodes[i].payload = &storage[i]; root = Curl_splayinsert(key, root, &nodes[i]); } puts("Result:"); splayprint(root, 0, 1); for(i = 0; i < NUM_NODES; i++) { int rem = (i + 7)%NUM_NODES; printf("Tree look:\n"); splayprint(root, 0, 1); printf("remove pointer %d, payload %zu\n", rem, *(size_t *)nodes[rem].payload); rc = Curl_splayremove(root, &nodes[rem], &root); if(rc) { /* failed! */ printf("remove %d failed!\n", rem); fail("remove"); } } fail_unless(root == NULL, "tree not empty after removing all nodes"); /* rebuild tree */ for(i = 0; i < NUM_NODES; i++) { struct curltime key; key.tv_sec = 0; key.tv_usec = (541*i)%1023; /* add some nodes with the same key */ for(j = 0; j <= i % 3; j++) { storage[i * 3 + j] = key.tv_usec*10 + j; nodes[i * 3 + j].payload = &storage[i * 3 + j]; root = Curl_splayinsert(key, root, &nodes[i * 3 + j]); } } removed = NULL; for(i = 0; i <= 1100; i += 100) { printf("Removing nodes not larger than %d\n", i); tv_now.tv_usec = i; root = Curl_splaygetbest(tv_now, root, &removed); while(removed != NULL) { printf("removed payload %zu[%zu]\n", (*(size_t *)removed->payload) / 10, (*(size_t *)removed->payload) % 10); root = Curl_splaygetbest(tv_now, root, &removed); } } fail_unless(root == NULL, "tree not empty when it should be"); UNITTEST_STOP
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/unit/unit1654.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2019 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curlcheck.h" #include "urldata.h" #include "altsvc.h" static CURLcode unit_setup(void) { return CURLE_OK; } static void unit_stop(void) { curl_global_cleanup(); } #if defined(CURL_DISABLE_HTTP) || defined(CURL_DISABLE_ALTSVC) UNITTEST_START { return 0; /* nothing to do when HTTP or alt-svc is disabled */ } UNITTEST_STOP #else UNITTEST_START { char outname[256]; CURL *curl; CURLcode result; struct altsvcinfo *asi = Curl_altsvc_init(); if(!asi) return 1; result = Curl_altsvc_load(asi, arg); if(result) { Curl_altsvc_cleanup(&asi); return result; } curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if(!curl) goto fail; fail_unless(asi->list.size == 4, "wrong number of entries"); msnprintf(outname, sizeof(outname), "%s-out", arg); result = Curl_altsvc_parse(curl, asi, "h2=\"example.com:8080\"\r\n", ALPN_h1, "example.org", 8080); if(result) { fprintf(stderr, "Curl_altsvc_parse() failed!\n"); unitfail++; } fail_unless(asi->list.size == 5, "wrong number of entries"); result = Curl_altsvc_parse(curl, asi, "h3=\":8080\"\r\n", ALPN_h1, "2.example.org", 8080); if(result) { fprintf(stderr, "Curl_altsvc_parse(2) failed!\n"); unitfail++; } fail_unless(asi->list.size == 6, "wrong number of entries"); result = Curl_altsvc_parse(curl, asi, "h2=\"example.com:8080\", h3=\"yesyes.com\"\r\n", ALPN_h1, "3.example.org", 8080); if(result) { fprintf(stderr, "Curl_altsvc_parse(3) failed!\n"); unitfail++; } /* that one should make two entries */ fail_unless(asi->list.size == 8, "wrong number of entries"); result = Curl_altsvc_parse(curl, asi, "h2=\"example.com:443\"; ma = 120;\r\n", ALPN_h2, "example.org", 80); if(result) { fprintf(stderr, "Curl_altsvc_parse(4) failed!\n"); unitfail++; } fail_unless(asi->list.size == 9, "wrong number of entries"); /* quoted 'ma' value */ result = Curl_altsvc_parse(curl, asi, "h2=\"example.net:443\"; ma=\"180\";\r\n", ALPN_h2, "example.net", 80); if(result) { fprintf(stderr, "Curl_altsvc_parse(4) failed!\n"); unitfail++; } fail_unless(asi->list.size == 10, "wrong number of entries"); result = Curl_altsvc_parse(curl, asi, "h2=\":443\", h3=\":443\"; ma = 120; persist = 1\r\n", ALPN_h1, "curl.se", 80); if(result) { fprintf(stderr, "Curl_altsvc_parse(5) failed!\n"); unitfail++; } fail_unless(asi->list.size == 12, "wrong number of entries"); /* clear that one again and decrease the counter */ result = Curl_altsvc_parse(curl, asi, "clear;\r\n", ALPN_h1, "curl.se", 80); if(result) { fprintf(stderr, "Curl_altsvc_parse(6) failed!\n"); unitfail++; } fail_unless(asi->list.size == 10, "wrong number of entries"); Curl_altsvc_save(curl, asi, outname); curl_easy_cleanup(curl); curl_global_cleanup(); fail: Curl_altsvc_cleanup(&asi); curl_global_cleanup(); return unitfail; } UNITTEST_STOP #endif
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/unit/unit1395.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curlcheck.h" #include "dotdot.h" #include "memdebug.h" static CURLcode unit_setup(void) { return CURLE_OK; } static void unit_stop(void) { } struct dotdot { const char *input; const char *output; }; UNITTEST_START unsigned int i; int fails = 0; const struct dotdot pairs[] = { { "/a/b/c/./../../g", "/a/g" }, { "mid/content=5/../6", "mid/6" }, { "/hello/../moo", "/moo" }, { "/1/../1", "/1" }, { "/1/./1", "/1/1" }, { "/1/..", "/" }, { "/1/.", "/1/" }, { "/1/./..", "/" }, { "/1/./../2", "/2" }, { "/hello/1/./../2", "/hello/2" }, { "test/this", "test/this" }, { "test/this/../now", "test/now" }, { "/1../moo../foo", "/1../moo../foo"}, { "/../../moo", "/moo"}, { "/../../moo?andnot/../yay", "/moo?andnot/../yay"}, { "/123?foo=/./&bar=/../", "/123?foo=/./&bar=/../"}, { "/../moo/..?what", "/?what" }, { "/", "/" }, { "", "" }, { "/.../", "/.../" }, { "./moo", "moo" }, { "../moo", "moo" }, { "/.", "/" }, { "/..", "/" }, { "/moo/..", "/" }, { "..", "" }, { ".", "" }, }; for(i = 0; i < sizeof(pairs)/sizeof(pairs[0]); i++) { char *out = Curl_dedotdotify(pairs[i].input); abort_unless(out != NULL, "returned NULL!"); if(strcmp(out, pairs[i].output)) { fprintf(stderr, "Test %u: '%s' gave '%s' instead of '%s'\n", i, pairs[i].input, out, pairs[i].output); fail("Test case output mismatched"); fails++; } else fprintf(stderr, "Test %u: OK\n", i); free(out); } fail_if(fails, "output mismatched"); UNITTEST_STOP
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/unit/unit1607.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curlcheck.h" #include "urldata.h" #include "connect.h" #include "share.h" #include "memdebug.h" /* LAST include file */ static void unit_stop(void) { curl_global_cleanup(); } static CURLcode unit_setup(void) { int res = CURLE_OK; global_init(CURL_GLOBAL_ALL); return res; } struct testcase { /* host:port:address[,address]... */ const char *optval; /* lowercase host and port to retrieve the addresses from hostcache */ const char *host; int port; /* whether we expect a permanent or non-permanent cache entry */ bool permanent; /* 0 to 9 addresses expected from hostcache */ const char *address[10]; }; /* In builds without IPv6 support CURLOPT_RESOLVE should skip over those addresses, so we have to do that as well. */ static const char skip = 0; #ifdef ENABLE_IPV6 #define IPV6ONLY(x) x #else #define IPV6ONLY(x) &skip #endif /* CURLOPT_RESOLVE address parsing tests */ static const struct testcase tests[] = { /* spaces aren't allowed, for now */ { "test.com:80:127.0.0.1, 127.0.0.2", "test.com", 80, TRUE, { NULL, } }, { "TEST.com:80:,,127.0.0.1,,,127.0.0.2,,,,::1,,,", "test.com", 80, TRUE, { "127.0.0.1", "127.0.0.2", IPV6ONLY("::1"), } }, { "test.com:80:::1,127.0.0.1", "test.com", 80, TRUE, { IPV6ONLY("::1"), "127.0.0.1", } }, { "test.com:80:[::1],127.0.0.1", "test.com", 80, TRUE, { IPV6ONLY("::1"), "127.0.0.1", } }, { "test.com:80:::1", "test.com", 80, TRUE, { IPV6ONLY("::1"), } }, { "test.com:80:[::1]", "test.com", 80, TRUE, { IPV6ONLY("::1"), } }, { "test.com:80:127.0.0.1", "test.com", 80, TRUE, { "127.0.0.1", } }, { "test.com:80:,127.0.0.1", "test.com", 80, TRUE, { "127.0.0.1", } }, { "test.com:80:127.0.0.1,", "test.com", 80, TRUE, { "127.0.0.1", } }, { "test.com:0:127.0.0.1", "test.com", 0, TRUE, { "127.0.0.1", } }, { "+test.com:80:127.0.0.1,", "test.com", 80, FALSE, { "127.0.0.1", } }, }; UNITTEST_START { int i; int testnum = sizeof(tests) / sizeof(struct testcase); struct Curl_multi *multi = NULL; struct Curl_easy *easy = NULL; struct curl_slist *list = NULL; for(i = 0; i < testnum; ++i) { int j; int addressnum = sizeof(tests[i].address) / sizeof(*tests[i].address); struct Curl_addrinfo *addr; struct Curl_dns_entry *dns; void *entry_id; bool problem = false; easy = curl_easy_init(); if(!easy) goto error; /* create a multi handle and add the easy handle to it so that the hostcache is setup */ multi = curl_multi_init(); curl_multi_add_handle(multi, easy); list = curl_slist_append(NULL, tests[i].optval); if(!list) goto error; curl_easy_setopt(easy, CURLOPT_RESOLVE, list); Curl_loadhostpairs(easy); entry_id = (void *)aprintf("%s:%d", tests[i].host, tests[i].port); if(!entry_id) goto error; dns = Curl_hash_pick(easy->dns.hostcache, entry_id, strlen(entry_id) + 1); free(entry_id); entry_id = NULL; addr = dns ? dns->addr : NULL; for(j = 0; j < addressnum; ++j) { int port = 0; char ipaddress[MAX_IPADR_LEN] = {0}; if(!addr && !tests[i].address[j]) break; if(tests[i].address[j] == &skip) continue; if(addr && !Curl_addr2string(addr->ai_addr, addr->ai_addrlen, ipaddress, &port)) { fprintf(stderr, "%s:%d tests[%d] failed. getaddressinfo failed.\n", __FILE__, __LINE__, i); problem = true; break; } if(addr && !tests[i].address[j]) { fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " "is %s but tests[%d].address[%d] is NULL.\n", __FILE__, __LINE__, i, ipaddress, i, j); problem = true; break; } if(!addr && tests[i].address[j]) { fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " "is NULL but tests[%d].address[%d] is %s.\n", __FILE__, __LINE__, i, i, j, tests[i].address[j]); problem = true; break; } if(!curl_strequal(ipaddress, tests[i].address[j])) { fprintf(stderr, "%s:%d tests[%d] failed. the retrieved addr " "%s is not equal to tests[%d].address[%d] %s.\n", __FILE__, __LINE__, i, ipaddress, i, j, tests[i].address[j]); problem = true; break; } if(port != tests[i].port) { fprintf(stderr, "%s:%d tests[%d] failed. the retrieved port " "for tests[%d].address[%d] is %ld but tests[%d].port is %d.\n", __FILE__, __LINE__, i, i, j, port, i, tests[i].port); problem = true; break; } if(dns->timestamp && tests[i].permanent) { fprintf(stderr, "%s:%d tests[%d] failed. the timestamp is not zero " "but tests[%d].permanent is TRUE\n", __FILE__, __LINE__, i, i); problem = true; break; } if(dns->timestamp == 0 && !tests[i].permanent) { fprintf(stderr, "%s:%d tests[%d] failed. the timestamp is zero " "but tests[%d].permanent is FALSE\n", __FILE__, __LINE__, i, i); problem = true; break; } addr = addr->ai_next; } curl_easy_cleanup(easy); easy = NULL; curl_multi_cleanup(multi); multi = NULL; curl_slist_free_all(list); list = NULL; if(problem) { unitfail++; continue; } } error: curl_easy_cleanup(easy); curl_multi_cleanup(multi); curl_slist_free_all(list); } UNITTEST_STOP
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/util.h
#ifndef HEADER_CURL_SERVER_UTIL_H #define HEADER_CURL_SERVER_UTIL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" char *data_to_hex(char *data, size_t len); void logmsg(const char *msg, ...); long timediff(struct timeval newer, struct timeval older); #define TEST_DATA_PATH "%s/data/test%ld" #define ALTTEST_DATA_PATH "%s/log/test%ld" #define SERVERLOGS_LOCK "log/serverlogs.lock" /* global variable, where to find the 'data' dir */ extern const char *path; /* global variable, log file name */ extern const char *serverlogfile; extern const char *cmdfile; #if defined(WIN32) || defined(_WIN32) #include <process.h> #include <fcntl.h> #define sleep(sec) Sleep ((sec)*1000) #undef perror #define perror(m) win32_perror(m) void win32_perror(const char *msg); #endif /* WIN32 or _WIN32 */ #ifdef USE_WINSOCK void win32_init(void); void win32_cleanup(void); #endif /* USE_WINSOCK */ /* fopens the test case file */ FILE *test2fopen(long testno); int wait_ms(int timeout_ms); curl_off_t our_getpid(void); int write_pidfile(const char *filename); int write_portfile(const char *filename, int port); void set_advisor_read_lock(const char *filename); void clear_advisor_read_lock(const char *filename); int strncasecompare(const char *first, const char *second, size_t max); /* global variable which if set indicates that the program should finish */ extern volatile int got_exit_signal; /* global variable which if set indicates the first signal handled */ extern volatile int exit_signal; #ifdef WIN32 /* global event which if set indicates that the program should finish */ extern HANDLE exit_event; #endif void install_signal_handlers(bool keep_sigalrm); void restore_signal_handlers(bool keep_sigalrm); #endif /* HEADER_CURL_SERVER_UTIL_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/tftp.h
#ifndef HEADER_CURL_SERVER_TFTP_H #define HEADER_CURL_SERVER_TFTP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" /* This file is a rewrite/clone of the arpa/tftp.h file for systems without it. */ #define SEGSIZE 512 /* data segment size */ #if defined(__GNUC__) && ((__GNUC__ >= 3) || \ ((__GNUC__ == 2) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ >= 7))) # define PACKED_STRUCT __attribute__((__packed__)) #else # define PACKED_STRUCT /*NOTHING*/ #endif /* Using a packed struct as binary in a program is begging for problems, but the tftpd server was written like this so we have this struct here to make things build. */ struct tftphdr { short th_opcode; /* packet type */ unsigned short th_block; /* all sorts of things */ char th_data[1]; /* data or error string */ } PACKED_STRUCT; #define th_stuff th_block #define th_code th_block #define th_msg th_data #define EUNDEF 0 #define ENOTFOUND 1 #define EACCESS 2 #define ENOSPACE 3 #define EBADOP 4 #define EBADID 5 #define EEXISTS 6 #define ENOUSER 7 #endif /* HEADER_CURL_SERVER_TFTP_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/rtspd.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" /* * curl's test suite Real Time Streaming Protocol (RTSP) server. * * This source file was started based on curl's HTTP test suite server. */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_NETINET_TCP_H #include <netinet/tcp.h> /* for TCP_NODELAY */ #endif #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ #include "getpart.h" #include "util.h" #include "server_sockaddr.h" /* include memdebug.h last */ #include "memdebug.h" #ifdef USE_WINSOCK #undef EINTR #define EINTR 4 /* errno.h value */ #undef ERANGE #define ERANGE 34 /* errno.h value */ #endif #ifdef ENABLE_IPV6 static bool use_ipv6 = FALSE; #endif static const char *ipv_inuse = "IPv4"; static int serverlogslocked = 0; #define REQBUFSIZ 150000 #define REQBUFSIZ_TXT "149999" static long prevtestno = -1; /* previous test number we served */ static long prevpartno = -1; /* previous part number we served */ static bool prevbounce = FALSE; /* instructs the server to increase the part number for a test in case the identical testno+partno request shows up again */ #define RCMD_NORMALREQ 0 /* default request, use the tests file normally */ #define RCMD_IDLE 1 /* told to sit idle */ #define RCMD_STREAM 2 /* told to stream */ typedef enum { RPROT_NONE = 0, RPROT_RTSP = 1, RPROT_HTTP = 2 } reqprot_t; #define SET_RTP_PKT_CHN(p,c) ((p)[1] = (unsigned char)((c) & 0xFF)) #define SET_RTP_PKT_LEN(p,l) (((p)[2] = (unsigned char)(((l) >> 8) & 0xFF)), \ ((p)[3] = (unsigned char)((l) & 0xFF))) struct httprequest { char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */ size_t checkindex; /* where to start checking of the request */ size_t offset; /* size of the incoming request */ long testno; /* test number found in the request */ long partno; /* part number found in the request */ bool open; /* keep connection open info, as found in the request */ bool auth_req; /* authentication required, don't wait for body unless there's an Authorization header */ bool auth; /* Authorization header present in the incoming request */ size_t cl; /* Content-Length of the incoming request */ bool digest; /* Authorization digest header found */ bool ntlm; /* Authorization ntlm header found */ int pipe; /* if non-zero, expect this many requests to do a "piped" request/response */ int skip; /* if non-zero, the server is instructed to not read this many bytes from a PUT/POST request. Ie the client sends N bytes said in Content-Length, but the server only reads N - skip bytes. */ int rcmd; /* doing a special command, see defines above */ reqprot_t protocol; /* request protocol, HTTP or RTSP */ int prot_version; /* HTTP or RTSP version (major*10 + minor) */ bool pipelining; /* true if request is pipelined */ char *rtp_buffer; size_t rtp_buffersize; }; static int ProcessRequest(struct httprequest *req); static void storerequest(char *reqbuf, size_t totalsize); #define DEFAULT_PORT 8999 #ifndef DEFAULT_LOGFILE #define DEFAULT_LOGFILE "log/rtspd.log" #endif const char *serverlogfile = DEFAULT_LOGFILE; #define RTSPDVERSION "curl test suite RTSP server/0.1" #define REQUEST_DUMP "log/server.input" #define RESPONSE_DUMP "log/server.response" /* very-big-path support */ #define MAXDOCNAMELEN 140000 #define MAXDOCNAMELEN_TXT "139999" #define REQUEST_KEYWORD_SIZE 256 #define REQUEST_KEYWORD_SIZE_TXT "255" #define CMD_AUTH_REQUIRED "auth_required" /* 'idle' means that it will accept the request fine but never respond any data. Just keep the connection alive. */ #define CMD_IDLE "idle" /* 'stream' means to send a never-ending stream of data */ #define CMD_STREAM "stream" #define END_OF_HEADERS "\r\n\r\n" enum { DOCNUMBER_NOTHING = -7, DOCNUMBER_QUIT = -6, DOCNUMBER_BADCONNECT = -5, DOCNUMBER_INTERNAL = -4, DOCNUMBER_CONNECT = -3, DOCNUMBER_WERULEZ = -2, DOCNUMBER_404 = -1 }; /* sent as reply to a QUIT */ static const char *docquit = "HTTP/1.1 200 Goodbye" END_OF_HEADERS; /* sent as reply to a CONNECT */ static const char *docconnect = "HTTP/1.1 200 Mighty fine indeed" END_OF_HEADERS; /* sent as reply to a "bad" CONNECT */ static const char *docbadconnect = "HTTP/1.1 501 Forbidden you fool" END_OF_HEADERS; /* send back this on HTTP 404 file not found */ static const char *doc404_HTTP = "HTTP/1.1 404 Not Found\r\n" "Server: " RTSPDVERSION "\r\n" "Connection: close\r\n" "Content-Type: text/html" END_OF_HEADERS "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" "<HTML><HEAD>\n" "<TITLE>404 Not Found</TITLE>\n" "</HEAD><BODY>\n" "<H1>Not Found</H1>\n" "The requested URL was not found on this server.\n" "<P><HR><ADDRESS>" RTSPDVERSION "</ADDRESS>\n" "</BODY></HTML>\n"; /* send back this on RTSP 404 file not found */ static const char *doc404_RTSP = "RTSP/1.0 404 Not Found\r\n" "Server: " RTSPDVERSION END_OF_HEADERS; /* Default size to send away fake RTP data */ #define RTP_DATA_SIZE 12 static const char *RTP_DATA = "$_1234\n\0asdf"; static int ProcessRequest(struct httprequest *req) { char *line = &req->reqbuf[req->checkindex]; bool chunked = FALSE; static char request[REQUEST_KEYWORD_SIZE]; static char doc[MAXDOCNAMELEN]; static char prot_str[5]; int prot_major, prot_minor; char *end = strstr(line, END_OF_HEADERS); logmsg("ProcessRequest() called with testno %ld and line [%s]", req->testno, line); /* try to figure out the request characteristics as soon as possible, but only once! */ if((req->testno == DOCNUMBER_NOTHING) && sscanf(line, "%" REQUEST_KEYWORD_SIZE_TXT"s %" MAXDOCNAMELEN_TXT "s %4s/%d.%d", request, doc, prot_str, &prot_major, &prot_minor) == 5) { char *ptr; char logbuf[256]; if(!strcmp(prot_str, "HTTP")) { req->protocol = RPROT_HTTP; } else if(!strcmp(prot_str, "RTSP")) { req->protocol = RPROT_RTSP; } else { req->protocol = RPROT_NONE; logmsg("got unknown protocol %s", prot_str); return 1; } req->prot_version = prot_major*10 + prot_minor; /* find the last slash */ ptr = strrchr(doc, '/'); /* get the number after it */ if(ptr) { FILE *stream; if((strlen(doc) + strlen(request)) < 200) msnprintf(logbuf, sizeof(logbuf), "Got request: %s %s %s/%d.%d", request, doc, prot_str, prot_major, prot_minor); else msnprintf(logbuf, sizeof(logbuf), "Got a *HUGE* request %s/%d.%d", prot_str, prot_major, prot_minor); logmsg("%s", logbuf); if(!strncmp("/verifiedserver", ptr, 15)) { logmsg("Are-we-friendly question received"); req->testno = DOCNUMBER_WERULEZ; return 1; /* done */ } if(!strncmp("/quit", ptr, 5)) { logmsg("Request-to-quit received"); req->testno = DOCNUMBER_QUIT; return 1; /* done */ } ptr++; /* skip the slash */ /* skip all non-numericals following the slash */ while(*ptr && !ISDIGIT(*ptr)) ptr++; req->testno = strtol(ptr, &ptr, 10); if(req->testno > 10000) { req->partno = req->testno % 10000; req->testno /= 10000; } else req->partno = 0; msnprintf(logbuf, sizeof(logbuf), "Requested test number %ld part %ld", req->testno, req->partno); logmsg("%s", logbuf); stream = test2fopen(req->testno); if(!stream) { int error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Couldn't open test file %ld", req->testno); req->open = FALSE; /* closes connection */ return 1; /* done */ } else { char *cmd = NULL; size_t cmdsize = 0; int num = 0; int rtp_channel = 0; int rtp_size = 0; int rtp_partno = -1; char *rtp_scratch = NULL; /* get the custom server control "commands" */ int error = getpart(&cmd, &cmdsize, "reply", "servercmd", stream); fclose(stream); if(error) { logmsg("getpart() failed with error: %d", error); req->open = FALSE; /* closes connection */ return 1; /* done */ } ptr = cmd; if(cmdsize) { logmsg("Found a reply-servercmd section!"); do { if(!strncmp(CMD_AUTH_REQUIRED, ptr, strlen(CMD_AUTH_REQUIRED))) { logmsg("instructed to require authorization header"); req->auth_req = TRUE; } else if(!strncmp(CMD_IDLE, ptr, strlen(CMD_IDLE))) { logmsg("instructed to idle"); req->rcmd = RCMD_IDLE; req->open = TRUE; } else if(!strncmp(CMD_STREAM, ptr, strlen(CMD_STREAM))) { logmsg("instructed to stream"); req->rcmd = RCMD_STREAM; } else if(1 == sscanf(ptr, "pipe: %d", &num)) { logmsg("instructed to allow a pipe size of %d", num); if(num < 0) logmsg("negative pipe size ignored"); else if(num > 0) req->pipe = num-1; /* decrease by one since we don't count the first request in this number */ } else if(1 == sscanf(ptr, "skip: %d", &num)) { logmsg("instructed to skip this number of bytes %d", num); req->skip = num; } else if(3 == sscanf(ptr, "rtp: part %d channel %d size %d", &rtp_partno, &rtp_channel, &rtp_size)) { if(rtp_partno == req->partno) { int i = 0; logmsg("RTP: part %d channel %d size %d", rtp_partno, rtp_channel, rtp_size); /* Make our scratch buffer enough to fit all the * desired data and one for padding */ rtp_scratch = malloc(rtp_size + 4 + RTP_DATA_SIZE); /* RTP is signalled with a $ */ rtp_scratch[0] = '$'; /* The channel follows and is one byte */ SET_RTP_PKT_CHN(rtp_scratch, rtp_channel); /* Length follows and is a two byte short in network order */ SET_RTP_PKT_LEN(rtp_scratch, rtp_size); /* Fill it with junk data */ for(i = 0; i < rtp_size; i += RTP_DATA_SIZE) { memcpy(rtp_scratch + 4 + i, RTP_DATA, RTP_DATA_SIZE); } if(!req->rtp_buffer) { req->rtp_buffer = rtp_scratch; req->rtp_buffersize = rtp_size + 4; } else { req->rtp_buffer = realloc(req->rtp_buffer, req->rtp_buffersize + rtp_size + 4); memcpy(req->rtp_buffer + req->rtp_buffersize, rtp_scratch, rtp_size + 4); req->rtp_buffersize += rtp_size + 4; free(rtp_scratch); } logmsg("rtp_buffersize is %zu, rtp_size is %d.", req->rtp_buffersize, rtp_size); } } else { logmsg("funny instruction found: %s", ptr); } ptr = strchr(ptr, '\n'); if(ptr) ptr++; else ptr = NULL; } while(ptr && *ptr); logmsg("Done parsing server commands"); } free(cmd); } } else { if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d", doc, &prot_major, &prot_minor) == 3) { msnprintf(logbuf, sizeof(logbuf), "Received a CONNECT %s HTTP/%d.%d request", doc, prot_major, prot_minor); logmsg("%s", logbuf); if(req->prot_version == 10) req->open = FALSE; /* HTTP 1.0 closes connection by default */ if(!strncmp(doc, "bad", 3)) /* if the host name starts with bad, we fake an error here */ req->testno = DOCNUMBER_BADCONNECT; else if(!strncmp(doc, "test", 4)) { /* if the host name starts with test, the port number used in the CONNECT line will be used as test number! */ char *portp = strchr(doc, ':'); if(portp && (*(portp + 1) != '\0') && ISDIGIT(*(portp + 1))) req->testno = strtol(portp + 1, NULL, 10); else req->testno = DOCNUMBER_CONNECT; } else req->testno = DOCNUMBER_CONNECT; } else { logmsg("Did not find test number in PATH"); req->testno = DOCNUMBER_404; } } } if(!end) { /* we don't have a complete request yet! */ logmsg("ProcessRequest returned without a complete request"); return 0; /* not complete yet */ } logmsg("ProcessRequest found a complete request"); if(req->pipe) /* we do have a full set, advance the checkindex to after the end of the headers, for the pipelining case mostly */ req->checkindex += (end - line) + strlen(END_OF_HEADERS); /* **** Persistence **** * * If the request is a HTTP/1.0 one, we close the connection unconditionally * when we're done. * * If the request is a HTTP/1.1 one, we MUST check for a "Connection:" * header that might say "close". If it does, we close a connection when * this request is processed. Otherwise, we keep the connection alive for X * seconds. */ do { if(got_exit_signal) return 1; /* done */ if((req->cl == 0) && strncasecompare("Content-Length:", line, 15)) { /* If we don't ignore content-length, we read it and we read the whole request including the body before we return. If we've been told to ignore the content-length, we will return as soon as all headers have been received */ char *endptr; char *ptr = line + 15; unsigned long clen = 0; while(*ptr && ISSPACE(*ptr)) ptr++; endptr = ptr; errno = 0; clen = strtoul(ptr, &endptr, 10); if((ptr == endptr) || !ISSPACE(*endptr) || (ERANGE == errno)) { /* this assumes that a zero Content-Length is valid */ logmsg("Found invalid Content-Length: (%s) in the request", ptr); req->open = FALSE; /* closes connection */ return 1; /* done */ } req->cl = clen - req->skip; logmsg("Found Content-Length: %lu in the request", clen); if(req->skip) logmsg("... but will abort after %zu bytes", req->cl); break; } else if(strncasecompare("Transfer-Encoding: chunked", line, strlen("Transfer-Encoding: chunked"))) { /* chunked data coming in */ chunked = TRUE; } if(chunked) { if(strstr(req->reqbuf, "\r\n0\r\n\r\n")) /* end of chunks reached */ return 1; /* done */ else return 0; /* not done */ } line = strchr(line, '\n'); if(line) line++; } while(line); if(!req->auth && strstr(req->reqbuf, "Authorization:")) { req->auth = TRUE; /* Authorization: header present! */ if(req->auth_req) logmsg("Authorization header found, as required"); } if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) { /* If the client is passing this Digest-header, we set the part number to 1000. Not only to spice up the complexity of this, but to make Digest stuff to work in the test suite. */ req->partno += 1000; req->digest = TRUE; /* header found */ logmsg("Received Digest request, sending back data %ld", req->partno); } else if(!req->ntlm && strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) { /* If the client is passing this type-3 NTLM header */ req->partno += 1002; req->ntlm = TRUE; /* NTLM found */ logmsg("Received NTLM type-3, sending back data %ld", req->partno); if(req->cl) { logmsg(" Expecting %zu POSTed bytes", req->cl); } } else if(!req->ntlm && strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) { /* If the client is passing this type-1 NTLM header */ req->partno += 1001; req->ntlm = TRUE; /* NTLM found */ logmsg("Received NTLM type-1, sending back data %ld", req->partno); } else if((req->partno >= 1000) && strstr(req->reqbuf, "Authorization: Basic")) { /* If the client is passing this Basic-header and the part number is already >=1000, we add 1 to the part number. This allows simple Basic authentication negotiation to work in the test suite. */ req->partno += 1; logmsg("Received Basic request, sending back data %ld", req->partno); } if(strstr(req->reqbuf, "Connection: close")) req->open = FALSE; /* close connection after this request */ if(!req->pipe && req->open && req->prot_version >= 11 && req->reqbuf + req->offset > end + strlen(END_OF_HEADERS) && (!strncmp(req->reqbuf, "GET", strlen("GET")) || !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) { /* If we have a persistent connection, HTTP version >= 1.1 and GET/HEAD request, enable pipelining. */ req->checkindex = (end - req->reqbuf) + strlen(END_OF_HEADERS); req->pipelining = TRUE; } while(req->pipe) { if(got_exit_signal) return 1; /* done */ /* scan for more header ends within this chunk */ line = &req->reqbuf[req->checkindex]; end = strstr(line, END_OF_HEADERS); if(!end) break; req->checkindex += (end - line) + strlen(END_OF_HEADERS); req->pipe--; } /* If authentication is required and no auth was provided, end now. This makes the server NOT wait for PUT/POST data and you can then make the test case send a rejection before any such data has been sent. Test case 154 uses this.*/ if(req->auth_req && !req->auth) return 1; /* done */ if(req->cl > 0) { if(req->cl <= req->offset - (end - req->reqbuf) - strlen(END_OF_HEADERS)) return 1; /* done */ else return 0; /* not complete yet */ } return 1; /* done */ } /* store the entire request in a file */ static void storerequest(char *reqbuf, size_t totalsize) { int res; int error = 0; size_t written; size_t writeleft; FILE *dump; if(!reqbuf) return; if(totalsize == 0) return; do { dump = fopen(REQUEST_DUMP, "ab"); } while(!dump && ((error = errno) == EINTR)); if(!dump) { logmsg("Error opening file %s error: %d %s", REQUEST_DUMP, error, strerror(error)); logmsg("Failed to write request input to " REQUEST_DUMP); return; } writeleft = totalsize; do { written = fwrite(&reqbuf[totalsize-writeleft], 1, writeleft, dump); if(got_exit_signal) goto storerequest_cleanup; if(written > 0) writeleft -= written; } while((writeleft > 0) && ((error = errno) == EINTR)); if(writeleft == 0) logmsg("Wrote request (%zu bytes) input to " REQUEST_DUMP, totalsize); else if(writeleft > 0) { logmsg("Error writing file %s error: %d %s", REQUEST_DUMP, error, strerror(error)); logmsg("Wrote only (%zu bytes) of (%zu bytes) request input to %s", totalsize-writeleft, totalsize, REQUEST_DUMP); } storerequest_cleanup: do { res = fclose(dump); } while(res && ((error = errno) == EINTR)); if(res) logmsg("Error closing file %s error: %d %s", REQUEST_DUMP, error, strerror(error)); } /* return 0 on success, non-zero on failure */ static int get_request(curl_socket_t sock, struct httprequest *req) { int error; int fail = 0; int done_processing = 0; char *reqbuf = req->reqbuf; ssize_t got = 0; char *pipereq = NULL; size_t pipereq_length = 0; if(req->pipelining) { pipereq = reqbuf + req->checkindex; pipereq_length = req->offset - req->checkindex; } /*** Init the httprequest structure properly for the upcoming request ***/ req->checkindex = 0; req->offset = 0; req->testno = DOCNUMBER_NOTHING; req->partno = 0; req->open = TRUE; req->auth_req = FALSE; req->auth = FALSE; req->cl = 0; req->digest = FALSE; req->ntlm = FALSE; req->pipe = 0; req->skip = 0; req->rcmd = RCMD_NORMALREQ; req->protocol = RPROT_NONE; req->prot_version = 0; req->pipelining = FALSE; req->rtp_buffer = NULL; req->rtp_buffersize = 0; /*** end of httprequest init ***/ while(!done_processing && (req->offset < REQBUFSIZ-1)) { if(pipereq_length && pipereq) { memmove(reqbuf, pipereq, pipereq_length); got = curlx_uztosz(pipereq_length); pipereq_length = 0; } else { if(req->skip) /* we are instructed to not read the entire thing, so we make sure to only read what we're supposed to and NOT read the enire thing the client wants to send! */ got = sread(sock, reqbuf + req->offset, req->cl); else got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset); } if(got_exit_signal) return 1; if(got == 0) { logmsg("Connection closed by client"); fail = 1; } else if(got < 0) { error = SOCKERRNO; logmsg("recv() returned error: (%d) %s", error, strerror(error)); fail = 1; } if(fail) { /* dump the request received so far to the external file */ reqbuf[req->offset] = '\0'; storerequest(reqbuf, req->offset); return 1; } logmsg("Read %zd bytes", got); req->offset += (size_t)got; reqbuf[req->offset] = '\0'; done_processing = ProcessRequest(req); if(got_exit_signal) return 1; if(done_processing && req->pipe) { logmsg("Waiting for another piped request"); done_processing = 0; req->pipe--; } } if((req->offset == REQBUFSIZ-1) && (got > 0)) { logmsg("Request would overflow buffer, closing connection"); /* dump request received so far to external file anyway */ reqbuf[REQBUFSIZ-1] = '\0'; fail = 1; } else if(req->offset > REQBUFSIZ-1) { logmsg("Request buffer overflow, closing connection"); /* dump request received so far to external file anyway */ reqbuf[REQBUFSIZ-1] = '\0'; fail = 1; } else reqbuf[req->offset] = '\0'; /* dump the request to an external file */ storerequest(reqbuf, req->pipelining ? req->checkindex : req->offset); if(got_exit_signal) return 1; return fail; /* return 0 on success */ } /* returns -1 on failure */ static int send_doc(curl_socket_t sock, struct httprequest *req) { ssize_t written; size_t count; const char *buffer; char *ptr = NULL; char *cmd = NULL; size_t cmdsize = 0; FILE *dump; bool persistent = TRUE; bool sendfailure = FALSE; size_t responsesize; int error = 0; int res; static char weare[256]; logmsg("Send response number %ld part %ld", req->testno, req->partno); switch(req->rcmd) { default: case RCMD_NORMALREQ: break; /* continue with business as usual */ case RCMD_STREAM: #define STREAMTHIS "a string to stream 01234567890\n" count = strlen(STREAMTHIS); for(;;) { written = swrite(sock, STREAMTHIS, count); if(got_exit_signal) return -1; if(written != (ssize_t)count) { logmsg("Stopped streaming"); break; } } return -1; case RCMD_IDLE: /* Do nothing. Sit idle. Pretend it rains. */ return 0; } req->open = FALSE; if(req->testno < 0) { size_t msglen; char msgbuf[64]; switch(req->testno) { case DOCNUMBER_QUIT: logmsg("Replying to QUIT"); buffer = docquit; break; case DOCNUMBER_WERULEZ: /* we got a "friends?" question, reply back that we sure are */ logmsg("Identifying ourselves as friends"); msnprintf(msgbuf, sizeof(msgbuf), "RTSP_SERVER WE ROOLZ: %" CURL_FORMAT_CURL_OFF_T "\r\n", our_getpid()); msglen = strlen(msgbuf); msnprintf(weare, sizeof(weare), "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s", msglen, msgbuf); buffer = weare; break; case DOCNUMBER_INTERNAL: logmsg("Bailing out due to internal error"); return -1; case DOCNUMBER_CONNECT: logmsg("Replying to CONNECT"); buffer = docconnect; break; case DOCNUMBER_BADCONNECT: logmsg("Replying to a bad CONNECT"); buffer = docbadconnect; break; case DOCNUMBER_404: default: logmsg("Replying to with a 404"); if(req->protocol == RPROT_HTTP) { buffer = doc404_HTTP; } else { buffer = doc404_RTSP; } break; } count = strlen(buffer); } else { FILE *stream = test2fopen(req->testno); char partbuf[80]="data"; if(0 != req->partno) msnprintf(partbuf, sizeof(partbuf), "data%ld", req->partno); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Couldn't open test file"); return 0; } else { error = getpart(&ptr, &count, "reply", partbuf, stream); fclose(stream); if(error) { logmsg("getpart() failed with error: %d", error); return 0; } buffer = ptr; } if(got_exit_signal) { free(ptr); return -1; } /* re-open the same file again */ stream = test2fopen(req->testno); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Couldn't open test file"); free(ptr); return 0; } else { /* get the custom server control "commands" */ error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream); fclose(stream); if(error) { logmsg("getpart() failed with error: %d", error); free(ptr); return 0; } } } if(got_exit_signal) { free(ptr); free(cmd); return -1; } /* If the word 'swsclose' is present anywhere in the reply chunk, the connection will be closed after the data has been sent to the requesting client... */ if(strstr(buffer, "swsclose") || !count) { persistent = FALSE; logmsg("connection close instruction \"swsclose\" found in response"); } if(strstr(buffer, "swsbounce")) { prevbounce = TRUE; logmsg("enable \"swsbounce\" in the next request"); } else prevbounce = FALSE; dump = fopen(RESPONSE_DUMP, "ab"); if(!dump) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Error opening file: %s", RESPONSE_DUMP); logmsg("couldn't create logfile: " RESPONSE_DUMP); free(ptr); free(cmd); return -1; } responsesize = count; do { /* Ok, we send no more than 200 bytes at a time, just to make sure that larger chunks are split up so that the client will need to do multiple recv() calls to get it and thus we exercise that code better */ size_t num = count; if(num > 200) num = 200; written = swrite(sock, buffer, num); if(written < 0) { sendfailure = TRUE; break; } else { logmsg("Sent off %zd bytes", written); } /* write to file as well */ fwrite(buffer, 1, (size_t)written, dump); if(got_exit_signal) break; count -= written; buffer += written; } while(count>0); /* Send out any RTP data */ if(req->rtp_buffer) { logmsg("About to write %zu RTP bytes", req->rtp_buffersize); count = req->rtp_buffersize; do { size_t num = count; if(num > 200) num = 200; written = swrite(sock, req->rtp_buffer + (req->rtp_buffersize - count), num); if(written < 0) { sendfailure = TRUE; break; } count -= written; } while(count > 0); free(req->rtp_buffer); req->rtp_buffersize = 0; } do { res = fclose(dump); } while(res && ((error = errno) == EINTR)); if(res) logmsg("Error closing file %s error: %d %s", RESPONSE_DUMP, error, strerror(error)); if(got_exit_signal) { free(ptr); free(cmd); return -1; } if(sendfailure) { logmsg("Sending response failed. Only (%zu bytes) of " "(%zu bytes) were sent", responsesize-count, responsesize); free(ptr); free(cmd); return -1; } logmsg("Response sent (%zu bytes) and written to " RESPONSE_DUMP, responsesize); free(ptr); if(cmdsize > 0) { char command[32]; int quarters; int num; ptr = cmd; do { if(2 == sscanf(ptr, "%31s %d", command, &num)) { if(!strcmp("wait", command)) { logmsg("Told to sleep for %d seconds", num); quarters = num * 4; while(quarters > 0) { quarters--; res = wait_ms(250); if(got_exit_signal) break; if(res) { /* should not happen */ error = errno; logmsg("wait_ms() failed with error: (%d) %s", error, strerror(error)); break; } } if(!quarters) logmsg("Continuing after sleeping %d seconds", num); } else logmsg("Unknown command in reply command section"); } ptr = strchr(ptr, '\n'); if(ptr) ptr++; else ptr = NULL; } while(ptr && *ptr); } free(cmd); req->open = persistent; prevtestno = req->testno; prevpartno = req->partno; return 0; } int main(int argc, char *argv[]) { srvr_sockaddr_union_t me; curl_socket_t sock = CURL_SOCKET_BAD; curl_socket_t msgsock = CURL_SOCKET_BAD; int wrotepidfile = 0; int wroteportfile = 0; int flag; unsigned short port = DEFAULT_PORT; const char *pidname = ".rtsp.pid"; const char *portname = NULL; /* none by default */ struct httprequest req; int rc; int error; int arg = 1; memset(&req, 0, sizeof(req)); while(argc>arg) { if(!strcmp("--version", argv[arg])) { printf("rtspd IPv4%s" "\n" , #ifdef ENABLE_IPV6 "/IPv6" #else "" #endif ); return 0; } else if(!strcmp("--pidfile", argv[arg])) { arg++; if(argc>arg) pidname = argv[arg++]; } else if(!strcmp("--portfile", argv[arg])) { arg++; if(argc>arg) portname = argv[arg++]; } else if(!strcmp("--logfile", argv[arg])) { arg++; if(argc>arg) serverlogfile = argv[arg++]; } else if(!strcmp("--ipv4", argv[arg])) { #ifdef ENABLE_IPV6 ipv_inuse = "IPv4"; use_ipv6 = FALSE; #endif arg++; } else if(!strcmp("--ipv6", argv[arg])) { #ifdef ENABLE_IPV6 ipv_inuse = "IPv6"; use_ipv6 = TRUE; #endif arg++; } else if(!strcmp("--port", argv[arg])) { arg++; if(argc>arg) { char *endptr; unsigned long ulnum = strtoul(argv[arg], &endptr, 10); port = curlx_ultous(ulnum); arg++; } } else if(!strcmp("--srcdir", argv[arg])) { arg++; if(argc>arg) { path = argv[arg]; arg++; } } else { puts("Usage: rtspd [option]\n" " --version\n" " --logfile [file]\n" " --pidfile [file]\n" " --portfile [file]\n" " --ipv4\n" " --ipv6\n" " --port [port]\n" " --srcdir [path]"); return 0; } } #ifdef WIN32 win32_init(); atexit(win32_cleanup); #endif install_signal_handlers(false); #ifdef ENABLE_IPV6 if(!use_ipv6) #endif sock = socket(AF_INET, SOCK_STREAM, 0); #ifdef ENABLE_IPV6 else sock = socket(AF_INET6, SOCK_STREAM, 0); #endif if(CURL_SOCKET_BAD == sock) { error = SOCKERRNO; logmsg("Error creating socket: (%d) %s", error, strerror(error)); goto server_cleanup; } flag = 1; if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, sizeof(flag))) { error = SOCKERRNO; logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", error, strerror(error)); goto server_cleanup; } #ifdef ENABLE_IPV6 if(!use_ipv6) { #endif memset(&me.sa4, 0, sizeof(me.sa4)); me.sa4.sin_family = AF_INET; me.sa4.sin_addr.s_addr = INADDR_ANY; me.sa4.sin_port = htons(port); rc = bind(sock, &me.sa, sizeof(me.sa4)); #ifdef ENABLE_IPV6 } else { memset(&me.sa6, 0, sizeof(me.sa6)); me.sa6.sin6_family = AF_INET6; me.sa6.sin6_addr = in6addr_any; me.sa6.sin6_port = htons(port); rc = bind(sock, &me.sa, sizeof(me.sa6)); } #endif /* ENABLE_IPV6 */ if(0 != rc) { error = SOCKERRNO; logmsg("Error binding socket on port %hu: (%d) %s", port, error, strerror(error)); goto server_cleanup; } if(!port) { /* The system was supposed to choose a port number, figure out which port we actually got and update the listener port value with it. */ curl_socklen_t la_size; srvr_sockaddr_union_t localaddr; #ifdef ENABLE_IPV6 if(!use_ipv6) #endif la_size = sizeof(localaddr.sa4); #ifdef ENABLE_IPV6 else la_size = sizeof(localaddr.sa6); #endif memset(&localaddr.sa, 0, (size_t)la_size); if(getsockname(sock, &localaddr.sa, &la_size) < 0) { error = SOCKERRNO; logmsg("getsockname() failed with error: (%d) %s", error, strerror(error)); sclose(sock); goto server_cleanup; } switch(localaddr.sa.sa_family) { case AF_INET: port = ntohs(localaddr.sa4.sin_port); break; #ifdef ENABLE_IPV6 case AF_INET6: port = ntohs(localaddr.sa6.sin6_port); break; #endif default: break; } if(!port) { /* Real failure, listener port shall not be zero beyond this point. */ logmsg("Apparently getsockname() succeeded, with listener port zero."); logmsg("A valid reason for this failure is a binary built without"); logmsg("proper network library linkage. This might not be the only"); logmsg("reason, but double check it before anything else."); sclose(sock); goto server_cleanup; } } logmsg("Running %s version on port %d", ipv_inuse, (int)port); /* start accepting connections */ rc = listen(sock, 5); if(0 != rc) { error = SOCKERRNO; logmsg("listen() failed with error: (%d) %s", error, strerror(error)); goto server_cleanup; } /* ** As soon as this server writes its pid file the test harness will ** attempt to connect to this server and initiate its verification. */ wrotepidfile = write_pidfile(pidname); if(!wrotepidfile) goto server_cleanup; if(portname) { wroteportfile = write_portfile(portname, port); if(!wroteportfile) goto server_cleanup; } for(;;) { msgsock = accept(sock, NULL, NULL); if(got_exit_signal) break; if(CURL_SOCKET_BAD == msgsock) { error = SOCKERRNO; logmsg("MAJOR ERROR: accept() failed with error: (%d) %s", error, strerror(error)); break; } /* ** As soon as this server acepts a connection from the test harness it ** must set the server logs advisor read lock to indicate that server ** logs should not be read until this lock is removed by this server. */ set_advisor_read_lock(SERVERLOGS_LOCK); serverlogslocked = 1; logmsg("====> Client connect"); #ifdef TCP_NODELAY /* * Disable the Nagle algorithm to make it easier to send out a large * response in many small segments to torture the clients more. */ flag = 1; if(setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY, (void *)&flag, sizeof(flag)) == -1) { logmsg("====> TCP_NODELAY failed"); } #endif /* initialization of httprequest struct is done in get_request(), but due to pipelining treatment the pipelining struct field must be initialized previously to FALSE every time a new connection arrives. */ req.pipelining = FALSE; do { if(got_exit_signal) break; if(get_request(msgsock, &req)) /* non-zero means error, break out of loop */ break; if(prevbounce) { /* bounce treatment requested */ if((req.testno == prevtestno) && (req.partno == prevpartno)) { req.partno++; logmsg("BOUNCE part number to %ld", req.partno); } else { prevbounce = FALSE; prevtestno = -1; prevpartno = -1; } } send_doc(msgsock, &req); if(got_exit_signal) break; if((req.testno < 0) && (req.testno != DOCNUMBER_CONNECT)) { logmsg("special request received, no persistency"); break; } if(!req.open) { logmsg("instructed to close connection after server-reply"); break; } if(req.open) logmsg("=> persistent connection request ended, awaits new request"); /* if we got a CONNECT, loop and get another request as well! */ } while(req.open || (req.testno == DOCNUMBER_CONNECT)); if(got_exit_signal) break; logmsg("====> Client disconnect"); sclose(msgsock); msgsock = CURL_SOCKET_BAD; if(serverlogslocked) { serverlogslocked = 0; clear_advisor_read_lock(SERVERLOGS_LOCK); } if(req.testno == DOCNUMBER_QUIT) break; } server_cleanup: if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD)) sclose(msgsock); if(sock != CURL_SOCKET_BAD) sclose(sock); if(got_exit_signal) logmsg("signalled to die"); if(wrotepidfile) unlink(pidname); if(wroteportfile) unlink(portname); if(serverlogslocked) { serverlogslocked = 0; clear_advisor_read_lock(SERVERLOGS_LOCK); } restore_signal_handlers(false); if(got_exit_signal) { logmsg("========> %s rtspd (port: %d pid: %ld) exits with signal (%d)", ipv_inuse, (int)port, (long)getpid(), exit_signal); /* * To properly set the return status of the process we * must raise the same signal SIGINT or SIGTERM that we * caught and let the old handler take care of it. */ raise(exit_signal); } logmsg("========> rtspd quits"); return 0; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/sockfilt.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" /* Purpose * * 1. Accept a TCP connection on a custom port (IPv4 or IPv6), or connect * to a given (localhost) port. * * 2. Get commands on STDIN. Pass data on to the TCP stream. * Get data from TCP stream and pass on to STDOUT. * * This program is made to perform all the socket/stream/connection stuff for * the test suite's (perl) FTP server. Previously the perl code did all of * this by its own, but I decided to let this program do the socket layer * because of several things: * * o We want the perl code to work with rather old perl installations, thus * we cannot use recent perl modules or features. * * o We want IPv6 support for systems that provide it, and doing optional IPv6 * support in perl seems if not impossible so at least awkward. * * o We want FTP-SSL support, which means that a connection that starts with * plain sockets needs to be able to "go SSL" in the midst. This would also * require some nasty perl stuff I'd rather avoid. * * (Source originally based on sws.c) */ /* * Signal handling notes for sockfilt * ---------------------------------- * * This program is a single-threaded process. * * This program is intended to be highly portable and as such it must be kept * as simple as possible, due to this the only signal handling mechanisms used * will be those of ANSI C, and used only in the most basic form which is good * enough for the purpose of this program. * * For the above reason and the specific needs of this program signals SIGHUP, * SIGPIPE and SIGALRM will be simply ignored on systems where this can be * done. If possible, signals SIGINT and SIGTERM will be handled by this * program as an indication to cleanup and finish execution as soon as * possible. This will be achieved with a single signal handler * 'exit_signal_handler' for both signals. * * The 'exit_signal_handler' upon the first SIGINT or SIGTERM received signal * will just set to one the global var 'got_exit_signal' storing in global var * 'exit_signal' the signal that triggered this change. * * Nothing fancy that could introduce problems is used, the program at certain * points in its normal flow checks if var 'got_exit_signal' is set and in * case this is true it just makes its way out of loops and functions in * structured and well behaved manner to achieve proper program cleanup and * termination. * * Even with the above mechanism implemented it is worthwhile to note that * other signals might still be received, or that there might be systems on * which it is not possible to trap and ignore some of the above signals. * This implies that for increased portability and reliability the program * must be coded as if no signal was being ignored or handled at all. Enjoy * it! */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ #include "getpart.h" #include "inet_pton.h" #include "util.h" #include "server_sockaddr.h" #include "warnless.h" /* include memdebug.h last */ #include "memdebug.h" #ifdef USE_WINSOCK #undef EINTR #define EINTR 4 /* errno.h value */ #undef EAGAIN #define EAGAIN 11 /* errno.h value */ #undef ENOMEM #define ENOMEM 12 /* errno.h value */ #undef EINVAL #define EINVAL 22 /* errno.h value */ #endif #define DEFAULT_PORT 8999 #ifndef DEFAULT_LOGFILE #define DEFAULT_LOGFILE "log/sockfilt.log" #endif const char *serverlogfile = DEFAULT_LOGFILE; static bool verbose = FALSE; static bool bind_only = FALSE; #ifdef ENABLE_IPV6 static bool use_ipv6 = FALSE; #endif static const char *ipv_inuse = "IPv4"; static unsigned short port = DEFAULT_PORT; static unsigned short connectport = 0; /* if non-zero, we activate this mode */ enum sockmode { PASSIVE_LISTEN, /* as a server waiting for connections */ PASSIVE_CONNECT, /* as a server, connected to a client */ ACTIVE, /* as a client, connected to a server */ ACTIVE_DISCONNECT /* as a client, disconnected from server */ }; #ifdef WIN32 /* * read-wrapper to support reading from stdin on Windows. */ static ssize_t read_wincon(int fd, void *buf, size_t count) { HANDLE handle = NULL; DWORD mode, rcount = 0; BOOL success; if(fd == fileno(stdin)) { handle = GetStdHandle(STD_INPUT_HANDLE); } else { return read(fd, buf, count); } if(GetConsoleMode(handle, &mode)) { success = ReadConsole(handle, buf, curlx_uztoul(count), &rcount, NULL); } else { success = ReadFile(handle, buf, curlx_uztoul(count), &rcount, NULL); } if(success) { return rcount; } errno = GetLastError(); return -1; } #undef read #define read(a,b,c) read_wincon(a,b,c) /* * write-wrapper to support writing to stdout and stderr on Windows. */ static ssize_t write_wincon(int fd, const void *buf, size_t count) { HANDLE handle = NULL; DWORD mode, wcount = 0; BOOL success; if(fd == fileno(stdout)) { handle = GetStdHandle(STD_OUTPUT_HANDLE); } else if(fd == fileno(stderr)) { handle = GetStdHandle(STD_ERROR_HANDLE); } else { return write(fd, buf, count); } if(GetConsoleMode(handle, &mode)) { success = WriteConsole(handle, buf, curlx_uztoul(count), &wcount, NULL); } else { success = WriteFile(handle, buf, curlx_uztoul(count), &wcount, NULL); } if(success) { return wcount; } errno = GetLastError(); return -1; } #undef write #define write(a,b,c) write_wincon(a,b,c) #endif /* * fullread is a wrapper around the read() function. This will repeat the call * to read() until it actually has read the complete number of bytes indicated * in nbytes or it fails with a condition that cannot be handled with a simple * retry of the read call. */ static ssize_t fullread(int filedes, void *buffer, size_t nbytes) { int error; ssize_t nread = 0; do { ssize_t rc = read(filedes, (unsigned char *)buffer + nread, nbytes - nread); if(got_exit_signal) { logmsg("signalled to die"); return -1; } if(rc < 0) { error = errno; if((error == EINTR) || (error == EAGAIN)) continue; logmsg("reading from file descriptor: %d,", filedes); logmsg("unrecoverable read() failure: (%d) %s", error, strerror(error)); return -1; } if(rc == 0) { logmsg("got 0 reading from stdin"); return 0; } nread += rc; } while((size_t)nread < nbytes); if(verbose) logmsg("read %zd bytes", nread); return nread; } /* * fullwrite is a wrapper around the write() function. This will repeat the * call to write() until it actually has written the complete number of bytes * indicated in nbytes or it fails with a condition that cannot be handled * with a simple retry of the write call. */ static ssize_t fullwrite(int filedes, const void *buffer, size_t nbytes) { int error; ssize_t nwrite = 0; do { ssize_t wc = write(filedes, (const unsigned char *)buffer + nwrite, nbytes - nwrite); if(got_exit_signal) { logmsg("signalled to die"); return -1; } if(wc < 0) { error = errno; if((error == EINTR) || (error == EAGAIN)) continue; logmsg("writing to file descriptor: %d,", filedes); logmsg("unrecoverable write() failure: (%d) %s", error, strerror(error)); return -1; } if(wc == 0) { logmsg("put 0 writing to stdout"); return 0; } nwrite += wc; } while((size_t)nwrite < nbytes); if(verbose) logmsg("wrote %zd bytes", nwrite); return nwrite; } /* * read_stdin tries to read from stdin nbytes into the given buffer. This is a * blocking function that will only return TRUE when nbytes have actually been * read or FALSE when an unrecoverable error has been detected. Failure of this * function is an indication that the sockfilt process should terminate. */ static bool read_stdin(void *buffer, size_t nbytes) { ssize_t nread = fullread(fileno(stdin), buffer, nbytes); if(nread != (ssize_t)nbytes) { logmsg("exiting..."); return FALSE; } return TRUE; } /* * write_stdout tries to write to stdio nbytes from the given buffer. This is a * blocking function that will only return TRUE when nbytes have actually been * written or FALSE when an unrecoverable error has been detected. Failure of * this function is an indication that the sockfilt process should terminate. */ static bool write_stdout(const void *buffer, size_t nbytes) { ssize_t nwrite = fullwrite(fileno(stdout), buffer, nbytes); if(nwrite != (ssize_t)nbytes) { logmsg("exiting..."); return FALSE; } return TRUE; } static void lograw(unsigned char *buffer, ssize_t len) { char data[120]; ssize_t i; unsigned char *ptr = buffer; char *optr = data; ssize_t width = 0; int left = sizeof(data); for(i = 0; i<len; i++) { switch(ptr[i]) { case '\n': msnprintf(optr, left, "\\n"); width += 2; optr += 2; left -= 2; break; case '\r': msnprintf(optr, left, "\\r"); width += 2; optr += 2; left -= 2; break; default: msnprintf(optr, left, "%c", (ISGRAPH(ptr[i]) || ptr[i] == 0x20) ?ptr[i]:'.'); width++; optr++; left--; break; } if(width>60) { logmsg("'%s'", data); width = 0; optr = data; left = sizeof(data); } } if(width) logmsg("'%s'", data); } #ifdef USE_WINSOCK /* * WinSock select() does not support standard file descriptors, * it can only check SOCKETs. The following function is an attempt * to re-create a select() function with support for other handle types. * * select() function with support for WINSOCK2 sockets and all * other handle types supported by WaitForMultipleObjectsEx() as * well as disk files, anonymous and names pipes, and character input. * * https://msdn.microsoft.com/en-us/library/windows/desktop/ms687028.aspx * https://msdn.microsoft.com/en-us/library/windows/desktop/ms741572.aspx */ struct select_ws_wait_data { HANDLE handle; /* actual handle to wait for during select */ HANDLE signal; /* internal event to signal handle trigger */ HANDLE abort; /* internal event to abort waiting thread */ HANDLE mutex; /* mutex to prevent event race-condition */ }; static DWORD WINAPI select_ws_wait_thread(LPVOID lpParameter) { struct select_ws_wait_data *data; HANDLE mutex, signal, handle, handles[2]; INPUT_RECORD inputrecord; LARGE_INTEGER size, pos; DWORD type, length, ret; /* retrieve handles from internal structure */ data = (struct select_ws_wait_data *) lpParameter; if(data) { handle = data->handle; handles[0] = data->abort; handles[1] = handle; signal = data->signal; mutex = data->mutex; free(data); } else return (DWORD)-1; /* retrieve the type of file to wait on */ type = GetFileType(handle); switch(type) { case FILE_TYPE_DISK: /* The handle represents a file on disk, this means: * - WaitForMultipleObjectsEx will always be signalled for it. * - comparison of current position in file and total size of * the file can be used to check if we reached the end yet. * * Approach: Loop till either the internal event is signalled * or if the end of the file has already been reached. */ while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE) == WAIT_TIMEOUT) { ret = WaitForSingleObjectEx(mutex, 0, FALSE); if(ret == WAIT_OBJECT_0) { /* get total size of file */ length = 0; size.QuadPart = 0; size.LowPart = GetFileSize(handle, &length); if((size.LowPart != INVALID_FILE_SIZE) || (GetLastError() == NO_ERROR)) { size.HighPart = length; /* get the current position within the file */ pos.QuadPart = 0; pos.LowPart = SetFilePointer(handle, 0, &pos.HighPart, FILE_CURRENT); if((pos.LowPart != INVALID_SET_FILE_POINTER) || (GetLastError() == NO_ERROR)) { /* compare position with size, abort if not equal */ if(size.QuadPart == pos.QuadPart) { /* sleep and continue waiting */ SleepEx(0, FALSE); ReleaseMutex(mutex); continue; } } } /* there is some data available, stop waiting */ logmsg("[select_ws_wait_thread] data available, DISK: %p", handle); SetEvent(signal); ReleaseMutex(mutex); break; } else if(ret == WAIT_ABANDONED) { /* we are not allowed to process this event, because select_ws is post-processing the signalled events and we must exit. */ break; } } break; case FILE_TYPE_CHAR: /* The handle represents a character input, this means: * - WaitForMultipleObjectsEx will be signalled on any kind of input, * including mouse and window size events we do not care about. * * Approach: Loop till either the internal event is signalled * or we get signalled for an actual key-event. */ while(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE) == WAIT_OBJECT_0 + 1) { ret = WaitForSingleObjectEx(mutex, 0, FALSE); if(ret == WAIT_OBJECT_0) { /* check if this is an actual console handle */ if(GetConsoleMode(handle, &ret)) { /* retrieve an event from the console buffer */ length = 0; if(PeekConsoleInput(handle, &inputrecord, 1, &length)) { /* check if the event is not an actual key-event */ if(length == 1 && inputrecord.EventType != KEY_EVENT) { /* purge the non-key-event and continue waiting */ ReadConsoleInput(handle, &inputrecord, 1, &length); ReleaseMutex(mutex); continue; } } } /* there is some data available, stop waiting */ logmsg("[select_ws_wait_thread] data available, CHAR: %p", handle); SetEvent(signal); ReleaseMutex(mutex); break; } else if(ret == WAIT_ABANDONED) { /* we are not allowed to process this event, because select_ws is post-processing the signalled events and we must exit. */ break; } } break; case FILE_TYPE_PIPE: /* The handle represents an anonymous or named pipe, this means: * - WaitForMultipleObjectsEx will always be signalled for it. * - peek into the pipe and retrieve the amount of data available. * * Approach: Loop till either the internal event is signalled * or there is data in the pipe available for reading. */ while(WaitForMultipleObjectsEx(1, handles, FALSE, 0, FALSE) == WAIT_TIMEOUT) { ret = WaitForSingleObjectEx(mutex, 0, FALSE); if(ret == WAIT_OBJECT_0) { /* peek into the pipe and retrieve the amount of data available */ length = 0; if(PeekNamedPipe(handle, NULL, 0, NULL, &length, NULL)) { /* if there is no data available, sleep and continue waiting */ if(length == 0) { SleepEx(0, FALSE); ReleaseMutex(mutex); continue; } else { logmsg("[select_ws_wait_thread] PeekNamedPipe len: %d", length); } } else { /* if the pipe has NOT been closed, sleep and continue waiting */ ret = GetLastError(); if(ret != ERROR_BROKEN_PIPE) { logmsg("[select_ws_wait_thread] PeekNamedPipe error: %d", ret); SleepEx(0, FALSE); ReleaseMutex(mutex); continue; } else { logmsg("[select_ws_wait_thread] pipe closed, PIPE: %p", handle); } } /* there is some data available, stop waiting */ logmsg("[select_ws_wait_thread] data available, PIPE: %p", handle); SetEvent(signal); ReleaseMutex(mutex); break; } else if(ret == WAIT_ABANDONED) { /* we are not allowed to process this event, because select_ws is post-processing the signalled events and we must exit. */ break; } } break; default: /* The handle has an unknown type, try to wait on it */ if(WaitForMultipleObjectsEx(2, handles, FALSE, INFINITE, FALSE) == WAIT_OBJECT_0 + 1) { if(WaitForSingleObjectEx(mutex, 0, FALSE) == WAIT_OBJECT_0) { logmsg("[select_ws_wait_thread] data available, HANDLE: %p", handle); SetEvent(signal); ReleaseMutex(mutex); } } break; } return 0; } static HANDLE select_ws_wait(HANDLE handle, HANDLE signal, HANDLE abort, HANDLE mutex) { struct select_ws_wait_data *data; HANDLE thread = NULL; /* allocate internal waiting data structure */ data = malloc(sizeof(struct select_ws_wait_data)); if(data) { data->handle = handle; data->signal = signal; data->abort = abort; data->mutex = mutex; /* launch waiting thread */ thread = CreateThread(NULL, 0, &select_ws_wait_thread, data, 0, NULL); /* free data if thread failed to launch */ if(!thread) { free(data); } } return thread; } struct select_ws_data { int fd; /* provided file descriptor (indexed by nfd) */ long wsastate; /* internal pre-select state (indexed by nfd) */ curl_socket_t wsasock; /* internal socket handle (indexed by nws) */ WSAEVENT wsaevent; /* internal select event (indexed by nws) */ HANDLE signal; /* internal thread signal (indexed by nth) */ HANDLE thread; /* internal thread handle (indexed by nth) */ }; static int select_ws(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *tv) { HANDLE abort, mutex, signal, handle, *handles; DWORD timeout_ms, wait, nfd, nth, nws, i; fd_set readsock, writesock, exceptsock; struct select_ws_data *data; WSANETWORKEVENTS wsaevents; curl_socket_t wsasock; int error, ret, fd; WSAEVENT wsaevent; /* check if the input value is valid */ if(nfds < 0) { errno = EINVAL; return -1; } /* convert struct timeval to milliseconds */ if(tv) { timeout_ms = (tv->tv_sec*1000) + (DWORD)(((double)tv->tv_usec)/1000.0); } else { timeout_ms = INFINITE; } /* check if we got descriptors, sleep in case we got none */ if(!nfds) { SleepEx(timeout_ms, FALSE); return 0; } /* create internal event to abort waiting threads */ abort = CreateEvent(NULL, TRUE, FALSE, NULL); if(!abort) { errno = ENOMEM; return -1; } /* create internal mutex to lock event handling in threads */ mutex = CreateMutex(NULL, FALSE, NULL); if(!mutex) { CloseHandle(abort); errno = ENOMEM; return -1; } /* allocate internal array for the internal data */ data = calloc(nfds, sizeof(struct select_ws_data)); if(!data) { CloseHandle(abort); CloseHandle(mutex); errno = ENOMEM; return -1; } /* allocate internal array for the internal event handles */ handles = calloc(nfds + 1, sizeof(HANDLE)); if(!handles) { CloseHandle(abort); CloseHandle(mutex); free(data); errno = ENOMEM; return -1; } /* loop over the handles in the input descriptor sets */ nfd = 0; /* number of handled file descriptors */ nth = 0; /* number of internal waiting threads */ nws = 0; /* number of handled WINSOCK sockets */ for(fd = 0; fd < nfds; fd++) { wsasock = curlx_sitosk(fd); wsaevents.lNetworkEvents = 0; handles[nfd] = 0; FD_ZERO(&readsock); FD_ZERO(&writesock); FD_ZERO(&exceptsock); if(FD_ISSET(wsasock, readfds)) { FD_SET(wsasock, &readsock); wsaevents.lNetworkEvents |= FD_READ|FD_ACCEPT|FD_CLOSE; } if(FD_ISSET(wsasock, writefds)) { FD_SET(wsasock, &writesock); wsaevents.lNetworkEvents |= FD_WRITE|FD_CONNECT|FD_CLOSE; } if(FD_ISSET(wsasock, exceptfds)) { FD_SET(wsasock, &exceptsock); wsaevents.lNetworkEvents |= FD_OOB; } /* only wait for events for which we actually care */ if(wsaevents.lNetworkEvents) { data[nfd].fd = fd; if(fd == fileno(stdin)) { signal = CreateEvent(NULL, TRUE, FALSE, NULL); if(signal) { handle = GetStdHandle(STD_INPUT_HANDLE); handle = select_ws_wait(handle, signal, abort, mutex); if(handle) { handles[nfd] = signal; data[nth].signal = signal; data[nth].thread = handle; nfd++; nth++; } else { CloseHandle(signal); } } } else if(fd == fileno(stdout)) { handles[nfd] = GetStdHandle(STD_OUTPUT_HANDLE); nfd++; } else if(fd == fileno(stderr)) { handles[nfd] = GetStdHandle(STD_ERROR_HANDLE); nfd++; } else { wsaevent = WSACreateEvent(); if(wsaevent != WSA_INVALID_EVENT) { if(wsaevents.lNetworkEvents & FD_WRITE) { send(wsasock, NULL, 0, 0); /* reset FD_WRITE */ } error = WSAEventSelect(wsasock, wsaevent, wsaevents.lNetworkEvents); if(error != SOCKET_ERROR) { handles[nfd] = (HANDLE)wsaevent; data[nws].wsasock = wsasock; data[nws].wsaevent = wsaevent; data[nfd].wsastate = 0; tv->tv_sec = 0; tv->tv_usec = 0; /* check if the socket is already ready */ if(select(fd + 1, &readsock, &writesock, &exceptsock, tv) == 1) { logmsg("[select_ws] socket %d is ready", fd); WSASetEvent(wsaevent); if(FD_ISSET(wsasock, &readsock)) data[nfd].wsastate |= FD_READ; if(FD_ISSET(wsasock, &writesock)) data[nfd].wsastate |= FD_WRITE; if(FD_ISSET(wsasock, &exceptsock)) data[nfd].wsastate |= FD_OOB; } nfd++; nws++; } else { WSACloseEvent(wsaevent); signal = CreateEvent(NULL, TRUE, FALSE, NULL); if(signal) { handle = (HANDLE)wsasock; handle = select_ws_wait(handle, signal, abort, mutex); if(handle) { handles[nfd] = signal; data[nth].signal = signal; data[nth].thread = handle; nfd++; nth++; } else { CloseHandle(signal); } } } } } } } /* wait on the number of handles */ wait = nfd; /* make sure we stop waiting on exit signal event */ if(exit_event) { /* we allocated handles nfds + 1 for this */ handles[nfd] = exit_event; wait += 1; } /* wait for one of the internal handles to trigger */ wait = WaitForMultipleObjectsEx(wait, handles, FALSE, timeout_ms, FALSE); /* wait for internal mutex to lock event handling in threads */ WaitForSingleObjectEx(mutex, INFINITE, FALSE); /* loop over the internal handles returned in the descriptors */ ret = 0; /* number of ready file descriptors */ for(i = 0; i < nfd; i++) { fd = data[i].fd; handle = handles[i]; wsasock = curlx_sitosk(fd); /* check if the current internal handle was triggered */ if(wait != WAIT_FAILED && (wait - WAIT_OBJECT_0) <= i && WaitForSingleObjectEx(handle, 0, FALSE) == WAIT_OBJECT_0) { /* first handle stdin, stdout and stderr */ if(fd == fileno(stdin)) { /* stdin is never ready for write or exceptional */ FD_CLR(wsasock, writefds); FD_CLR(wsasock, exceptfds); } else if(fd == fileno(stdout) || fd == fileno(stderr)) { /* stdout and stderr are never ready for read or exceptional */ FD_CLR(wsasock, readfds); FD_CLR(wsasock, exceptfds); } else { /* try to handle the event with the WINSOCK2 functions */ wsaevents.lNetworkEvents = 0; error = WSAEnumNetworkEvents(wsasock, handle, &wsaevents); if(error != SOCKET_ERROR) { /* merge result from pre-check using select */ wsaevents.lNetworkEvents |= data[i].wsastate; /* remove from descriptor set if not ready for read/accept/close */ if(!(wsaevents.lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE))) FD_CLR(wsasock, readfds); /* remove from descriptor set if not ready for write/connect */ if(!(wsaevents.lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE))) FD_CLR(wsasock, writefds); /* remove from descriptor set if not exceptional */ if(!(wsaevents.lNetworkEvents & FD_OOB)) FD_CLR(wsasock, exceptfds); } } /* check if the event has not been filtered using specific tests */ if(FD_ISSET(wsasock, readfds) || FD_ISSET(wsasock, writefds) || FD_ISSET(wsasock, exceptfds)) { ret++; } } else { /* remove from all descriptor sets since this handle did not trigger */ FD_CLR(wsasock, readfds); FD_CLR(wsasock, writefds); FD_CLR(wsasock, exceptfds); } } /* signal the event handle for the other waiting threads */ SetEvent(abort); for(fd = 0; fd < nfds; fd++) { if(FD_ISSET(fd, readfds)) logmsg("[select_ws] %d is readable", fd); if(FD_ISSET(fd, writefds)) logmsg("[select_ws] %d is writable", fd); if(FD_ISSET(fd, exceptfds)) logmsg("[select_ws] %d is exceptional", fd); } for(i = 0; i < nws; i++) { WSAEventSelect(data[i].wsasock, NULL, 0); WSACloseEvent(data[i].wsaevent); } for(i = 0; i < nth; i++) { WaitForSingleObjectEx(data[i].thread, INFINITE, FALSE); CloseHandle(data[i].thread); CloseHandle(data[i].signal); } CloseHandle(abort); CloseHandle(mutex); free(handles); free(data); return ret; } #define select(a,b,c,d,e) select_ws(a,b,c,d,e) #endif /* USE_WINSOCK */ /* sockfdp is a pointer to an established stream or CURL_SOCKET_BAD if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must accept() */ static bool juggle(curl_socket_t *sockfdp, curl_socket_t listenfd, enum sockmode *mode) { struct timeval timeout; fd_set fds_read; fd_set fds_write; fd_set fds_err; curl_socket_t sockfd = CURL_SOCKET_BAD; int maxfd = -99; ssize_t rc; int error = 0; /* 'buffer' is this excessively large only to be able to support things like test 1003 which tests exceedingly large server response lines */ unsigned char buffer[17010]; char data[16]; if(got_exit_signal) { logmsg("signalled to die, exiting..."); return FALSE; } #ifdef HAVE_GETPPID /* As a last resort, quit if sockfilt process becomes orphan. Just in case parent ftpserver process has died without killing its sockfilt children */ if(getppid() <= 1) { logmsg("process becomes orphan, exiting"); return FALSE; } #endif timeout.tv_sec = 120; timeout.tv_usec = 0; FD_ZERO(&fds_read); FD_ZERO(&fds_write); FD_ZERO(&fds_err); FD_SET((curl_socket_t)fileno(stdin), &fds_read); switch(*mode) { case PASSIVE_LISTEN: /* server mode */ sockfd = listenfd; /* there's always a socket to wait for */ FD_SET(sockfd, &fds_read); maxfd = (int)sockfd; break; case PASSIVE_CONNECT: sockfd = *sockfdp; if(CURL_SOCKET_BAD == sockfd) { /* eeek, we are supposedly connected and then this cannot be -1 ! */ logmsg("socket is -1! on %s:%d", __FILE__, __LINE__); maxfd = 0; /* stdin */ } else { /* there's always a socket to wait for */ FD_SET(sockfd, &fds_read); maxfd = (int)sockfd; } break; case ACTIVE: sockfd = *sockfdp; /* sockfd turns CURL_SOCKET_BAD when our connection has been closed */ if(CURL_SOCKET_BAD != sockfd) { FD_SET(sockfd, &fds_read); maxfd = (int)sockfd; } else { logmsg("No socket to read on"); maxfd = 0; } break; case ACTIVE_DISCONNECT: logmsg("disconnected, no socket to read on"); maxfd = 0; sockfd = CURL_SOCKET_BAD; break; } /* switch(*mode) */ do { /* select() blocking behavior call on blocking descriptors please */ rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, &timeout); if(got_exit_signal) { logmsg("signalled to die, exiting..."); return FALSE; } } while((rc == -1) && ((error = errno) == EINTR)); if(rc < 0) { logmsg("select() failed with error: (%d) %s", error, strerror(error)); return FALSE; } if(rc == 0) /* timeout */ return TRUE; if(FD_ISSET(fileno(stdin), &fds_read)) { ssize_t buffer_len; /* read from stdin, commands/data to be dealt with and possibly passed on to the socket protocol: 4 letter command + LF [mandatory] 4-digit hexadecimal data length + LF [if the command takes data] data [the data being as long as set above] Commands: DATA - plain pass-through data */ if(!read_stdin(buffer, 5)) return FALSE; logmsg("Received %c%c%c%c (on stdin)", buffer[0], buffer[1], buffer[2], buffer[3]); if(!memcmp("PING", buffer, 4)) { /* send reply on stdout, just proving we are alive */ if(!write_stdout("PONG\n", 5)) return FALSE; } else if(!memcmp("PORT", buffer, 4)) { /* Question asking us what PORT number we are listening to. Replies to PORT with "IPv[num]/[port]" */ msnprintf((char *)buffer, sizeof(buffer), "%s/%hu\n", ipv_inuse, port); buffer_len = (ssize_t)strlen((char *)buffer); msnprintf(data, sizeof(data), "PORT\n%04zx\n", buffer_len); if(!write_stdout(data, 10)) return FALSE; if(!write_stdout(buffer, buffer_len)) return FALSE; } else if(!memcmp("QUIT", buffer, 4)) { /* just die */ logmsg("quits"); return FALSE; } else if(!memcmp("DATA", buffer, 4)) { /* data IN => data OUT */ if(!read_stdin(buffer, 5)) return FALSE; buffer[5] = '\0'; buffer_len = (ssize_t)strtol((char *)buffer, NULL, 16); if(buffer_len > (ssize_t)sizeof(buffer)) { logmsg("ERROR: Buffer size (%zu bytes) too small for data size " "(%zd bytes)", sizeof(buffer), buffer_len); return FALSE; } logmsg("> %zd bytes data, server => client", buffer_len); if(!read_stdin(buffer, buffer_len)) return FALSE; lograw(buffer, buffer_len); if(*mode == PASSIVE_LISTEN) { logmsg("*** We are disconnected!"); if(!write_stdout("DISC\n", 5)) return FALSE; } else { /* send away on the socket */ ssize_t bytes_written = swrite(sockfd, buffer, buffer_len); if(bytes_written != buffer_len) { logmsg("Not all data was sent. Bytes to send: %zd sent: %zd", buffer_len, bytes_written); } } } else if(!memcmp("DISC", buffer, 4)) { /* disconnect! */ if(!write_stdout("DISC\n", 5)) return FALSE; if(sockfd != CURL_SOCKET_BAD) { logmsg("====> Client forcibly disconnected"); sclose(sockfd); *sockfdp = CURL_SOCKET_BAD; if(*mode == PASSIVE_CONNECT) *mode = PASSIVE_LISTEN; else *mode = ACTIVE_DISCONNECT; } else logmsg("attempt to close already dead connection"); return TRUE; } } if((sockfd != CURL_SOCKET_BAD) && (FD_ISSET(sockfd, &fds_read)) ) { ssize_t nread_socket; if(*mode == PASSIVE_LISTEN) { /* there's no stream set up yet, this is an indication that there's a client connecting. */ curl_socket_t newfd = accept(sockfd, NULL, NULL); if(CURL_SOCKET_BAD == newfd) { error = SOCKERRNO; logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s", sockfd, error, strerror(error)); } else { logmsg("====> Client connect"); if(!write_stdout("CNCT\n", 5)) return FALSE; *sockfdp = newfd; /* store the new socket */ *mode = PASSIVE_CONNECT; /* we have connected */ } return TRUE; } /* read from socket, pass on data to stdout */ nread_socket = sread(sockfd, buffer, sizeof(buffer)); if(nread_socket > 0) { msnprintf(data, sizeof(data), "DATA\n%04zx\n", nread_socket); if(!write_stdout(data, 10)) return FALSE; if(!write_stdout(buffer, nread_socket)) return FALSE; logmsg("< %zd bytes data, client => server", nread_socket); lograw(buffer, nread_socket); } if(nread_socket <= 0) { logmsg("====> Client disconnect"); if(!write_stdout("DISC\n", 5)) return FALSE; sclose(sockfd); *sockfdp = CURL_SOCKET_BAD; if(*mode == PASSIVE_CONNECT) *mode = PASSIVE_LISTEN; else *mode = ACTIVE_DISCONNECT; return TRUE; } } return TRUE; } static curl_socket_t sockdaemon(curl_socket_t sock, unsigned short *listenport) { /* passive daemon style */ srvr_sockaddr_union_t listener; int flag; int rc; int totdelay = 0; int maxretr = 10; int delay = 20; int attempt = 0; int error = 0; do { attempt++; flag = 1; rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, sizeof(flag)); if(rc) { error = SOCKERRNO; logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", error, strerror(error)); if(maxretr) { rc = wait_ms(delay); if(rc) { /* should not happen */ error = errno; logmsg("wait_ms() failed with error: (%d) %s", error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } if(got_exit_signal) { logmsg("signalled to die, exiting..."); sclose(sock); return CURL_SOCKET_BAD; } totdelay += delay; delay *= 2; /* double the sleep for next attempt */ } } } while(rc && maxretr--); if(rc) { logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s", attempt, totdelay, error, strerror(error)); logmsg("Continuing anyway..."); } /* When the specified listener port is zero, it is actually a request to let the system choose a non-zero available port. */ #ifdef ENABLE_IPV6 if(!use_ipv6) { #endif memset(&listener.sa4, 0, sizeof(listener.sa4)); listener.sa4.sin_family = AF_INET; listener.sa4.sin_addr.s_addr = INADDR_ANY; listener.sa4.sin_port = htons(*listenport); rc = bind(sock, &listener.sa, sizeof(listener.sa4)); #ifdef ENABLE_IPV6 } else { memset(&listener.sa6, 0, sizeof(listener.sa6)); listener.sa6.sin6_family = AF_INET6; listener.sa6.sin6_addr = in6addr_any; listener.sa6.sin6_port = htons(*listenport); rc = bind(sock, &listener.sa, sizeof(listener.sa6)); } #endif /* ENABLE_IPV6 */ if(rc) { error = SOCKERRNO; logmsg("Error binding socket on port %hu: (%d) %s", *listenport, error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } if(!*listenport) { /* The system was supposed to choose a port number, figure out which port we actually got and update the listener port value with it. */ curl_socklen_t la_size; srvr_sockaddr_union_t localaddr; #ifdef ENABLE_IPV6 if(!use_ipv6) #endif la_size = sizeof(localaddr.sa4); #ifdef ENABLE_IPV6 else la_size = sizeof(localaddr.sa6); #endif memset(&localaddr.sa, 0, (size_t)la_size); if(getsockname(sock, &localaddr.sa, &la_size) < 0) { error = SOCKERRNO; logmsg("getsockname() failed with error: (%d) %s", error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } switch(localaddr.sa.sa_family) { case AF_INET: *listenport = ntohs(localaddr.sa4.sin_port); break; #ifdef ENABLE_IPV6 case AF_INET6: *listenport = ntohs(localaddr.sa6.sin6_port); break; #endif default: break; } if(!*listenport) { /* Real failure, listener port shall not be zero beyond this point. */ logmsg("Apparently getsockname() succeeded, with listener port zero."); logmsg("A valid reason for this failure is a binary built without"); logmsg("proper network library linkage. This might not be the only"); logmsg("reason, but double check it before anything else."); sclose(sock); return CURL_SOCKET_BAD; } } /* bindonly option forces no listening */ if(bind_only) { logmsg("instructed to bind port without listening"); return sock; } /* start accepting connections */ rc = listen(sock, 5); if(0 != rc) { error = SOCKERRNO; logmsg("listen(%d, 5) failed with error: (%d) %s", sock, error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } return sock; } int main(int argc, char *argv[]) { srvr_sockaddr_union_t me; curl_socket_t sock = CURL_SOCKET_BAD; curl_socket_t msgsock = CURL_SOCKET_BAD; int wrotepidfile = 0; int wroteportfile = 0; const char *pidname = ".sockfilt.pid"; const char *portname = NULL; /* none by default */ bool juggle_again; int rc; int error; int arg = 1; enum sockmode mode = PASSIVE_LISTEN; /* default */ const char *addr = NULL; while(argc>arg) { if(!strcmp("--version", argv[arg])) { printf("sockfilt IPv4%s\n", #ifdef ENABLE_IPV6 "/IPv6" #else "" #endif ); return 0; } else if(!strcmp("--verbose", argv[arg])) { verbose = TRUE; arg++; } else if(!strcmp("--pidfile", argv[arg])) { arg++; if(argc>arg) pidname = argv[arg++]; } else if(!strcmp("--portfile", argv[arg])) { arg++; if(argc > arg) portname = argv[arg++]; } else if(!strcmp("--logfile", argv[arg])) { arg++; if(argc>arg) serverlogfile = argv[arg++]; } else if(!strcmp("--ipv6", argv[arg])) { #ifdef ENABLE_IPV6 ipv_inuse = "IPv6"; use_ipv6 = TRUE; #endif arg++; } else if(!strcmp("--ipv4", argv[arg])) { /* for completeness, we support this option as well */ #ifdef ENABLE_IPV6 ipv_inuse = "IPv4"; use_ipv6 = FALSE; #endif arg++; } else if(!strcmp("--bindonly", argv[arg])) { bind_only = TRUE; arg++; } else if(!strcmp("--port", argv[arg])) { arg++; if(argc>arg) { char *endptr; unsigned long ulnum = strtoul(argv[arg], &endptr, 10); port = curlx_ultous(ulnum); arg++; } } else if(!strcmp("--connect", argv[arg])) { /* Asked to actively connect to the specified local port instead of doing a passive server-style listening. */ arg++; if(argc>arg) { char *endptr; unsigned long ulnum = strtoul(argv[arg], &endptr, 10); if((endptr != argv[arg] + strlen(argv[arg])) || (ulnum < 1025UL) || (ulnum > 65535UL)) { fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n", argv[arg]); return 0; } connectport = curlx_ultous(ulnum); arg++; } } else if(!strcmp("--addr", argv[arg])) { /* Set an IP address to use with --connect; otherwise use localhost */ arg++; if(argc>arg) { addr = argv[arg]; arg++; } } else { puts("Usage: sockfilt [option]\n" " --version\n" " --verbose\n" " --logfile [file]\n" " --pidfile [file]\n" " --portfile [file]\n" " --ipv4\n" " --ipv6\n" " --bindonly\n" " --port [port]\n" " --connect [port]\n" " --addr [address]"); return 0; } } #ifdef WIN32 win32_init(); atexit(win32_cleanup); setmode(fileno(stdin), O_BINARY); setmode(fileno(stdout), O_BINARY); setmode(fileno(stderr), O_BINARY); #endif install_signal_handlers(false); #ifdef ENABLE_IPV6 if(!use_ipv6) #endif sock = socket(AF_INET, SOCK_STREAM, 0); #ifdef ENABLE_IPV6 else sock = socket(AF_INET6, SOCK_STREAM, 0); #endif if(CURL_SOCKET_BAD == sock) { error = SOCKERRNO; logmsg("Error creating socket: (%d) %s", error, strerror(error)); write_stdout("FAIL\n", 5); goto sockfilt_cleanup; } if(connectport) { /* Active mode, we should connect to the given port number */ mode = ACTIVE; #ifdef ENABLE_IPV6 if(!use_ipv6) { #endif memset(&me.sa4, 0, sizeof(me.sa4)); me.sa4.sin_family = AF_INET; me.sa4.sin_port = htons(connectport); me.sa4.sin_addr.s_addr = INADDR_ANY; if(!addr) addr = "127.0.0.1"; Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr); rc = connect(sock, &me.sa, sizeof(me.sa4)); #ifdef ENABLE_IPV6 } else { memset(&me.sa6, 0, sizeof(me.sa6)); me.sa6.sin6_family = AF_INET6; me.sa6.sin6_port = htons(connectport); if(!addr) addr = "::1"; Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr); rc = connect(sock, &me.sa, sizeof(me.sa6)); } #endif /* ENABLE_IPV6 */ if(rc) { error = SOCKERRNO; logmsg("Error connecting to port %hu: (%d) %s", connectport, error, strerror(error)); write_stdout("FAIL\n", 5); goto sockfilt_cleanup; } logmsg("====> Client connect"); msgsock = sock; /* use this as stream */ } else { /* passive daemon style */ sock = sockdaemon(sock, &port); if(CURL_SOCKET_BAD == sock) { write_stdout("FAIL\n", 5); goto sockfilt_cleanup; } msgsock = CURL_SOCKET_BAD; /* no stream socket yet */ } logmsg("Running %s version", ipv_inuse); if(connectport) logmsg("Connected to port %hu", connectport); else if(bind_only) logmsg("Bound without listening on port %hu", port); else logmsg("Listening on port %hu", port); wrotepidfile = write_pidfile(pidname); if(!wrotepidfile) { write_stdout("FAIL\n", 5); goto sockfilt_cleanup; } if(portname) { wroteportfile = write_portfile(portname, port); if(!wroteportfile) { write_stdout("FAIL\n", 5); goto sockfilt_cleanup; } } do { juggle_again = juggle(&msgsock, sock, &mode); } while(juggle_again); sockfilt_cleanup: if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD)) sclose(msgsock); if(sock != CURL_SOCKET_BAD) sclose(sock); if(wrotepidfile) unlink(pidname); if(wroteportfile) unlink(portname); restore_signal_handlers(false); if(got_exit_signal) { logmsg("============> sockfilt exits with signal (%d)", exit_signal); /* * To properly set the return status of the process we * must raise the same signal SIGINT or SIGTERM that we * caught and let the old handler take care of it. */ raise(exit_signal); } logmsg("============> sockfilt quits"); return 0; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/base64.pl
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 2004 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### use MIME::Base64 qw(encode_base64); my $buf; while(read(STDIN, $buf, 60*57)) { my $enc = encode_base64($buf); print "$enc"; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/CMakeLists.txt
#*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 2009 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### set(TARGET_LABEL_PREFIX "Test server ") if(MSVC) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4306") endif() function(SETUP_EXECUTABLE TEST_NAME) # ARGN are the files in the test add_executable(${TEST_NAME} EXCLUDE_FROM_ALL ${ARGN}) add_dependencies(testdeps ${TEST_NAME}) string(TOUPPER ${TEST_NAME} UPPER_TEST_NAME) include_directories( ${CURL_SOURCE_DIR}/lib # To be able to reach "curl_setup_once.h" ${CURL_BINARY_DIR}/lib # To be able to reach "curl_config.h" ${CURL_BINARY_DIR}/include # To be able to reach "curl/curl.h" ) if(USE_ARES) include_directories(${CARES_INCLUDE_DIR}) endif() target_link_libraries(${TEST_NAME} ${CURL_LIBS}) # Test servers simply are standalone programs that do not use libcurl # library. For convenience and to ease portability of these servers, # some source code files from the libcurl subdirectory are also used # to build the servers. In order to achieve proper linkage of these # files on Win32 targets it is necessary to build the test servers # with CURL_STATICLIB defined, independently of how libcurl is built. if(BUILD_SHARED_LIBS) set_target_properties(${TEST_NAME} PROPERTIES COMPILE_DEFINITIONS CURL_STATICLIB) # ${UPPER_TEST_NAME} endif() set_target_properties(${TEST_NAME} PROPERTIES PROJECT_LABEL "${TARGET_LABEL_PREFIX}${TEST_NAME}") endfunction() transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake") include(${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake) foreach(EXECUTABLE_NAME ${noinst_PROGRAMS}) setup_executable(${EXECUTABLE_NAME} ${${EXECUTABLE_NAME}_SOURCES}) endforeach() # SET(useful # getpart.c getpart.h # ${CURL_SOURCE_DIR}/lib/strequal.c # ${CURL_SOURCE_DIR}/lib/base64.c # ${CURL_SOURCE_DIR}/lib/mprintf.c # ${CURL_SOURCE_DIR}/lib/memdebug.c # ${CURL_SOURCE_DIR}/lib/timeval.c # ) # SETUP_EXECUTABLE(sws sws.c util.c util.h ${useful}) # SETUP_EXECUTABLE(resolve resolve.c util.c util.h ${useful}) # SETUP_EXECUTABLE(sockfilt sockfilt.c util.c util.h ${useful} ${CURL_SOURCE_DIR}/lib/inet_pton.c) # SETUP_EXECUTABLE(getpart testpart.c ${useful}) # SETUP_EXECUTABLE(tftpd tftpd.c util.c util.h ${useful} tftp.h)
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/Makefile.inc
#*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 2009 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### noinst_PROGRAMS = getpart resolve rtspd sockfilt sws tftpd fake_ntlm \ socksd disabled mqttd CURLX_SRCS = \ ../../lib/mprintf.c \ ../../lib/nonblock.c \ ../../lib/strtoofft.c \ ../../lib/warnless.c \ ../../lib/curl_ctype.c \ ../../lib/dynbuf.c \ ../../lib/strdup.c \ ../../lib/curl_multibyte.c CURLX_HDRS = \ ../../lib/curlx.h \ ../../lib/nonblock.h \ ../../lib/strtoofft.h \ ../../lib/warnless.h \ ../../lib/curl_ctype.h \ ../../lib/dynbuf.h \ ../../lib/strdup.h \ ../../lib/curl_multibyte.h USEFUL = \ getpart.c \ getpart.h \ server_setup.h \ ../../lib/base64.c \ ../../lib/curl_base64.h \ ../../lib/memdebug.c \ ../../lib/memdebug.h UTIL = \ util.c \ util.h getpart_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) \ testpart.c getpart_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ getpart_CFLAGS = $(AM_CFLAGS) resolve_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ resolve.c resolve_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ resolve_CFLAGS = $(AM_CFLAGS) rtspd_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ server_sockaddr.h \ rtspd.c rtspd_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ rtspd_CFLAGS = $(AM_CFLAGS) sockfilt_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ server_sockaddr.h \ sockfilt.c \ ../../lib/inet_pton.c sockfilt_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ sockfilt_CFLAGS = $(AM_CFLAGS) socksd_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ server_sockaddr.h socksd.c \ ../../lib/inet_pton.c socksd_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ socksd_CFLAGS = $(AM_CFLAGS) mqttd_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ server_sockaddr.h mqttd.c \ ../../lib/inet_pton.c mqttd_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ mqttd_CFLAGS = $(AM_CFLAGS) sws_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ server_sockaddr.h \ sws.c \ ../../lib/inet_pton.c sws_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ sws_CFLAGS = $(AM_CFLAGS) tftpd_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ server_sockaddr.h \ tftpd.c \ tftp.h tftpd_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ tftpd_CFLAGS = $(AM_CFLAGS) fake_ntlm_SOURCES = $(CURLX_SRCS) $(CURLX_HDRS) $(USEFUL) $(UTIL) \ fake_ntlm.c fake_ntlm_LDADD = @CURL_NETWORK_AND_TIME_LIBS@ fake_ntlm_CFLAGS = $(AM_CFLAGS) disabled_SOURCES = disabled.c
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/getpart.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" #include "getpart.h" #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ /* just to please curl_base64.h we create a fake struct */ struct Curl_easy { int fake; }; #include "curl_base64.h" #include "curl_memory.h" /* include memdebug.h last */ #include "memdebug.h" #define EAT_SPACE(p) while(*(p) && ISSPACE(*(p))) (p)++ #define EAT_WORD(p) while(*(p) && !ISSPACE(*(p)) && ('>' != *(p))) (p)++ #ifdef DEBUG_GETPART #define show(x) printf x #else #define show(x) Curl_nop_stmt #endif #if defined(_MSC_VER) && defined(_DLL) # pragma warning(disable:4232) /* MSVC extension, dllimport identity */ #endif curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc; curl_free_callback Curl_cfree = (curl_free_callback)free; curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc; curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)strdup; curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc; #if defined(WIN32) && defined(UNICODE) curl_wcsdup_callback Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; #endif #if defined(_MSC_VER) && defined(_DLL) # pragma warning(default:4232) /* MSVC extension, dllimport identity */ #endif /* * Curl_convert_clone() returns a malloced copy of the source string (if * returning CURLE_OK), with the data converted to network format. This * function is used by base64 code in libcurl built to support data * conversion. This is a DUMMY VERSION that returns data unmodified - for * use by the test server only. */ CURLcode Curl_convert_clone(struct Curl_easy *data, const char *indata, size_t insize, char **outbuf); CURLcode Curl_convert_clone(struct Curl_easy *data, const char *indata, size_t insize, char **outbuf) { char *convbuf; (void)data; convbuf = malloc(insize); if(!convbuf) return CURLE_OUT_OF_MEMORY; memcpy(convbuf, indata, insize); *outbuf = convbuf; return CURLE_OK; } /* * readline() * * Reads a complete line from a file into a dynamically allocated buffer. * * Calling function may call this multiple times with same 'buffer' * and 'bufsize' pointers to avoid multiple buffer allocations. Buffer * will be reallocated and 'bufsize' increased until whole line fits in * buffer before returning it. * * Calling function is responsible to free allocated buffer. * * This function may return: * GPE_OUT_OF_MEMORY * GPE_END_OF_FILE * GPE_OK */ static int readline(char **buffer, size_t *bufsize, FILE *stream) { size_t offset = 0; char *newptr; if(!*buffer) { *buffer = malloc(128); if(!*buffer) return GPE_OUT_OF_MEMORY; *bufsize = 128; } for(;;) { size_t length; int bytestoread = curlx_uztosi(*bufsize - offset); if(!fgets(*buffer + offset, bytestoread, stream)) return (offset != 0) ? GPE_OK : GPE_END_OF_FILE; length = offset + strlen(*buffer + offset); if(*(*buffer + length - 1) == '\n') break; offset = length; if(length < *bufsize - 1) continue; newptr = realloc(*buffer, *bufsize * 2); if(!newptr) return GPE_OUT_OF_MEMORY; *buffer = newptr; *bufsize *= 2; } return GPE_OK; } /* * appenddata() * * This appends data from a given source buffer to the end of the used part of * a destination buffer. Arguments relative to the destination buffer are, the * address of a pointer to the destination buffer 'dst_buf', the length of data * in destination buffer excluding potential null string termination 'dst_len', * the allocated size of destination buffer 'dst_alloc'. All three destination * buffer arguments may be modified by this function. Arguments relative to the * source buffer are, a pointer to the source buffer 'src_buf' and indication * whether the source buffer is base64 encoded or not 'src_b64'. * * If the source buffer is indicated to be base64 encoded, this appends the * decoded data, binary or whatever, to the destination. The source buffer * may not hold binary data, only a null terminated string is valid content. * * Destination buffer will be enlarged and relocated as needed. * * Calling function is responsible to provide preallocated destination * buffer and also to deallocate it when no longer needed. * * This function may return: * GPE_OUT_OF_MEMORY * GPE_OK */ static int appenddata(char **dst_buf, /* dest buffer */ size_t *dst_len, /* dest buffer data length */ size_t *dst_alloc, /* dest buffer allocated size */ char *src_buf, /* source buffer */ int src_b64) /* != 0 if source is base64 encoded */ { size_t need_alloc = 0; size_t src_len = strlen(src_buf); if(!src_len) return GPE_OK; need_alloc = src_len + *dst_len + 1; if(src_b64) { if(src_buf[src_len - 1] == '\r') src_len--; if(src_buf[src_len - 1] == '\n') src_len--; } /* enlarge destination buffer if required */ if(need_alloc > *dst_alloc) { size_t newsize = need_alloc * 2; char *newptr = realloc(*dst_buf, newsize); if(!newptr) { return GPE_OUT_OF_MEMORY; } *dst_alloc = newsize; *dst_buf = newptr; } /* memcpy to support binary blobs */ memcpy(*dst_buf + *dst_len, src_buf, src_len); *dst_len += src_len; *(*dst_buf + *dst_len) = '\0'; return GPE_OK; } static int decodedata(char **buf, /* dest buffer */ size_t *len) /* dest buffer data length */ { CURLcode error = CURLE_OK; unsigned char *buf64 = NULL; size_t src_len = 0; if(!*len) return GPE_OK; /* base64 decode the given buffer */ error = Curl_base64_decode(*buf, &buf64, &src_len); if(error) return GPE_OUT_OF_MEMORY; if(!src_len) { /* ** currently there is no way to tell apart an OOM condition in ** Curl_base64_decode() from zero length decoded data. For now, ** let's just assume it is an OOM condition, currently we have ** no input for this function that decodes to zero length data. */ free(buf64); return GPE_OUT_OF_MEMORY; } /* memcpy to support binary blobs */ memcpy(*buf, buf64, src_len); *len = src_len; *(*buf + src_len) = '\0'; free(buf64); return GPE_OK; } /* * getpart() * * This returns whole contents of specified XML-like section and subsection * from the given file. This is mostly used to retrieve a specific part from * a test definition file for consumption by test suite servers. * * Data is returned in a dynamically allocated buffer, a pointer to this data * and the size of the data is stored at the addresses that caller specifies. * * If the returned data is a string the returned size will be the length of * the string excluding null termination. Otherwise it will just be the size * of the returned binary data. * * Calling function is responsible to free returned buffer. * * This function may return: * GPE_NO_BUFFER_SPACE * GPE_OUT_OF_MEMORY * GPE_OK */ int getpart(char **outbuf, size_t *outlen, const char *main, const char *sub, FILE *stream) { # define MAX_TAG_LEN 200 char couter[MAX_TAG_LEN + 1]; /* current outermost section */ char cmain[MAX_TAG_LEN + 1]; /* current main section */ char csub[MAX_TAG_LEN + 1]; /* current sub section */ char ptag[MAX_TAG_LEN + 1]; /* potential tag */ char patt[MAX_TAG_LEN + 1]; /* potential attributes */ char *buffer = NULL; char *ptr; char *end; union { ssize_t sig; size_t uns; } len; size_t bufsize = 0; size_t outalloc = 256; int in_wanted_part = 0; int base64 = 0; int error; enum { STATE_OUTSIDE = 0, STATE_OUTER = 1, STATE_INMAIN = 2, STATE_INSUB = 3, STATE_ILLEGAL = 4 } state = STATE_OUTSIDE; *outlen = 0; *outbuf = malloc(outalloc); if(!*outbuf) return GPE_OUT_OF_MEMORY; *(*outbuf) = '\0'; couter[0] = cmain[0] = csub[0] = ptag[0] = patt[0] = '\0'; while((error = readline(&buffer, &bufsize, stream)) == GPE_OK) { ptr = buffer; EAT_SPACE(ptr); if('<' != *ptr) { if(in_wanted_part) { show(("=> %s", buffer)); error = appenddata(outbuf, outlen, &outalloc, buffer, base64); if(error) break; } continue; } ptr++; if('/' == *ptr) { /* ** closing section tag */ ptr++; end = ptr; EAT_WORD(end); len.sig = end - ptr; if(len.sig > MAX_TAG_LEN) { error = GPE_NO_BUFFER_SPACE; break; } memcpy(ptag, ptr, len.uns); ptag[len.uns] = '\0'; if((STATE_INSUB == state) && !strcmp(csub, ptag)) { /* end of current sub section */ state = STATE_INMAIN; csub[0] = '\0'; if(in_wanted_part) { /* end of wanted part */ in_wanted_part = 0; /* Do we need to base64 decode the data? */ if(base64) { error = decodedata(outbuf, outlen); if(error) return error; } break; } } else if((STATE_INMAIN == state) && !strcmp(cmain, ptag)) { /* end of current main section */ state = STATE_OUTER; cmain[0] = '\0'; if(in_wanted_part) { /* end of wanted part */ in_wanted_part = 0; /* Do we need to base64 decode the data? */ if(base64) { error = decodedata(outbuf, outlen); if(error) return error; } break; } } else if((STATE_OUTER == state) && !strcmp(couter, ptag)) { /* end of outermost file section */ state = STATE_OUTSIDE; couter[0] = '\0'; if(in_wanted_part) { /* end of wanted part */ in_wanted_part = 0; break; } } } else if(!in_wanted_part) { /* ** opening section tag */ /* get potential tag */ end = ptr; EAT_WORD(end); len.sig = end - ptr; if(len.sig > MAX_TAG_LEN) { error = GPE_NO_BUFFER_SPACE; break; } memcpy(ptag, ptr, len.uns); ptag[len.uns] = '\0'; /* ignore comments, doctypes and xml declarations */ if(('!' == ptag[0]) || ('?' == ptag[0])) { show(("* ignoring (%s)", buffer)); continue; } /* get all potential attributes */ ptr = end; EAT_SPACE(ptr); end = ptr; while(*end && ('>' != *end)) end++; len.sig = end - ptr; if(len.sig > MAX_TAG_LEN) { error = GPE_NO_BUFFER_SPACE; break; } memcpy(patt, ptr, len.uns); patt[len.uns] = '\0'; if(STATE_OUTSIDE == state) { /* outermost element (<testcase>) */ strcpy(couter, ptag); state = STATE_OUTER; continue; } else if(STATE_OUTER == state) { /* start of a main section */ strcpy(cmain, ptag); state = STATE_INMAIN; continue; } else if(STATE_INMAIN == state) { /* start of a sub section */ strcpy(csub, ptag); state = STATE_INSUB; if(!strcmp(cmain, main) && !strcmp(csub, sub)) { /* start of wanted part */ in_wanted_part = 1; if(strstr(patt, "base64=")) /* bit rough test, but "mostly" functional, */ /* treat wanted part data as base64 encoded */ base64 = 1; } continue; } } if(in_wanted_part) { show(("=> %s", buffer)); error = appenddata(outbuf, outlen, &outalloc, buffer, base64); if(error) break; } } /* while */ free(buffer); if(error != GPE_OK) { if(error == GPE_END_OF_FILE) error = GPE_OK; else { free(*outbuf); *outbuf = NULL; *outlen = 0; } } return error; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/fake_ntlm.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2010, Mandy Wu, <[email protected]> * Copyright (C) 2011 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" /* * This is a fake ntlm_auth, which is used for testing NTLM single-sign-on. * When DEBUGBUILD is defined, libcurl invoke this tool instead of real winbind * daemon helper /usr/bin/ntlm_auth. This tool will accept commands and * responses with a pre-written string saved in test case test2005. */ #define ENABLE_CURLX_PRINTF #include "curlx.h" /* from the private lib dir */ #include "getpart.h" #include "util.h" /* include memdebug.h last */ #include "memdebug.h" #define LOGFILE "log/fake_ntlm%ld.log" const char *serverlogfile; /* * Returns an allocated buffer with printable representation of input * buffer contents or returns NULL on out of memory condition. */ static char *printable(char *inbuf, size_t inlength) { char *outbuf; char *newbuf; size_t newsize; size_t outsize; size_t outincr = 0; size_t i, o = 0; #define HEX_FMT_STR "[0x%02X]" #define HEX_STR_LEN 6 #define NOTHING_STR "[NOTHING]" #define NOTHING_LEN 9 if(!inlength) inlength = strlen(inbuf); if(inlength) { outincr = ((inlength/2) < (HEX_STR_LEN + 1)) ? HEX_STR_LEN + 1 : inlength/2; outsize = inlength + outincr; } else outsize = NOTHING_LEN + 1; outbuf = malloc(outsize); if(!outbuf) return NULL; if(!inlength) { msnprintf(&outbuf[0], outsize, "%s", NOTHING_STR); return outbuf; } for(i = 0; i<inlength; i++) { if(o > outsize - (HEX_STR_LEN + 1)) { newsize = outsize + outincr; newbuf = realloc(outbuf, newsize); if(!newbuf) { free(outbuf); return NULL; } outbuf = newbuf; outsize = newsize; } if((inbuf[i] > 0x20) && (inbuf[i] < 0x7F)) { outbuf[o] = inbuf[i]; o++; } else { msnprintf(&outbuf[o], outsize - o, HEX_FMT_STR, inbuf[i]); o += HEX_STR_LEN; } } outbuf[o] = '\0'; return outbuf; } int main(int argc, char *argv[]) { char buf[1024]; char logfilename[256]; FILE *stream; int error; char *type1_input = NULL, *type3_input = NULL; char *type1_output = NULL, *type3_output = NULL; size_t size = 0; long testnum; const char *env; int arg = 1; const char *helper_user = "unknown"; const char *helper_proto = "unknown"; const char *helper_domain = "unknown"; bool use_cached_creds = FALSE; char *msgbuf; buf[0] = '\0'; while(argc > arg) { if(!strcmp("--use-cached-creds", argv[arg])) { use_cached_creds = TRUE; arg++; } else if(!strcmp("--helper-protocol", argv[arg])) { arg++; if(argc > arg) helper_proto = argv[arg++]; } else if(!strcmp("--username", argv[arg])) { arg++; if(argc > arg) helper_user = argv[arg++]; } else if(!strcmp("--domain", argv[arg])) { arg++; if(argc > arg) helper_domain = argv[arg++]; } else { puts("Usage: fake_ntlm [option]\n" " --use-cached-creds\n" " --helper-protocol [protocol]\n" " --username [username]\n" " --domain [domain]"); exit(1); } } env = getenv("CURL_NTLM_AUTH_TESTNUM"); if(env) { char *endptr; long lnum = strtol(env, &endptr, 10); if((endptr != env + strlen(env)) || (lnum < 1L)) { fprintf(stderr, "Test number not valid in CURL_NTLM_AUTH_TESTNUM"); exit(1); } testnum = lnum; } else { fprintf(stderr, "Test number not specified in CURL_NTLM_AUTH_TESTNUM"); exit(1); } /* logmsg cannot be used until this file name is set */ msnprintf(logfilename, sizeof(logfilename), LOGFILE, testnum); serverlogfile = logfilename; logmsg("fake_ntlm (user: %s) (proto: %s) (domain: %s) (cached creds: %s)", helper_user, helper_proto, helper_domain, (use_cached_creds) ? "yes" : "no"); env = getenv("CURL_NTLM_AUTH_SRCDIR"); if(env) { path = env; } stream = test2fopen(testnum); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Couldn't open test file %ld", testnum); exit(1); } else { /* get the ntlm_auth input/output */ error = getpart(&type1_input, &size, "ntlm_auth_type1", "input", stream); fclose(stream); if(error || size == 0) { logmsg("getpart() type 1 input failed with error: %d", error); exit(1); } } stream = test2fopen(testnum); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Couldn't open test file %ld", testnum); } else { size = 0; error = getpart(&type3_input, &size, "ntlm_auth_type3", "input", stream); fclose(stream); if(error || size == 0) { logmsg("getpart() type 3 input failed with error: %d", error); exit(1); } } while(fgets(buf, sizeof(buf), stdin)) { if(strcmp(buf, type1_input) == 0) { stream = test2fopen(testnum); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Couldn't open test file %ld", testnum); exit(1); } else { size = 0; error = getpart(&type1_output, &size, "ntlm_auth_type1", "output", stream); fclose(stream); if(error || size == 0) { logmsg("getpart() type 1 output failed with error: %d", error); exit(1); } } printf("%s", type1_output); fflush(stdout); } else if(strncmp(buf, type3_input, strlen(type3_input)) == 0) { stream = test2fopen(testnum); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Couldn't open test file %ld", testnum); exit(1); } else { size = 0; error = getpart(&type3_output, &size, "ntlm_auth_type3", "output", stream); fclose(stream); if(error || size == 0) { logmsg("getpart() type 3 output failed with error: %d", error); exit(1); } } printf("%s", type3_output); fflush(stdout); } else { printf("Unknown request\n"); msgbuf = printable(buf, 0); if(msgbuf) { logmsg("invalid input: '%s'\n", msgbuf); free(msgbuf); } else logmsg("OOM formatting invalid input: '%s'\n", buf); exit(1); } } logmsg("Exit"); return 1; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/sws.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" /* sws.c: simple (silly?) web server This code was originally graciously donated to the project by Juergen Wilke. Thanks a bunch! */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_NETINET_TCP_H #include <netinet/tcp.h> /* for TCP_NODELAY */ #endif #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ #include "getpart.h" #include "inet_pton.h" #include "util.h" #include "server_sockaddr.h" /* include memdebug.h last */ #include "memdebug.h" #ifdef USE_WINSOCK #undef EINTR #define EINTR 4 /* errno.h value */ #undef EAGAIN #define EAGAIN 11 /* errno.h value */ #undef ERANGE #define ERANGE 34 /* errno.h value */ #endif static enum { socket_domain_inet = AF_INET #ifdef ENABLE_IPV6 , socket_domain_inet6 = AF_INET6 #endif #ifdef USE_UNIX_SOCKETS , socket_domain_unix = AF_UNIX #endif } socket_domain = AF_INET; static bool use_gopher = FALSE; static int serverlogslocked = 0; static bool is_proxy = FALSE; #define REQBUFSIZ (2*1024*1024) static long prevtestno = -1; /* previous test number we served */ static long prevpartno = -1; /* previous part number we served */ static bool prevbounce = FALSE; /* instructs the server to increase the part number for a test in case the identical testno+partno request shows up again */ #define RCMD_NORMALREQ 0 /* default request, use the tests file normally */ #define RCMD_IDLE 1 /* told to sit idle */ #define RCMD_STREAM 2 /* told to stream */ struct httprequest { char reqbuf[REQBUFSIZ]; /* buffer area for the incoming request */ bool connect_request; /* if a CONNECT */ unsigned short connect_port; /* the port number CONNECT used */ size_t checkindex; /* where to start checking of the request */ size_t offset; /* size of the incoming request */ long testno; /* test number found in the request */ long partno; /* part number found in the request */ bool open; /* keep connection open info, as found in the request */ bool auth_req; /* authentication required, don't wait for body unless there's an Authorization header */ bool auth; /* Authorization header present in the incoming request */ size_t cl; /* Content-Length of the incoming request */ bool digest; /* Authorization digest header found */ bool ntlm; /* Authorization ntlm header found */ int writedelay; /* if non-zero, delay this number of seconds between writes in the response */ int skip; /* if non-zero, the server is instructed to not read this many bytes from a PUT/POST request. Ie the client sends N bytes said in Content-Length, but the server only reads N - skip bytes. */ int rcmd; /* doing a special command, see defines above */ int prot_version; /* HTTP version * 10 */ int callcount; /* times ProcessRequest() gets called */ bool skipall; /* skip all incoming data */ bool noexpect; /* refuse Expect: (don't read the body) */ bool connmon; /* monitor the state of the connection, log disconnects */ bool upgrade; /* test case allows upgrade to http2 */ bool upgrade_request; /* upgrade request found and allowed */ bool close; /* similar to swsclose in response: close connection after response is sent */ int done_processing; }; #define MAX_SOCKETS 1024 static curl_socket_t all_sockets[MAX_SOCKETS]; static size_t num_sockets = 0; static int ProcessRequest(struct httprequest *req); static void storerequest(const char *reqbuf, size_t totalsize); #define DEFAULT_PORT 8999 #ifndef DEFAULT_LOGFILE #define DEFAULT_LOGFILE "log/sws.log" #endif const char *serverlogfile = DEFAULT_LOGFILE; #define SWSVERSION "curl test suite HTTP server/0.1" #define REQUEST_DUMP "log/server.input" #define RESPONSE_DUMP "log/server.response" /* when told to run as proxy, we store the logs in different files so that they can co-exist with the same program running as a "server" */ #define REQUEST_PROXY_DUMP "log/proxy.input" #define RESPONSE_PROXY_DUMP "log/proxy.response" /* file in which additional instructions may be found */ #define DEFAULT_CMDFILE "log/ftpserver.cmd" const char *cmdfile = DEFAULT_CMDFILE; /* very-big-path support */ #define MAXDOCNAMELEN 140000 #define MAXDOCNAMELEN_TXT "139999" #define REQUEST_KEYWORD_SIZE 256 #define REQUEST_KEYWORD_SIZE_TXT "255" #define CMD_AUTH_REQUIRED "auth_required" /* 'idle' means that it will accept the request fine but never respond any data. Just keep the connection alive. */ #define CMD_IDLE "idle" /* 'stream' means to send a never-ending stream of data */ #define CMD_STREAM "stream" /* 'connection-monitor' will output when a server/proxy connection gets disconnected as for some cases it is important that it gets done at the proper point - like with NTLM */ #define CMD_CONNECTIONMONITOR "connection-monitor" /* upgrade to http2 */ #define CMD_UPGRADE "upgrade" /* close connection */ #define CMD_SWSCLOSE "swsclose" /* deny Expect: requests */ #define CMD_NOEXPECT "no-expect" #define END_OF_HEADERS "\r\n\r\n" enum { DOCNUMBER_NOTHING = -4, DOCNUMBER_QUIT = -3, DOCNUMBER_WERULEZ = -2, DOCNUMBER_404 = -1 }; static const char *end_of_headers = END_OF_HEADERS; /* sent as reply to a QUIT */ static const char *docquit = "HTTP/1.1 200 Goodbye" END_OF_HEADERS; /* send back this on 404 file not found */ static const char *doc404 = "HTTP/1.1 404 Not Found\r\n" "Server: " SWSVERSION "\r\n" "Connection: close\r\n" "Content-Type: text/html" END_OF_HEADERS "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" "<HTML><HEAD>\n" "<TITLE>404 Not Found</TITLE>\n" "</HEAD><BODY>\n" "<H1>Not Found</H1>\n" "The requested URL was not found on this server.\n" "<P><HR><ADDRESS>" SWSVERSION "</ADDRESS>\n" "</BODY></HTML>\n"; /* work around for handling trailing headers */ static int already_recv_zeroed_chunk = FALSE; /* returns true if the current socket is an IP one */ static bool socket_domain_is_ip(void) { switch(socket_domain) { case AF_INET: #ifdef ENABLE_IPV6 case AF_INET6: #endif return true; default: /* case AF_UNIX: */ return false; } } /* parse the file on disk that might have a test number for us */ static int parse_cmdfile(struct httprequest *req) { FILE *f = fopen(cmdfile, FOPEN_READTEXT); if(f) { int testnum = DOCNUMBER_NOTHING; char buf[256]; while(fgets(buf, sizeof(buf), f)) { if(1 == sscanf(buf, "Testnum %d", &testnum)) { logmsg("[%s] cmdfile says testnum %d", cmdfile, testnum); req->testno = testnum; } } fclose(f); } return 0; } /* based on the testno, parse the correct server commands */ static int parse_servercmd(struct httprequest *req) { FILE *stream; int error; stream = test2fopen(req->testno); req->close = FALSE; req->connmon = FALSE; if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg(" Couldn't open test file %ld", req->testno); req->open = FALSE; /* closes connection */ return 1; /* done */ } else { char *orgcmd = NULL; char *cmd = NULL; size_t cmdsize = 0; int num = 0; /* get the custom server control "commands" */ error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream); fclose(stream); if(error) { logmsg("getpart() failed with error: %d", error); req->open = FALSE; /* closes connection */ return 1; /* done */ } cmd = orgcmd; while(cmd && cmdsize) { char *check; if(!strncmp(CMD_AUTH_REQUIRED, cmd, strlen(CMD_AUTH_REQUIRED))) { logmsg("instructed to require authorization header"); req->auth_req = TRUE; } else if(!strncmp(CMD_IDLE, cmd, strlen(CMD_IDLE))) { logmsg("instructed to idle"); req->rcmd = RCMD_IDLE; req->open = TRUE; } else if(!strncmp(CMD_STREAM, cmd, strlen(CMD_STREAM))) { logmsg("instructed to stream"); req->rcmd = RCMD_STREAM; } else if(!strncmp(CMD_CONNECTIONMONITOR, cmd, strlen(CMD_CONNECTIONMONITOR))) { logmsg("enabled connection monitoring"); req->connmon = TRUE; } else if(!strncmp(CMD_UPGRADE, cmd, strlen(CMD_UPGRADE))) { logmsg("enabled upgrade to http2"); req->upgrade = TRUE; } else if(!strncmp(CMD_SWSCLOSE, cmd, strlen(CMD_SWSCLOSE))) { logmsg("swsclose: close this connection after response"); req->close = TRUE; } else if(1 == sscanf(cmd, "skip: %d", &num)) { logmsg("instructed to skip this number of bytes %d", num); req->skip = num; } else if(!strncmp(CMD_NOEXPECT, cmd, strlen(CMD_NOEXPECT))) { logmsg("instructed to reject Expect: 100-continue"); req->noexpect = TRUE; } else if(1 == sscanf(cmd, "writedelay: %d", &num)) { logmsg("instructed to delay %d secs between packets", num); req->writedelay = num; } else { logmsg("Unknown <servercmd> instruction found: %s", cmd); } /* try to deal with CRLF or just LF */ check = strchr(cmd, '\r'); if(!check) check = strchr(cmd, '\n'); if(check) { /* get to the letter following the newline */ while((*check == '\r') || (*check == '\n')) check++; if(!*check) /* if we reached a zero, get out */ break; cmd = check; } else break; } free(orgcmd); } return 0; /* OK! */ } static int ProcessRequest(struct httprequest *req) { char *line = &req->reqbuf[req->checkindex]; bool chunked = FALSE; static char request[REQUEST_KEYWORD_SIZE]; static char doc[MAXDOCNAMELEN]; char logbuf[456]; int prot_major, prot_minor; char *end = strstr(line, end_of_headers); req->callcount++; logmsg("Process %d bytes request%s", req->offset, req->callcount > 1?" [CONTINUED]":""); /* try to figure out the request characteristics as soon as possible, but only once! */ if(use_gopher && (req->testno == DOCNUMBER_NOTHING) && !strncmp("/verifiedserver", line, 15)) { logmsg("Are-we-friendly question received"); req->testno = DOCNUMBER_WERULEZ; return 1; /* done */ } else if((req->testno == DOCNUMBER_NOTHING) && sscanf(line, "%" REQUEST_KEYWORD_SIZE_TXT"s %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d", request, doc, &prot_major, &prot_minor) == 4) { char *ptr; req->prot_version = prot_major*10 + prot_minor; /* find the last slash */ ptr = strrchr(doc, '/'); /* get the number after it */ if(ptr) { if((strlen(doc) + strlen(request)) < 400) msnprintf(logbuf, sizeof(logbuf), "Got request: %s %s HTTP/%d.%d", request, doc, prot_major, prot_minor); else msnprintf(logbuf, sizeof(logbuf), "Got a *HUGE* request HTTP/%d.%d", prot_major, prot_minor); logmsg("%s", logbuf); if(!strncmp("/verifiedserver", ptr, 15)) { logmsg("Are-we-friendly question received"); req->testno = DOCNUMBER_WERULEZ; return 1; /* done */ } if(!strncmp("/quit", ptr, 5)) { logmsg("Request-to-quit received"); req->testno = DOCNUMBER_QUIT; return 1; /* done */ } ptr++; /* skip the slash */ /* skip all non-numericals following the slash */ while(*ptr && !ISDIGIT(*ptr)) ptr++; req->testno = strtol(ptr, &ptr, 10); if(req->testno > 10000) { req->partno = req->testno % 10000; req->testno /= 10000; } else req->partno = 0; if(req->testno) { msnprintf(logbuf, sizeof(logbuf), "Requested test number %ld part %ld", req->testno, req->partno); logmsg("%s", logbuf); } else { logmsg("No test number"); req->testno = DOCNUMBER_NOTHING; } } if(req->testno == DOCNUMBER_NOTHING) { /* didn't find any in the first scan, try alternative test case number placements */ if(sscanf(req->reqbuf, "CONNECT %" MAXDOCNAMELEN_TXT "s HTTP/%d.%d", doc, &prot_major, &prot_minor) == 3) { char *portp = NULL; msnprintf(logbuf, sizeof(logbuf), "Received a CONNECT %s HTTP/%d.%d request", doc, prot_major, prot_minor); logmsg("%s", logbuf); req->connect_request = TRUE; if(req->prot_version == 10) req->open = FALSE; /* HTTP 1.0 closes connection by default */ if(doc[0] == '[') { char *p = &doc[1]; unsigned long part = 0; /* scan through the hexgroups and store the value of the last group in the 'part' variable and use as test case number!! */ while(*p && (ISXDIGIT(*p) || (*p == ':') || (*p == '.'))) { char *endp; part = strtoul(p, &endp, 16); if(ISXDIGIT(*p)) p = endp; else p++; } if(*p != ']') logmsg("Invalid CONNECT IPv6 address format"); else if(*(p + 1) != ':') logmsg("Invalid CONNECT IPv6 port format"); else portp = p + 1; req->testno = part; } else portp = strchr(doc, ':'); if(portp && (*(portp + 1) != '\0') && ISDIGIT(*(portp + 1))) { unsigned long ulnum = strtoul(portp + 1, NULL, 10); if(!ulnum || (ulnum > 65535UL)) logmsg("Invalid CONNECT port received"); else req->connect_port = curlx_ultous(ulnum); } logmsg("Port number: %d, test case number: %ld", req->connect_port, req->testno); } } if(req->testno == DOCNUMBER_NOTHING) { /* Still no test case number. Try to get the number off the last dot instead, IE we consider the TLD to be the test number. Test 123 can then be written as "example.com.123". */ /* find the last dot */ ptr = strrchr(doc, '.'); /* get the number after it */ if(ptr) { long num; ptr++; /* skip the dot */ num = strtol(ptr, &ptr, 10); if(num) { req->testno = num; if(req->testno > 10000) { req->partno = req->testno % 10000; req->testno /= 10000; logmsg("found test %d in requested host name", req->testno); } else req->partno = 0; } if(req->testno != DOCNUMBER_NOTHING) { logmsg("Requested test number %ld part %ld (from host name)", req->testno, req->partno); } } } if(req->testno == DOCNUMBER_NOTHING) /* might get the test number */ parse_cmdfile(req); if(req->testno == DOCNUMBER_NOTHING) { logmsg("Did not find test number in PATH"); req->testno = DOCNUMBER_404; } else parse_servercmd(req); } else if((req->offset >= 3) && (req->testno == DOCNUMBER_NOTHING)) { logmsg("** Unusual request. Starts with %02x %02x %02x (%c%c%c)", line[0], line[1], line[2], line[0], line[1], line[2]); } if(!end) { /* we don't have a complete request yet! */ logmsg("request not complete yet"); return 0; /* not complete yet */ } logmsg("- request found to be complete (%d)", req->testno); if(req->testno == DOCNUMBER_NOTHING) { /* check for a Testno: header with the test case number */ char *testno = strstr(line, "\nTestno: "); if(testno) { req->testno = strtol(&testno[9], NULL, 10); logmsg("Found test number %d in Testno: header!", req->testno); } else { logmsg("No Testno: header"); } } /* find and parse <servercmd> for this test */ parse_servercmd(req); if(use_gopher) { /* when using gopher we cannot check the request until the entire thing has been received */ char *ptr; /* find the last slash in the line */ ptr = strrchr(line, '/'); if(ptr) { ptr++; /* skip the slash */ /* skip all non-numericals following the slash */ while(*ptr && !ISDIGIT(*ptr)) ptr++; req->testno = strtol(ptr, &ptr, 10); if(req->testno > 10000) { req->partno = req->testno % 10000; req->testno /= 10000; } else req->partno = 0; msnprintf(logbuf, sizeof(logbuf), "Requested GOPHER test number %ld part %ld", req->testno, req->partno); logmsg("%s", logbuf); } } /* **** Persistence **** * * If the request is a HTTP/1.0 one, we close the connection unconditionally * when we're done. * * If the request is a HTTP/1.1 one, we MUST check for a "Connection:" * header that might say "close". If it does, we close a connection when * this request is processed. Otherwise, we keep the connection alive for X * seconds. */ do { if(got_exit_signal) return 1; /* done */ if((req->cl == 0) && strncasecompare("Content-Length:", line, 15)) { /* If we don't ignore content-length, we read it and we read the whole request including the body before we return. If we've been told to ignore the content-length, we will return as soon as all headers have been received */ char *endptr; char *ptr = line + 15; unsigned long clen = 0; while(*ptr && ISSPACE(*ptr)) ptr++; endptr = ptr; errno = 0; clen = strtoul(ptr, &endptr, 10); if((ptr == endptr) || !ISSPACE(*endptr) || (ERANGE == errno)) { /* this assumes that a zero Content-Length is valid */ logmsg("Found invalid Content-Length: (%s) in the request", ptr); req->open = FALSE; /* closes connection */ return 1; /* done */ } if(req->skipall) req->cl = 0; else req->cl = clen - req->skip; logmsg("Found Content-Length: %lu in the request", clen); if(req->skip) logmsg("... but will abort after %zu bytes", req->cl); } else if(strncasecompare("Transfer-Encoding: chunked", line, strlen("Transfer-Encoding: chunked"))) { /* chunked data coming in */ chunked = TRUE; } else if(req->noexpect && strncasecompare("Expect: 100-continue", line, strlen("Expect: 100-continue"))) { if(req->cl) req->cl = 0; req->skipall = TRUE; logmsg("Found Expect: 100-continue, ignore body"); } if(chunked) { if(strstr(req->reqbuf, "\r\n0\r\n\r\n")) { /* end of chunks reached */ return 1; /* done */ } else if(strstr(req->reqbuf, "\r\n0\r\n")) { char *last_crlf_char = strstr(req->reqbuf, "\r\n\r\n"); while(TRUE) { if(!strstr(last_crlf_char + 4, "\r\n\r\n")) break; last_crlf_char = strstr(last_crlf_char + 4, "\r\n\r\n"); } if(last_crlf_char && last_crlf_char > strstr(req->reqbuf, "\r\n0\r\n")) return 1; already_recv_zeroed_chunk = TRUE; return 0; } else if(already_recv_zeroed_chunk && strstr(req->reqbuf, "\r\n\r\n")) return 1; else return 0; /* not done */ } line = strchr(line, '\n'); if(line) line++; } while(line); if(!req->auth && strstr(req->reqbuf, "Authorization:")) { req->auth = TRUE; /* Authorization: header present! */ if(req->auth_req) logmsg("Authorization header found, as required"); } if(strstr(req->reqbuf, "Authorization: Negotiate")) { /* Negotiate iterations */ static long prev_testno = -1; static long prev_partno = -1; logmsg("Negotiate: prev_testno: %d, prev_partno: %d", prev_testno, prev_partno); if(req->testno != prev_testno) { prev_testno = req->testno; prev_partno = req->partno; } prev_partno += 1; req->partno = prev_partno; } else if(!req->digest && strstr(req->reqbuf, "Authorization: Digest")) { /* If the client is passing this Digest-header, we set the part number to 1000. Not only to spice up the complexity of this, but to make Digest stuff to work in the test suite. */ req->partno += 1000; req->digest = TRUE; /* header found */ logmsg("Received Digest request, sending back data %ld", req->partno); } else if(!req->ntlm && strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAD")) { /* If the client is passing this type-3 NTLM header */ req->partno += 1002; req->ntlm = TRUE; /* NTLM found */ logmsg("Received NTLM type-3, sending back data %ld", req->partno); if(req->cl) { logmsg(" Expecting %zu POSTed bytes", req->cl); } } else if(!req->ntlm && strstr(req->reqbuf, "Authorization: NTLM TlRMTVNTUAAB")) { /* If the client is passing this type-1 NTLM header */ req->partno += 1001; req->ntlm = TRUE; /* NTLM found */ logmsg("Received NTLM type-1, sending back data %ld", req->partno); } else if((req->partno >= 1000) && strstr(req->reqbuf, "Authorization: Basic")) { /* If the client is passing this Basic-header and the part number is already >=1000, we add 1 to the part number. This allows simple Basic authentication negotiation to work in the test suite. */ req->partno += 1; logmsg("Received Basic request, sending back data %ld", req->partno); } if(strstr(req->reqbuf, "Connection: close")) req->open = FALSE; /* close connection after this request */ if(req->open && req->prot_version >= 11 && req->reqbuf + req->offset > end + strlen(end_of_headers) && !req->cl && (!strncmp(req->reqbuf, "GET", strlen("GET")) || !strncmp(req->reqbuf, "HEAD", strlen("HEAD")))) { /* If we have a persistent connection, HTTP version >= 1.1 and GET/HEAD request, enable pipelining. */ req->checkindex = (end - req->reqbuf) + strlen(end_of_headers); } /* If authentication is required and no auth was provided, end now. This makes the server NOT wait for PUT/POST data and you can then make the test case send a rejection before any such data has been sent. Test case 154 uses this.*/ if(req->auth_req && !req->auth) { logmsg("Return early due to auth requested by none provided"); return 1; /* done */ } if(req->upgrade && strstr(req->reqbuf, "Upgrade:")) { /* we allow upgrade and there was one! */ logmsg("Found Upgrade: in request and allows it"); req->upgrade_request = TRUE; } if(req->cl > 0) { if(req->cl <= req->offset - (end - req->reqbuf) - strlen(end_of_headers)) return 1; /* done */ else return 0; /* not complete yet */ } return 1; /* done */ } /* store the entire request in a file */ static void storerequest(const char *reqbuf, size_t totalsize) { int res; int error = 0; size_t written; size_t writeleft; FILE *dump; const char *dumpfile = is_proxy?REQUEST_PROXY_DUMP:REQUEST_DUMP; if(!reqbuf) return; if(totalsize == 0) return; do { dump = fopen(dumpfile, "ab"); } while(!dump && ((error = errno) == EINTR)); if(!dump) { logmsg("[2] Error opening file %s error: %d %s", dumpfile, error, strerror(error)); logmsg("Failed to write request input "); return; } writeleft = totalsize; do { written = fwrite(&reqbuf[totalsize-writeleft], 1, writeleft, dump); if(got_exit_signal) goto storerequest_cleanup; if(written > 0) writeleft -= written; } while((writeleft > 0) && ((error = errno) == EINTR)); if(writeleft == 0) logmsg("Wrote request (%zu bytes) input to %s", totalsize, dumpfile); else if(writeleft > 0) { logmsg("Error writing file %s error: %d %s", dumpfile, error, strerror(error)); logmsg("Wrote only (%zu bytes) of (%zu bytes) request input to %s", totalsize-writeleft, totalsize, dumpfile); } storerequest_cleanup: do { res = fclose(dump); } while(res && ((error = errno) == EINTR)); if(res) logmsg("Error closing file %s error: %d %s", dumpfile, error, strerror(error)); } static void init_httprequest(struct httprequest *req) { req->checkindex = 0; req->offset = 0; req->testno = DOCNUMBER_NOTHING; req->partno = 0; req->connect_request = FALSE; req->open = TRUE; req->auth_req = FALSE; req->auth = FALSE; req->cl = 0; req->digest = FALSE; req->ntlm = FALSE; req->skip = 0; req->skipall = FALSE; req->noexpect = FALSE; req->writedelay = 0; req->rcmd = RCMD_NORMALREQ; req->prot_version = 0; req->callcount = 0; req->connect_port = 0; req->done_processing = 0; req->upgrade = 0; req->upgrade_request = 0; } /* returns 1 if the connection should be serviced again immediately, 0 if there is no data waiting, or < 0 if it should be closed */ static int get_request(curl_socket_t sock, struct httprequest *req) { int fail = 0; char *reqbuf = req->reqbuf; ssize_t got = 0; int overflow = 0; if(req->offset >= REQBUFSIZ-1) { /* buffer is already full; do nothing */ overflow = 1; } else { if(req->skip) /* we are instructed to not read the entire thing, so we make sure to only read what we're supposed to and NOT read the enire thing the client wants to send! */ got = sread(sock, reqbuf + req->offset, req->cl); else got = sread(sock, reqbuf + req->offset, REQBUFSIZ-1 - req->offset); if(got_exit_signal) return -1; if(got == 0) { logmsg("Connection closed by client"); fail = 1; } else if(got < 0) { int error = SOCKERRNO; if(EAGAIN == error || EWOULDBLOCK == error) { /* nothing to read at the moment */ return 0; } logmsg("recv() returned error: (%d) %s", error, strerror(error)); fail = 1; } if(fail) { /* dump the request received so far to the external file */ reqbuf[req->offset] = '\0'; storerequest(reqbuf, req->offset); return -1; } logmsg("Read %zd bytes", got); req->offset += (size_t)got; reqbuf[req->offset] = '\0'; req->done_processing = ProcessRequest(req); if(got_exit_signal) return -1; } if(overflow || (req->offset == REQBUFSIZ-1 && got > 0)) { logmsg("Request would overflow buffer, closing connection"); /* dump request received so far to external file anyway */ reqbuf[REQBUFSIZ-1] = '\0'; fail = 1; } else if(req->offset > REQBUFSIZ-1) { logmsg("Request buffer overflow, closing connection"); /* dump request received so far to external file anyway */ reqbuf[REQBUFSIZ-1] = '\0'; fail = 1; } else reqbuf[req->offset] = '\0'; /* at the end of a request dump it to an external file */ if(fail || req->done_processing) storerequest(reqbuf, req->offset); if(got_exit_signal) return -1; return fail ? -1 : 1; } /* returns -1 on failure */ static int send_doc(curl_socket_t sock, struct httprequest *req) { ssize_t written; size_t count; const char *buffer; char *ptr = NULL; FILE *stream; char *cmd = NULL; size_t cmdsize = 0; FILE *dump; bool persistent = TRUE; bool sendfailure = FALSE; size_t responsesize; int error = 0; int res; const char *responsedump = is_proxy?RESPONSE_PROXY_DUMP:RESPONSE_DUMP; static char weare[256]; switch(req->rcmd) { default: case RCMD_NORMALREQ: break; /* continue with business as usual */ case RCMD_STREAM: #define STREAMTHIS "a string to stream 01234567890\n" count = strlen(STREAMTHIS); for(;;) { written = swrite(sock, STREAMTHIS, count); if(got_exit_signal) return -1; if(written != (ssize_t)count) { logmsg("Stopped streaming"); break; } } return -1; case RCMD_IDLE: /* Do nothing. Sit idle. Pretend it rains. */ return 0; } req->open = FALSE; if(req->testno < 0) { size_t msglen; char msgbuf[64]; switch(req->testno) { case DOCNUMBER_QUIT: logmsg("Replying to QUIT"); buffer = docquit; break; case DOCNUMBER_WERULEZ: /* we got a "friends?" question, reply back that we sure are */ logmsg("Identifying ourselves as friends"); msnprintf(msgbuf, sizeof(msgbuf), "WE ROOLZ: %" CURL_FORMAT_CURL_OFF_T "\r\n", our_getpid()); msglen = strlen(msgbuf); if(use_gopher) msnprintf(weare, sizeof(weare), "%s", msgbuf); else msnprintf(weare, sizeof(weare), "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s", msglen, msgbuf); buffer = weare; break; case DOCNUMBER_404: default: logmsg("Replying to with a 404"); buffer = doc404; break; } count = strlen(buffer); } else { char partbuf[80]; /* select the <data> tag for "normal" requests and the <connect> one for CONNECT requests (within the <reply> section) */ const char *section = req->connect_request?"connect":"data"; if(req->partno) msnprintf(partbuf, sizeof(partbuf), "%s%ld", section, req->partno); else msnprintf(partbuf, sizeof(partbuf), "%s", section); logmsg("Send response test%ld section <%s>", req->testno, partbuf); stream = test2fopen(req->testno); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); return 0; } else { error = getpart(&ptr, &count, "reply", partbuf, stream); fclose(stream); if(error) { logmsg("getpart() failed with error: %d", error); return 0; } buffer = ptr; } if(got_exit_signal) { free(ptr); return -1; } /* re-open the same file again */ stream = test2fopen(req->testno); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); free(ptr); return 0; } else { /* get the custom server control "commands" */ error = getpart(&cmd, &cmdsize, "reply", "postcmd", stream); fclose(stream); if(error) { logmsg("getpart() failed with error: %d", error); free(ptr); return 0; } } } if(got_exit_signal) { free(ptr); free(cmd); return -1; } /* If the word 'swsclose' is present anywhere in the reply chunk, the connection will be closed after the data has been sent to the requesting client... */ if(strstr(buffer, "swsclose") || !count || req->close) { persistent = FALSE; logmsg("connection close instruction \"swsclose\" found in response"); } if(strstr(buffer, "swsbounce")) { prevbounce = TRUE; logmsg("enable \"swsbounce\" in the next request"); } else prevbounce = FALSE; dump = fopen(responsedump, "ab"); if(!dump) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg(" [5] Error opening file: %s", responsedump); free(ptr); free(cmd); return -1; } responsesize = count; do { /* Ok, we send no more than N bytes at a time, just to make sure that larger chunks are split up so that the client will need to do multiple recv() calls to get it and thus we exercise that code better */ size_t num = count; if(num > 20) num = 20; retry: written = swrite(sock, buffer, num); if(written < 0) { if((EWOULDBLOCK == SOCKERRNO) || (EAGAIN == SOCKERRNO)) { wait_ms(10); goto retry; } sendfailure = TRUE; break; } /* write to file as well */ fwrite(buffer, 1, (size_t)written, dump); count -= written; buffer += written; if(req->writedelay) { int quarters = req->writedelay * 4; logmsg("Pausing %d seconds", req->writedelay); while((quarters > 0) && !got_exit_signal) { quarters--; wait_ms(250); } } } while((count > 0) && !got_exit_signal); do { res = fclose(dump); } while(res && ((error = errno) == EINTR)); if(res) logmsg("Error closing file %s error: %d %s", responsedump, error, strerror(error)); if(got_exit_signal) { free(ptr); free(cmd); return -1; } if(sendfailure) { logmsg("Sending response failed. Only (%zu bytes) of (%zu bytes) " "were sent", responsesize-count, responsesize); prevtestno = req->testno; prevpartno = req->partno; free(ptr); free(cmd); return -1; } logmsg("Response sent (%zu bytes) and written to %s", responsesize, responsedump); free(ptr); if(cmdsize > 0) { char command[32]; int quarters; int num; ptr = cmd; do { if(2 == sscanf(ptr, "%31s %d", command, &num)) { if(!strcmp("wait", command)) { logmsg("Told to sleep for %d seconds", num); quarters = num * 4; while((quarters > 0) && !got_exit_signal) { quarters--; res = wait_ms(250); if(res) { /* should not happen */ error = errno; logmsg("wait_ms() failed with error: (%d) %s", error, strerror(error)); break; } } if(!quarters) logmsg("Continuing after sleeping %d seconds", num); } else logmsg("Unknown command in reply command section"); } ptr = strchr(ptr, '\n'); if(ptr) ptr++; else ptr = NULL; } while(ptr && *ptr); } free(cmd); req->open = use_gopher?FALSE:persistent; prevtestno = req->testno; prevpartno = req->partno; return 0; } static curl_socket_t connect_to(const char *ipaddr, unsigned short port) { srvr_sockaddr_union_t serveraddr; curl_socket_t serverfd; int error; int rc = 0; const char *op_br = ""; const char *cl_br = ""; #ifdef ENABLE_IPV6 if(socket_domain == AF_INET6) { op_br = "["; cl_br = "]"; } #endif if(!ipaddr) return CURL_SOCKET_BAD; logmsg("about to connect to %s%s%s:%hu", op_br, ipaddr, cl_br, port); serverfd = socket(socket_domain, SOCK_STREAM, 0); if(CURL_SOCKET_BAD == serverfd) { error = SOCKERRNO; logmsg("Error creating socket for server connection: (%d) %s", error, strerror(error)); return CURL_SOCKET_BAD; } #ifdef TCP_NODELAY if(socket_domain_is_ip()) { /* Disable the Nagle algorithm */ curl_socklen_t flag = 1; if(0 != setsockopt(serverfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flag, sizeof(flag))) logmsg("====> TCP_NODELAY for server connection failed"); } #endif switch(socket_domain) { case AF_INET: memset(&serveraddr.sa4, 0, sizeof(serveraddr.sa4)); serveraddr.sa4.sin_family = AF_INET; serveraddr.sa4.sin_port = htons(port); if(Curl_inet_pton(AF_INET, ipaddr, &serveraddr.sa4.sin_addr) < 1) { logmsg("Error inet_pton failed AF_INET conversion of '%s'", ipaddr); sclose(serverfd); return CURL_SOCKET_BAD; } rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa4)); break; #ifdef ENABLE_IPV6 case AF_INET6: memset(&serveraddr.sa6, 0, sizeof(serveraddr.sa6)); serveraddr.sa6.sin6_family = AF_INET6; serveraddr.sa6.sin6_port = htons(port); if(Curl_inet_pton(AF_INET6, ipaddr, &serveraddr.sa6.sin6_addr) < 1) { logmsg("Error inet_pton failed AF_INET6 conversion of '%s'", ipaddr); sclose(serverfd); return CURL_SOCKET_BAD; } rc = connect(serverfd, &serveraddr.sa, sizeof(serveraddr.sa6)); break; #endif /* ENABLE_IPV6 */ #ifdef USE_UNIX_SOCKETS case AF_UNIX: logmsg("Proxying through Unix socket is not (yet?) supported."); return CURL_SOCKET_BAD; #endif /* USE_UNIX_SOCKETS */ } if(got_exit_signal) { sclose(serverfd); return CURL_SOCKET_BAD; } if(rc) { error = SOCKERRNO; logmsg("Error connecting to server port %hu: (%d) %s", port, error, strerror(error)); sclose(serverfd); return CURL_SOCKET_BAD; } logmsg("connected fine to %s%s%s:%hu, now tunnel", op_br, ipaddr, cl_br, port); return serverfd; } /* * A CONNECT has been received, a CONNECT response has been sent. * * This function needs to connect to the server, and then pass data between * the client and the server back and forth until the connection is closed by * either end. * * When doing FTP through a CONNECT proxy, we expect that the data connection * will be setup while the first connect is still being kept up. Therefore we * must accept a new connection and deal with it appropriately. */ #define data_or_ctrl(x) ((x)?"DATA":"CTRL") #define CTRL 0 #define DATA 1 static void http_connect(curl_socket_t *infdp, curl_socket_t rootfd, const char *ipaddr, unsigned short ipport) { curl_socket_t serverfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD}; curl_socket_t clientfd[2] = {CURL_SOCKET_BAD, CURL_SOCKET_BAD}; ssize_t toc[2] = {0, 0}; /* number of bytes to client */ ssize_t tos[2] = {0, 0}; /* number of bytes to server */ char readclient[2][256]; char readserver[2][256]; bool poll_client_rd[2] = { TRUE, TRUE }; bool poll_server_rd[2] = { TRUE, TRUE }; bool poll_client_wr[2] = { TRUE, TRUE }; bool poll_server_wr[2] = { TRUE, TRUE }; bool primary = FALSE; bool secondary = FALSE; int max_tunnel_idx; /* CTRL or DATA */ int loop; int i; int timeout_count = 0; /* primary tunnel client endpoint already connected */ clientfd[CTRL] = *infdp; /* Sleep here to make sure the client reads CONNECT response's 'end of headers' separate from the server data that follows. This is done to prevent triggering libcurl known bug #39. */ for(loop = 2; (loop > 0) && !got_exit_signal; loop--) wait_ms(250); if(got_exit_signal) goto http_connect_cleanup; serverfd[CTRL] = connect_to(ipaddr, ipport); if(serverfd[CTRL] == CURL_SOCKET_BAD) goto http_connect_cleanup; /* Primary tunnel socket endpoints are now connected. Tunnel data back and forth over the primary tunnel until client or server breaks the primary tunnel, simultaneously allowing establishment, operation and teardown of a secondary tunnel that may be used for passive FTP data connection. */ max_tunnel_idx = CTRL; primary = TRUE; while(!got_exit_signal) { fd_set input; fd_set output; struct timeval timeout = {1, 0}; /* 1000 ms */ ssize_t rc; curl_socket_t maxfd = (curl_socket_t)-1; FD_ZERO(&input); FD_ZERO(&output); if((clientfd[DATA] == CURL_SOCKET_BAD) && (serverfd[DATA] == CURL_SOCKET_BAD) && poll_client_rd[CTRL] && poll_client_wr[CTRL] && poll_server_rd[CTRL] && poll_server_wr[CTRL]) { /* listener socket is monitored to allow client to establish secondary tunnel only when this tunnel is not established and primary one is fully operational */ FD_SET(rootfd, &input); maxfd = rootfd; } /* set tunnel sockets to wait for */ for(i = 0; i <= max_tunnel_idx; i++) { /* client side socket monitoring */ if(clientfd[i] != CURL_SOCKET_BAD) { if(poll_client_rd[i]) { /* unless told not to do so, monitor readability */ FD_SET(clientfd[i], &input); if(clientfd[i] > maxfd) maxfd = clientfd[i]; } if(poll_client_wr[i] && toc[i]) { /* unless told not to do so, monitor writability if there is data ready to be sent to client */ FD_SET(clientfd[i], &output); if(clientfd[i] > maxfd) maxfd = clientfd[i]; } } /* server side socket monitoring */ if(serverfd[i] != CURL_SOCKET_BAD) { if(poll_server_rd[i]) { /* unless told not to do so, monitor readability */ FD_SET(serverfd[i], &input); if(serverfd[i] > maxfd) maxfd = serverfd[i]; } if(poll_server_wr[i] && tos[i]) { /* unless told not to do so, monitor writability if there is data ready to be sent to server */ FD_SET(serverfd[i], &output); if(serverfd[i] > maxfd) maxfd = serverfd[i]; } } } if(got_exit_signal) break; do { rc = select((int)maxfd + 1, &input, &output, NULL, &timeout); } while(rc < 0 && errno == EINTR && !got_exit_signal); if(got_exit_signal) break; if(rc > 0) { /* socket action */ bool tcp_fin_wr = FALSE; timeout_count = 0; /* ---------------------------------------------------------- */ /* passive mode FTP may establish a secondary tunnel */ if((clientfd[DATA] == CURL_SOCKET_BAD) && (serverfd[DATA] == CURL_SOCKET_BAD) && FD_ISSET(rootfd, &input)) { /* a new connection on listener socket (most likely from client) */ curl_socket_t datafd = accept(rootfd, NULL, NULL); if(datafd != CURL_SOCKET_BAD) { static struct httprequest *req2; int err = 0; if(!req2) { req2 = malloc(sizeof(*req2)); if(!req2) exit(1); } memset(req2, 0, sizeof(*req2)); logmsg("====> Client connect DATA"); #ifdef TCP_NODELAY if(socket_domain_is_ip()) { /* Disable the Nagle algorithm */ curl_socklen_t flag = 1; if(0 != setsockopt(datafd, IPPROTO_TCP, TCP_NODELAY, (void *)&flag, sizeof(flag))) logmsg("====> TCP_NODELAY for client DATA connection failed"); } #endif init_httprequest(req2); while(!req2->done_processing) { err = get_request(datafd, req2); if(err < 0) { /* this socket must be closed, done or not */ break; } } /* skip this and close the socket if err < 0 */ if(err >= 0) { err = send_doc(datafd, req2); if(!err && req2->connect_request) { /* sleep to prevent triggering libcurl known bug #39. */ for(loop = 2; (loop > 0) && !got_exit_signal; loop--) wait_ms(250); if(!got_exit_signal) { /* connect to the server */ serverfd[DATA] = connect_to(ipaddr, req2->connect_port); if(serverfd[DATA] != CURL_SOCKET_BAD) { /* secondary tunnel established, now we have two connections */ poll_client_rd[DATA] = TRUE; poll_client_wr[DATA] = TRUE; poll_server_rd[DATA] = TRUE; poll_server_wr[DATA] = TRUE; max_tunnel_idx = DATA; secondary = TRUE; toc[DATA] = 0; tos[DATA] = 0; clientfd[DATA] = datafd; datafd = CURL_SOCKET_BAD; } } } } if(datafd != CURL_SOCKET_BAD) { /* secondary tunnel not established */ shutdown(datafd, SHUT_RDWR); sclose(datafd); } } if(got_exit_signal) break; } /* ---------------------------------------------------------- */ /* react to tunnel endpoint readable/writable notifications */ for(i = 0; i <= max_tunnel_idx; i++) { size_t len; if(clientfd[i] != CURL_SOCKET_BAD) { len = sizeof(readclient[i]) - tos[i]; if(len && FD_ISSET(clientfd[i], &input)) { /* read from client */ rc = sread(clientfd[i], &readclient[i][tos[i]], len); if(rc <= 0) { logmsg("[%s] got %zd, STOP READING client", data_or_ctrl(i), rc); shutdown(clientfd[i], SHUT_RD); poll_client_rd[i] = FALSE; } else { logmsg("[%s] READ %zd bytes from client", data_or_ctrl(i), rc); logmsg("[%s] READ \"%s\"", data_or_ctrl(i), data_to_hex(&readclient[i][tos[i]], rc)); tos[i] += rc; } } } if(serverfd[i] != CURL_SOCKET_BAD) { len = sizeof(readserver[i])-toc[i]; if(len && FD_ISSET(serverfd[i], &input)) { /* read from server */ rc = sread(serverfd[i], &readserver[i][toc[i]], len); if(rc <= 0) { logmsg("[%s] got %zd, STOP READING server", data_or_ctrl(i), rc); shutdown(serverfd[i], SHUT_RD); poll_server_rd[i] = FALSE; } else { logmsg("[%s] READ %zd bytes from server", data_or_ctrl(i), rc); logmsg("[%s] READ \"%s\"", data_or_ctrl(i), data_to_hex(&readserver[i][toc[i]], rc)); toc[i] += rc; } } } if(clientfd[i] != CURL_SOCKET_BAD) { if(toc[i] && FD_ISSET(clientfd[i], &output)) { /* write to client */ rc = swrite(clientfd[i], readserver[i], toc[i]); if(rc <= 0) { logmsg("[%s] got %zd, STOP WRITING client", data_or_ctrl(i), rc); shutdown(clientfd[i], SHUT_WR); poll_client_wr[i] = FALSE; tcp_fin_wr = TRUE; } else { logmsg("[%s] SENT %zd bytes to client", data_or_ctrl(i), rc); logmsg("[%s] SENT \"%s\"", data_or_ctrl(i), data_to_hex(readserver[i], rc)); if(toc[i] - rc) memmove(&readserver[i][0], &readserver[i][rc], toc[i]-rc); toc[i] -= rc; } } } if(serverfd[i] != CURL_SOCKET_BAD) { if(tos[i] && FD_ISSET(serverfd[i], &output)) { /* write to server */ rc = swrite(serverfd[i], readclient[i], tos[i]); if(rc <= 0) { logmsg("[%s] got %zd, STOP WRITING server", data_or_ctrl(i), rc); shutdown(serverfd[i], SHUT_WR); poll_server_wr[i] = FALSE; tcp_fin_wr = TRUE; } else { logmsg("[%s] SENT %zd bytes to server", data_or_ctrl(i), rc); logmsg("[%s] SENT \"%s\"", data_or_ctrl(i), data_to_hex(readclient[i], rc)); if(tos[i] - rc) memmove(&readclient[i][0], &readclient[i][rc], tos[i]-rc); tos[i] -= rc; } } } } if(got_exit_signal) break; /* ---------------------------------------------------------- */ /* endpoint read/write disabling, endpoint closing and tunnel teardown */ for(i = 0; i <= max_tunnel_idx; i++) { for(loop = 2; loop > 0; loop--) { /* loop twice to satisfy condition interdependencies without having to await select timeout or another socket event */ if(clientfd[i] != CURL_SOCKET_BAD) { if(poll_client_rd[i] && !poll_server_wr[i]) { logmsg("[%s] DISABLED READING client", data_or_ctrl(i)); shutdown(clientfd[i], SHUT_RD); poll_client_rd[i] = FALSE; } if(poll_client_wr[i] && !poll_server_rd[i] && !toc[i]) { logmsg("[%s] DISABLED WRITING client", data_or_ctrl(i)); shutdown(clientfd[i], SHUT_WR); poll_client_wr[i] = FALSE; tcp_fin_wr = TRUE; } } if(serverfd[i] != CURL_SOCKET_BAD) { if(poll_server_rd[i] && !poll_client_wr[i]) { logmsg("[%s] DISABLED READING server", data_or_ctrl(i)); shutdown(serverfd[i], SHUT_RD); poll_server_rd[i] = FALSE; } if(poll_server_wr[i] && !poll_client_rd[i] && !tos[i]) { logmsg("[%s] DISABLED WRITING server", data_or_ctrl(i)); shutdown(serverfd[i], SHUT_WR); poll_server_wr[i] = FALSE; tcp_fin_wr = TRUE; } } } } if(tcp_fin_wr) /* allow kernel to place FIN bit packet on the wire */ wait_ms(250); /* socket clearing */ for(i = 0; i <= max_tunnel_idx; i++) { for(loop = 2; loop > 0; loop--) { if(clientfd[i] != CURL_SOCKET_BAD) { if(!poll_client_wr[i] && !poll_client_rd[i]) { logmsg("[%s] CLOSING client socket", data_or_ctrl(i)); sclose(clientfd[i]); clientfd[i] = CURL_SOCKET_BAD; if(serverfd[i] == CURL_SOCKET_BAD) { logmsg("[%s] ENDING", data_or_ctrl(i)); if(i == DATA) secondary = FALSE; else primary = FALSE; } } } if(serverfd[i] != CURL_SOCKET_BAD) { if(!poll_server_wr[i] && !poll_server_rd[i]) { logmsg("[%s] CLOSING server socket", data_or_ctrl(i)); sclose(serverfd[i]); serverfd[i] = CURL_SOCKET_BAD; if(clientfd[i] == CURL_SOCKET_BAD) { logmsg("[%s] ENDING", data_or_ctrl(i)); if(i == DATA) secondary = FALSE; else primary = FALSE; } } } } } /* ---------------------------------------------------------- */ max_tunnel_idx = secondary ? DATA : CTRL; if(!primary) /* exit loop upon primary tunnel teardown */ break; } /* (rc > 0) */ else { timeout_count++; if(timeout_count > 5) { logmsg("CONNECT proxy timeout after %d idle seconds!", timeout_count); break; } } } http_connect_cleanup: for(i = DATA; i >= CTRL; i--) { if(serverfd[i] != CURL_SOCKET_BAD) { logmsg("[%s] CLOSING server socket (cleanup)", data_or_ctrl(i)); shutdown(serverfd[i], SHUT_RDWR); sclose(serverfd[i]); } if(clientfd[i] != CURL_SOCKET_BAD) { logmsg("[%s] CLOSING client socket (cleanup)", data_or_ctrl(i)); shutdown(clientfd[i], SHUT_RDWR); sclose(clientfd[i]); } if((serverfd[i] != CURL_SOCKET_BAD) || (clientfd[i] != CURL_SOCKET_BAD)) { logmsg("[%s] ABORTING", data_or_ctrl(i)); } } *infdp = CURL_SOCKET_BAD; } static void http2(struct httprequest *req) { (void)req; logmsg("switched to http2"); /* left to implement */ } /* returns a socket handle, or 0 if there are no more waiting sockets, or < 0 if there was an error */ static curl_socket_t accept_connection(curl_socket_t sock) { curl_socket_t msgsock = CURL_SOCKET_BAD; int error; int flag = 1; if(MAX_SOCKETS == num_sockets) { logmsg("Too many open sockets!"); return CURL_SOCKET_BAD; } msgsock = accept(sock, NULL, NULL); if(got_exit_signal) { if(CURL_SOCKET_BAD != msgsock) sclose(msgsock); return CURL_SOCKET_BAD; } if(CURL_SOCKET_BAD == msgsock) { error = SOCKERRNO; if(EAGAIN == error || EWOULDBLOCK == error) { /* nothing to accept */ return 0; } logmsg("MAJOR ERROR: accept() failed with error: (%d) %s", error, strerror(error)); return CURL_SOCKET_BAD; } if(0 != curlx_nonblock(msgsock, TRUE)) { error = SOCKERRNO; logmsg("curlx_nonblock failed with error: (%d) %s", error, strerror(error)); sclose(msgsock); return CURL_SOCKET_BAD; } if(0 != setsockopt(msgsock, SOL_SOCKET, SO_KEEPALIVE, (void *)&flag, sizeof(flag))) { error = SOCKERRNO; logmsg("setsockopt(SO_KEEPALIVE) failed with error: (%d) %s", error, strerror(error)); sclose(msgsock); return CURL_SOCKET_BAD; } /* ** As soon as this server accepts a connection from the test harness it ** must set the server logs advisor read lock to indicate that server ** logs should not be read until this lock is removed by this server. */ if(!serverlogslocked) set_advisor_read_lock(SERVERLOGS_LOCK); serverlogslocked += 1; logmsg("====> Client connect"); all_sockets[num_sockets] = msgsock; num_sockets += 1; #ifdef TCP_NODELAY if(socket_domain_is_ip()) { /* * Disable the Nagle algorithm to make it easier to send out a large * response in many small segments to torture the clients more. */ if(0 != setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY, (void *)&flag, sizeof(flag))) logmsg("====> TCP_NODELAY failed"); } #endif return msgsock; } /* returns 1 if the connection should be serviced again immediately, 0 if there is no data waiting, or < 0 if it should be closed */ static int service_connection(curl_socket_t msgsock, struct httprequest *req, curl_socket_t listensock, const char *connecthost) { if(got_exit_signal) return -1; while(!req->done_processing) { int rc = get_request(msgsock, req); if(rc <= 0) { /* Nothing further to read now, possibly because the socket was closed */ return rc; } } if(prevbounce) { /* bounce treatment requested */ if((req->testno == prevtestno) && (req->partno == prevpartno)) { req->partno++; logmsg("BOUNCE part number to %ld", req->partno); } else { prevbounce = FALSE; prevtestno = -1; prevpartno = -1; } } send_doc(msgsock, req); if(got_exit_signal) return -1; if(req->testno < 0) { logmsg("special request received, no persistency"); return -1; } if(!req->open) { logmsg("instructed to close connection after server-reply"); return -1; } if(req->connect_request) { /* a CONNECT request, setup and talk the tunnel */ if(!is_proxy) { logmsg("received CONNECT but isn't running as proxy!"); return 1; } else { http_connect(&msgsock, listensock, connecthost, req->connect_port); return -1; } } if(req->upgrade_request) { /* an upgrade request, switch to http2 here */ http2(req); return -1; } /* if we got a CONNECT, loop and get another request as well! */ if(req->open) { logmsg("=> persistent connection request ended, awaits new request\n"); return 1; } return -1; } int main(int argc, char *argv[]) { srvr_sockaddr_union_t me; curl_socket_t sock = CURL_SOCKET_BAD; int wrotepidfile = 0; int wroteportfile = 0; int flag; unsigned short port = DEFAULT_PORT; #ifdef USE_UNIX_SOCKETS const char *unix_socket = NULL; bool unlink_socket = false; #endif const char *pidname = ".http.pid"; const char *portname = ".http.port"; struct httprequest *req = NULL; int rc = 0; int error; int arg = 1; const char *connecthost = "127.0.0.1"; const char *socket_type = "IPv4"; char port_str[11]; const char *location_str = port_str; /* a default CONNECT port is basically pointless but still ... */ size_t socket_idx; while(argc>arg) { if(!strcmp("--version", argv[arg])) { puts("sws IPv4" #ifdef ENABLE_IPV6 "/IPv6" #endif #ifdef USE_UNIX_SOCKETS "/unix" #endif ); return 0; } else if(!strcmp("--pidfile", argv[arg])) { arg++; if(argc>arg) pidname = argv[arg++]; } else if(!strcmp("--portfile", argv[arg])) { arg++; if(argc>arg) portname = argv[arg++]; } else if(!strcmp("--logfile", argv[arg])) { arg++; if(argc>arg) serverlogfile = argv[arg++]; } else if(!strcmp("--cmdfile", argv[arg])) { arg++; if(argc>arg) cmdfile = argv[arg++]; } else if(!strcmp("--gopher", argv[arg])) { arg++; use_gopher = TRUE; end_of_headers = "\r\n"; /* gopher style is much simpler */ } else if(!strcmp("--ipv4", argv[arg])) { socket_type = "IPv4"; socket_domain = AF_INET; location_str = port_str; arg++; } else if(!strcmp("--ipv6", argv[arg])) { #ifdef ENABLE_IPV6 socket_type = "IPv6"; socket_domain = AF_INET6; location_str = port_str; #endif arg++; } else if(!strcmp("--unix-socket", argv[arg])) { arg++; if(argc>arg) { #ifdef USE_UNIX_SOCKETS unix_socket = argv[arg]; if(strlen(unix_socket) >= sizeof(me.sau.sun_path)) { fprintf(stderr, "sws: socket path must be shorter than %zu chars\n", sizeof(me.sau.sun_path)); return 0; } socket_type = "unix"; socket_domain = AF_UNIX; location_str = unix_socket; #endif arg++; } } else if(!strcmp("--port", argv[arg])) { arg++; if(argc>arg) { char *endptr; unsigned long ulnum = strtoul(argv[arg], &endptr, 10); if((endptr != argv[arg] + strlen(argv[arg])) || (ulnum && ((ulnum < 1025UL) || (ulnum > 65535UL)))) { fprintf(stderr, "sws: invalid --port argument (%s)\n", argv[arg]); return 0; } port = curlx_ultous(ulnum); arg++; } } else if(!strcmp("--srcdir", argv[arg])) { arg++; if(argc>arg) { path = argv[arg]; arg++; } } else if(!strcmp("--connect", argv[arg])) { /* The connect host IP number that the proxy will connect to no matter what the client asks for, but also use this as a hint that we run as a proxy and do a few different internal choices */ arg++; if(argc>arg) { connecthost = argv[arg]; arg++; is_proxy = TRUE; logmsg("Run as proxy, CONNECT to host %s", connecthost); } } else { puts("Usage: sws [option]\n" " --version\n" " --logfile [file]\n" " --pidfile [file]\n" " --portfile [file]\n" " --ipv4\n" " --ipv6\n" " --unix-socket [file]\n" " --port [port]\n" " --srcdir [path]\n" " --connect [ip4-addr]\n" " --gopher"); return 0; } } #ifdef WIN32 win32_init(); atexit(win32_cleanup); #endif install_signal_handlers(false); req = calloc(1, sizeof(*req)); if(!req) goto sws_cleanup; sock = socket(socket_domain, SOCK_STREAM, 0); all_sockets[0] = sock; num_sockets = 1; if(CURL_SOCKET_BAD == sock) { error = SOCKERRNO; logmsg("Error creating socket: (%d) %s", error, strerror(error)); goto sws_cleanup; } flag = 1; if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, sizeof(flag))) { error = SOCKERRNO; logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", error, strerror(error)); goto sws_cleanup; } if(0 != curlx_nonblock(sock, TRUE)) { error = SOCKERRNO; logmsg("curlx_nonblock failed with error: (%d) %s", error, strerror(error)); goto sws_cleanup; } switch(socket_domain) { case AF_INET: memset(&me.sa4, 0, sizeof(me.sa4)); me.sa4.sin_family = AF_INET; me.sa4.sin_addr.s_addr = INADDR_ANY; me.sa4.sin_port = htons(port); rc = bind(sock, &me.sa, sizeof(me.sa4)); break; #ifdef ENABLE_IPV6 case AF_INET6: memset(&me.sa6, 0, sizeof(me.sa6)); me.sa6.sin6_family = AF_INET6; me.sa6.sin6_addr = in6addr_any; me.sa6.sin6_port = htons(port); rc = bind(sock, &me.sa, sizeof(me.sa6)); break; #endif /* ENABLE_IPV6 */ #ifdef USE_UNIX_SOCKETS case AF_UNIX: memset(&me.sau, 0, sizeof(me.sau)); me.sau.sun_family = AF_UNIX; strncpy(me.sau.sun_path, unix_socket, sizeof(me.sau.sun_path) - 1); rc = bind(sock, &me.sa, sizeof(me.sau)); if(0 != rc && errno == EADDRINUSE) { struct_stat statbuf; /* socket already exists. Perhaps it is stale? */ curl_socket_t unixfd = socket(AF_UNIX, SOCK_STREAM, 0); if(CURL_SOCKET_BAD == unixfd) { error = SOCKERRNO; logmsg("Error binding socket, failed to create socket at %s: (%d) %s", unix_socket, error, strerror(error)); goto sws_cleanup; } /* check whether the server is alive */ rc = connect(unixfd, &me.sa, sizeof(me.sau)); error = errno; sclose(unixfd); if(ECONNREFUSED != error) { logmsg("Error binding socket, failed to connect to %s: (%d) %s", unix_socket, error, strerror(error)); goto sws_cleanup; } /* socket server is not alive, now check if it was actually a socket. */ #ifdef WIN32 /* Windows does not have lstat function. */ rc = curlx_win32_stat(unix_socket, &statbuf); #else rc = lstat(unix_socket, &statbuf); #endif if(0 != rc) { logmsg("Error binding socket, failed to stat %s: (%d) %s", unix_socket, errno, strerror(errno)); goto sws_cleanup; } #ifdef S_IFSOCK if((statbuf.st_mode & S_IFSOCK) != S_IFSOCK) { logmsg("Error binding socket, failed to stat %s: (%d) %s", unix_socket, error, strerror(error)); goto sws_cleanup; } #endif /* dead socket, cleanup and retry bind */ rc = unlink(unix_socket); if(0 != rc) { logmsg("Error binding socket, failed to unlink %s: (%d) %s", unix_socket, errno, strerror(errno)); goto sws_cleanup; } /* stale socket is gone, retry bind */ rc = bind(sock, &me.sa, sizeof(me.sau)); } break; #endif /* USE_UNIX_SOCKETS */ } if(0 != rc) { error = SOCKERRNO; logmsg("Error binding socket: (%d) %s", error, strerror(error)); goto sws_cleanup; } if(!port) { /* The system was supposed to choose a port number, figure out which port we actually got and update the listener port value with it. */ curl_socklen_t la_size; srvr_sockaddr_union_t localaddr; #ifdef ENABLE_IPV6 if(socket_domain != AF_INET6) #endif la_size = sizeof(localaddr.sa4); #ifdef ENABLE_IPV6 else la_size = sizeof(localaddr.sa6); #endif memset(&localaddr.sa, 0, (size_t)la_size); if(getsockname(sock, &localaddr.sa, &la_size) < 0) { error = SOCKERRNO; logmsg("getsockname() failed with error: (%d) %s", error, strerror(error)); sclose(sock); goto sws_cleanup; } switch(localaddr.sa.sa_family) { case AF_INET: port = ntohs(localaddr.sa4.sin_port); break; #ifdef ENABLE_IPV6 case AF_INET6: port = ntohs(localaddr.sa6.sin6_port); break; #endif default: break; } if(!port) { /* Real failure, listener port shall not be zero beyond this point. */ logmsg("Apparently getsockname() succeeded, with listener port zero."); logmsg("A valid reason for this failure is a binary built without"); logmsg("proper network library linkage. This might not be the only"); logmsg("reason, but double check it before anything else."); sclose(sock); goto sws_cleanup; } } #ifdef USE_UNIX_SOCKETS if(socket_domain != AF_UNIX) #endif msnprintf(port_str, sizeof(port_str), "port %hu", port); logmsg("Running %s %s version on %s", use_gopher?"GOPHER":"HTTP", socket_type, location_str); /* start accepting connections */ rc = listen(sock, 5); if(0 != rc) { error = SOCKERRNO; logmsg("listen() failed with error: (%d) %s", error, strerror(error)); goto sws_cleanup; } #ifdef USE_UNIX_SOCKETS /* listen succeeds, so let's assume a valid listening Unix socket */ unlink_socket = true; #endif /* ** As soon as this server writes its pid file the test harness will ** attempt to connect to this server and initiate its verification. */ wrotepidfile = write_pidfile(pidname); if(!wrotepidfile) goto sws_cleanup; wroteportfile = write_portfile(portname, port); if(!wroteportfile) goto sws_cleanup; /* initialization of httprequest struct is done before get_request(), but the pipelining struct field must be initialized previously to FALSE every time a new connection arrives. */ init_httprequest(req); for(;;) { fd_set input; fd_set output; struct timeval timeout = {0, 250000L}; /* 250 ms */ curl_socket_t maxfd = (curl_socket_t)-1; int active; /* Clear out closed sockets */ for(socket_idx = num_sockets - 1; socket_idx >= 1; --socket_idx) { if(CURL_SOCKET_BAD == all_sockets[socket_idx]) { char *dst = (char *) (all_sockets + socket_idx); char *src = (char *) (all_sockets + socket_idx + 1); char *end = (char *) (all_sockets + num_sockets); memmove(dst, src, end - src); num_sockets -= 1; } } if(got_exit_signal) goto sws_cleanup; /* Set up for select */ FD_ZERO(&input); FD_ZERO(&output); for(socket_idx = 0; socket_idx < num_sockets; ++socket_idx) { /* Listen on all sockets */ FD_SET(all_sockets[socket_idx], &input); if(all_sockets[socket_idx] > maxfd) maxfd = all_sockets[socket_idx]; } if(got_exit_signal) goto sws_cleanup; do { rc = select((int)maxfd + 1, &input, &output, NULL, &timeout); } while(rc < 0 && errno == EINTR && !got_exit_signal); if(got_exit_signal) goto sws_cleanup; if(rc < 0) { error = SOCKERRNO; logmsg("select() failed with error: (%d) %s", error, strerror(error)); goto sws_cleanup; } if(rc == 0) { /* Timed out - try again */ continue; } active = rc; /* a positive number */ /* Check if the listening socket is ready to accept */ if(FD_ISSET(all_sockets[0], &input)) { /* Service all queued connections */ curl_socket_t msgsock; do { msgsock = accept_connection(sock); logmsg("accept_connection %d returned %d", sock, msgsock); if(CURL_SOCKET_BAD == msgsock) goto sws_cleanup; } while(msgsock > 0); active--; } /* Service all connections that are ready */ for(socket_idx = 1; (socket_idx < num_sockets) && active; ++socket_idx) { if(FD_ISSET(all_sockets[socket_idx], &input)) { active--; if(got_exit_signal) goto sws_cleanup; /* Service this connection until it has nothing available */ do { rc = service_connection(all_sockets[socket_idx], req, sock, connecthost); if(got_exit_signal) goto sws_cleanup; if(rc < 0) { logmsg("====> Client disconnect %d", req->connmon); if(req->connmon) { const char *keepopen = "[DISCONNECT]\n"; storerequest(keepopen, strlen(keepopen)); } if(!req->open) /* When instructed to close connection after server-reply we wait a very small amount of time before doing so. If this is not done client might get an ECONNRESET before reading a single byte of server-reply. */ wait_ms(50); if(all_sockets[socket_idx] != CURL_SOCKET_BAD) { sclose(all_sockets[socket_idx]); all_sockets[socket_idx] = CURL_SOCKET_BAD; } serverlogslocked -= 1; if(!serverlogslocked) clear_advisor_read_lock(SERVERLOGS_LOCK); if(req->testno == DOCNUMBER_QUIT) goto sws_cleanup; } /* Reset the request, unless we're still in the middle of reading */ if(rc) init_httprequest(req); } while(rc > 0); } } if(got_exit_signal) goto sws_cleanup; } sws_cleanup: for(socket_idx = 1; socket_idx < num_sockets; ++socket_idx) if((all_sockets[socket_idx] != sock) && (all_sockets[socket_idx] != CURL_SOCKET_BAD)) sclose(all_sockets[socket_idx]); if(sock != CURL_SOCKET_BAD) sclose(sock); #ifdef USE_UNIX_SOCKETS if(unlink_socket && socket_domain == AF_UNIX) { rc = unlink(unix_socket); logmsg("unlink(%s) = %d (%s)", unix_socket, rc, strerror(rc)); } #endif free(req); if(got_exit_signal) logmsg("signalled to die"); if(wrotepidfile) unlink(pidname); if(wroteportfile) unlink(portname); if(serverlogslocked) { serverlogslocked = 0; clear_advisor_read_lock(SERVERLOGS_LOCK); } restore_signal_handlers(false); if(got_exit_signal) { logmsg("========> %s sws (%s pid: %ld) exits with signal (%d)", socket_type, location_str, (long)getpid(), exit_signal); /* * To properly set the return status of the process we * must raise the same signal SIGINT or SIGTERM that we * caught and let the old handler take care of it. */ raise(exit_signal); } logmsg("========> sws quits"); return 0; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/server_setup.h
#ifndef HEADER_CURL_SERVER_SETUP_H #define HEADER_CURL_SERVER_SETUP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #define CURL_NO_OLDIES #include "curl_setup.h" /* portability help from the lib directory */ #endif /* HEADER_CURL_SERVER_SETUP_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/server_sockaddr.h
#ifndef HEADER_CURL_SERVER_SOCKADDR_H #define HEADER_CURL_SERVER_SOCKADDR_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" #ifdef HAVE_SYS_UN_H #include <sys/un.h> /* for sockaddr_un */ #endif typedef union { struct sockaddr sa; struct sockaddr_in sa4; #ifdef ENABLE_IPV6 struct sockaddr_in6 sa6; #endif #ifdef USE_UNIX_SOCKETS struct sockaddr_un sau; #endif } srvr_sockaddr_union_t; #endif /* HEADER_CURL_SERVER_SOCKADDR_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/getpart.h
#ifndef HEADER_CURL_SERVER_GETPART_H #define HEADER_CURL_SERVER_GETPART_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" #define GPE_NO_BUFFER_SPACE -2 #define GPE_OUT_OF_MEMORY -1 #define GPE_OK 0 #define GPE_END_OF_FILE 1 int getpart(char **outbuf, size_t *outlen, const char *main, const char *sub, FILE *stream); #endif /* HEADER_CURL_SERVER_GETPART_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/testpart.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" #include "getpart.h" #include "curl_printf.h" /* include memdebug.h last */ #include "memdebug.h" int main(int argc, char **argv) { char *part; size_t partlen; if(argc< 3) { printf("./testpart main sub\n"); } else { int rc = getpart(&part, &partlen, argv[1], argv[2], stdin); size_t i; if(rc) return rc; for(i = 0; i < partlen; i++) printf("%c", part[i]); free(part); } return 0; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/socksd.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" #include <stdlib.h> /* Function * * Accepts a TCP connection on a custom port (IPv4 or IPv6). Connects to a * given addr + port backend (that is NOT extracted form the client's * request). The backend server default to connect to can be set with * --backend and --backendport. * * Read commands from FILE (set with --config). The commands control how to * act and is reset to defaults each client TCP connect. * * Config file keywords: * * "version [number: 5]" - requires the communication to use this version. * "nmethods_min [number: 1]" - the minimum numberf NMETHODS the client must * state * "nmethods_max [number: 3]" - the minimum numberf NMETHODS the client must * state * "user [string]" - the user name that must match (if method is 2) * "password [string]" - the password that must match (if method is 2) * "backend [IPv4]" - numerical IPv4 address of backend to connect to * "backendport [number:0]" - TCP port of backend to connect to. 0 means use the client's specified port number. * "method [number: 0]" - connect method to respond with: * 0 - no auth * 1 - GSSAPI (not supported) * 2 - user + password * "response [number]" - the decimal number to respond to a connect * SOCKS5: 0 is OK, SOCKS4: 90 is ok * */ /* based on sockfilt.c */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ #include "getpart.h" #include "inet_pton.h" #include "util.h" #include "server_sockaddr.h" #include "warnless.h" /* include memdebug.h last */ #include "memdebug.h" #ifdef USE_WINSOCK #undef EINTR #define EINTR 4 /* errno.h value */ #undef EAGAIN #define EAGAIN 11 /* errno.h value */ #undef ENOMEM #define ENOMEM 12 /* errno.h value */ #undef EINVAL #define EINVAL 22 /* errno.h value */ #endif #define DEFAULT_PORT 8905 #ifndef DEFAULT_LOGFILE #define DEFAULT_LOGFILE "log/socksd.log" #endif #ifndef DEFAULT_CONFIG #define DEFAULT_CONFIG "socksd.config" #endif static const char *backendaddr = "127.0.0.1"; static unsigned short backendport = 0; /* default is use client's */ struct configurable { unsigned char version; /* initial version byte in the request must match this */ unsigned char nmethods_min; /* minimum number of nmethods to expect */ unsigned char nmethods_max; /* maximum number of nmethods to expect */ unsigned char responseversion; unsigned char responsemethod; unsigned char reqcmd; unsigned char connectrep; unsigned short port; /* backend port */ char addr[32]; /* backend IPv4 numerical */ char user[256]; char password[256]; }; #define CONFIG_VERSION 5 #define CONFIG_NMETHODS_MIN 1 /* unauth, gssapi, auth */ #define CONFIG_NMETHODS_MAX 3 #define CONFIG_RESPONSEVERSION CONFIG_VERSION #define CONFIG_RESPONSEMETHOD 0 /* no auth */ #define CONFIG_REQCMD 1 /* CONNECT */ #define CONFIG_PORT backendport #define CONFIG_ADDR backendaddr #define CONFIG_CONNECTREP 0 static struct configurable config; const char *serverlogfile = DEFAULT_LOGFILE; static const char *configfile = DEFAULT_CONFIG; #ifdef ENABLE_IPV6 static bool use_ipv6 = FALSE; #endif static const char *ipv_inuse = "IPv4"; static unsigned short port = DEFAULT_PORT; static void resetdefaults(void) { logmsg("Reset to defaults"); config.version = CONFIG_VERSION; config.nmethods_min = CONFIG_NMETHODS_MIN; config.nmethods_max = CONFIG_NMETHODS_MAX; config.responseversion = CONFIG_RESPONSEVERSION; config.responsemethod = CONFIG_RESPONSEMETHOD; config.reqcmd = CONFIG_REQCMD; config.connectrep = CONFIG_CONNECTREP; config.port = CONFIG_PORT; strcpy(config.addr, CONFIG_ADDR); strcpy(config.user, "user"); strcpy(config.password, "password"); } static unsigned char byteval(char *value) { unsigned long num = strtoul(value, NULL, 10); return num & 0xff; } static unsigned short shortval(char *value) { unsigned long num = strtoul(value, NULL, 10); return num & 0xffff; } static void getconfig(void) { FILE *fp = fopen(configfile, FOPEN_READTEXT); resetdefaults(); if(fp) { char buffer[512]; logmsg("parse config file"); while(fgets(buffer, sizeof(buffer), fp)) { char key[32]; char value[32]; if(2 == sscanf(buffer, "%31s %31s", key, value)) { if(!strcmp(key, "version")) { config.version = byteval(value); logmsg("version [%d] set", config.version); } else if(!strcmp(key, "nmethods_min")) { config.nmethods_min = byteval(value); logmsg("nmethods_min [%d] set", config.nmethods_min); } else if(!strcmp(key, "nmethods_max")) { config.nmethods_max = byteval(value); logmsg("nmethods_max [%d] set", config.nmethods_max); } else if(!strcmp(key, "backend")) { strcpy(config.addr, value); logmsg("backend [%s] set", config.addr); } else if(!strcmp(key, "backendport")) { config.port = shortval(value); logmsg("backendport [%d] set", config.port); } else if(!strcmp(key, "user")) { strcpy(config.user, value); logmsg("user [%s] set", config.user); } else if(!strcmp(key, "password")) { strcpy(config.password, value); logmsg("password [%s] set", config.password); } /* Methods: o X'00' NO AUTHENTICATION REQUIRED o X'01' GSSAPI o X'02' USERNAME/PASSWORD */ else if(!strcmp(key, "method")) { config.responsemethod = byteval(value); logmsg("method [%d] set", config.responsemethod); } else if(!strcmp(key, "response")) { config.connectrep = byteval(value); logmsg("response [%d] set", config.connectrep); } } } fclose(fp); } } static void loghex(unsigned char *buffer, ssize_t len) { char data[1200]; ssize_t i; unsigned char *ptr = buffer; char *optr = data; ssize_t width = 0; int left = sizeof(data); for(i = 0; i<len && (left >= 0); i++) { msnprintf(optr, left, "%02x", ptr[i]); width += 2; optr += 2; left -= 2; } if(width) logmsg("'%s'", data); } /* RFC 1928, SOCKS5 byte index */ #define SOCKS5_VERSION 0 #define SOCKS5_NMETHODS 1 /* number of methods that is listed */ /* in the request: */ #define SOCKS5_REQCMD 1 #define SOCKS5_RESERVED 2 #define SOCKS5_ATYP 3 #define SOCKS5_DSTADDR 4 /* connect response */ #define SOCKS5_REP 1 #define SOCKS5_BNDADDR 4 /* auth request */ #define SOCKS5_ULEN 1 #define SOCKS5_UNAME 2 #define SOCKS4_CD 1 #define SOCKS4_DSTPORT 2 /* connect to a given IPv4 address, not the one asked for */ static curl_socket_t socksconnect(unsigned short connectport, const char *connectaddr) { int rc; srvr_sockaddr_union_t me; curl_socket_t sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == CURL_SOCKET_BAD) return CURL_SOCKET_BAD; memset(&me.sa4, 0, sizeof(me.sa4)); me.sa4.sin_family = AF_INET; me.sa4.sin_port = htons(connectport); me.sa4.sin_addr.s_addr = INADDR_ANY; Curl_inet_pton(AF_INET, connectaddr, &me.sa4.sin_addr); rc = connect(sock, &me.sa, sizeof(me.sa4)); if(rc) { int error = SOCKERRNO; logmsg("Error connecting to %s:%hu: (%d) %s", connectaddr, connectport, error, strerror(error)); return CURL_SOCKET_BAD; } logmsg("Connected fine to %s:%d", connectaddr, connectport); return sock; } static curl_socket_t socks4(curl_socket_t fd, unsigned char *buffer, ssize_t rc) { unsigned char response[256 + 16]; curl_socket_t connfd; unsigned char cd; unsigned short s4port; if(buffer[SOCKS4_CD] != 1) { logmsg("SOCKS4 CD is not 1: %d", buffer[SOCKS4_CD]); return CURL_SOCKET_BAD; } if(rc < 9) { logmsg("SOCKS4 connect message too short: %d", rc); return CURL_SOCKET_BAD; } if(!config.port) s4port = (unsigned short)((buffer[SOCKS4_DSTPORT]<<8) | (buffer[SOCKS4_DSTPORT + 1])); else s4port = config.port; connfd = socksconnect(s4port, config.addr); if(connfd == CURL_SOCKET_BAD) { /* failed */ cd = 91; } else { /* success */ cd = 90; } response[0] = 0; /* reply version 0 */ response[1] = cd; /* result */ /* copy port and address from connect request */ memcpy(&response[2], &buffer[SOCKS4_DSTPORT], 6); rc = (send)(fd, (char *)response, 8, 0); if(rc != 8) { logmsg("Sending SOCKS4 response failed!"); return CURL_SOCKET_BAD; } logmsg("Sent %d bytes", rc); loghex(response, rc); if(cd == 90) /* now do the transfer */ return connfd; if(connfd != CURL_SOCKET_BAD) sclose(connfd); return CURL_SOCKET_BAD; } static curl_socket_t sockit(curl_socket_t fd) { unsigned char buffer[256 + 16]; unsigned char response[256 + 16]; ssize_t rc; unsigned char len; unsigned char type; unsigned char rep = 0; unsigned char *address; unsigned short socksport; curl_socket_t connfd = CURL_SOCKET_BAD; unsigned short s5port; getconfig(); rc = recv(fd, (char *)buffer, sizeof(buffer), 0); logmsg("READ %d bytes", rc); loghex(buffer, rc); if(buffer[SOCKS5_VERSION] == 4) return socks4(fd, buffer, rc); if(buffer[SOCKS5_VERSION] != config.version) { logmsg("VERSION byte not %d", config.version); return CURL_SOCKET_BAD; } if((buffer[SOCKS5_NMETHODS] < config.nmethods_min) || (buffer[SOCKS5_NMETHODS] > config.nmethods_max)) { logmsg("NMETHODS byte not within %d - %d ", config.nmethods_min, config.nmethods_max); return CURL_SOCKET_BAD; } /* after NMETHODS follows that many bytes listing the methods the client says it supports */ if(rc != (buffer[SOCKS5_NMETHODS] + 2)) { logmsg("Expected %d bytes, got %d", buffer[SOCKS5_NMETHODS] + 2, rc); return CURL_SOCKET_BAD; } logmsg("Incoming request deemed fine!"); /* respond with two bytes: VERSION + METHOD */ response[0] = config.responseversion; response[1] = config.responsemethod; rc = (send)(fd, (char *)response, 2, 0); if(rc != 2) { logmsg("Sending response failed!"); return CURL_SOCKET_BAD; } logmsg("Sent %d bytes", rc); loghex(response, rc); /* expect the request or auth */ rc = recv(fd, (char *)buffer, sizeof(buffer), 0); logmsg("READ %d bytes", rc); loghex(buffer, rc); if(config.responsemethod == 2) { /* RFC 1929 authentication +----+------+----------+------+----------+ |VER | ULEN | UNAME | PLEN | PASSWD | +----+------+----------+------+----------+ | 1 | 1 | 1 to 255 | 1 | 1 to 255 | +----+------+----------+------+----------+ */ unsigned char ulen; unsigned char plen; bool login = TRUE; if(rc < 5) { logmsg("Too short auth input: %d", rc); return CURL_SOCKET_BAD; } if(buffer[SOCKS5_VERSION] != 1) { logmsg("Auth VERSION byte not 1, got %d", buffer[SOCKS5_VERSION]); return CURL_SOCKET_BAD; } ulen = buffer[SOCKS5_ULEN]; if(rc < 4 + ulen) { logmsg("Too short packet for username: %d", rc); return CURL_SOCKET_BAD; } plen = buffer[SOCKS5_ULEN + ulen + 1]; if(rc < 3 + ulen + plen) { logmsg("Too short packet for ulen %d plen %d: %d", ulen, plen, rc); return CURL_SOCKET_BAD; } if((ulen != strlen(config.user)) || (plen != strlen(config.password)) || memcmp(&buffer[SOCKS5_UNAME], config.user, ulen) || memcmp(&buffer[SOCKS5_UNAME + ulen + 1], config.password, plen)) { /* no match! */ logmsg("mismatched credentials!"); login = FALSE; } response[0] = 1; response[1] = login ? 0 : 1; rc = (send)(fd, (char *)response, 2, 0); if(rc != 2) { logmsg("Sending auth response failed!"); return CURL_SOCKET_BAD; } logmsg("Sent %d bytes", rc); loghex(response, rc); if(!login) return CURL_SOCKET_BAD; /* expect the request */ rc = recv(fd, (char *)buffer, sizeof(buffer), 0); logmsg("READ %d bytes", rc); loghex(buffer, rc); } if(rc < 6) { logmsg("Too short for request: %d", rc); return CURL_SOCKET_BAD; } if(buffer[SOCKS5_VERSION] != config.version) { logmsg("Request VERSION byte not %d", config.version); return CURL_SOCKET_BAD; } /* 1 == CONNECT */ if(buffer[SOCKS5_REQCMD] != config.reqcmd) { logmsg("Request COMMAND byte not %d", config.reqcmd); return CURL_SOCKET_BAD; } /* reserved, should be zero */ if(buffer[SOCKS5_RESERVED]) { logmsg("Request COMMAND byte not %d", config.reqcmd); return CURL_SOCKET_BAD; } /* ATYP: o IP V4 address: X'01' o DOMAINNAME: X'03' o IP V6 address: X'04' */ type = buffer[SOCKS5_ATYP]; address = &buffer[SOCKS5_DSTADDR]; switch(type) { case 1: /* 4 bytes IPv4 address */ len = 4; break; case 3: /* The first octet of the address field contains the number of octets of name that follow */ len = buffer[SOCKS5_DSTADDR]; len++; break; case 4: /* 16 bytes IPv6 address */ len = 16; break; default: logmsg("Unknown ATYP %d", type); return CURL_SOCKET_BAD; } if(rc < (4 + len + 2)) { logmsg("Request too short: %d, expected %d", rc, 4 + len + 2); return CURL_SOCKET_BAD; } if(!config.port) { unsigned char *portp = &buffer[SOCKS5_DSTADDR + len]; s5port = (unsigned short)((portp[0]<<8) | (portp[1])); } else s5port = config.port; if(!config.connectrep) connfd = socksconnect(s5port, config.addr); if(connfd == CURL_SOCKET_BAD) { /* failed */ rep = 1; } else { rep = config.connectrep; } /* */ response[SOCKS5_VERSION] = config.responseversion; /* o REP Reply field: o X'00' succeeded o X'01' general SOCKS server failure o X'02' connection not allowed by ruleset o X'03' Network unreachable o X'04' Host unreachable o X'05' Connection refused o X'06' TTL expired o X'07' Command not supported o X'08' Address type not supported o X'09' to X'FF' unassigned */ response[SOCKS5_REP] = rep; response[SOCKS5_RESERVED] = 0; /* must be zero */ response[SOCKS5_ATYP] = type; /* address type */ /* mirror back the original addr + port */ /* address or hostname */ memcpy(&response[SOCKS5_BNDADDR], address, len); /* port number */ memcpy(&response[SOCKS5_BNDADDR + len], &buffer[SOCKS5_DSTADDR + len], sizeof(socksport)); rc = (send)(fd, (char *)response, len + 6, 0); if(rc != (len + 6)) { logmsg("Sending connect response failed!"); return CURL_SOCKET_BAD; } logmsg("Sent %d bytes", rc); loghex(response, rc); if(!rep) return connfd; if(connfd != CURL_SOCKET_BAD) sclose(connfd); return CURL_SOCKET_BAD; } struct perclient { size_t fromremote; size_t fromclient; curl_socket_t remotefd; curl_socket_t clientfd; bool used; }; /* return non-zero when transfer is done */ static int tunnel(struct perclient *cp, fd_set *fds) { ssize_t nread; ssize_t nwrite; char buffer[512]; if(FD_ISSET(cp->clientfd, fds)) { /* read from client, send to remote */ nread = recv(cp->clientfd, buffer, sizeof(buffer), 0); if(nread > 0) { nwrite = send(cp->remotefd, (char *)buffer, (SEND_TYPE_ARG3)nread, 0); if(nwrite != nread) return 1; cp->fromclient += nwrite; } else return 1; } if(FD_ISSET(cp->remotefd, fds)) { /* read from remote, send to client */ nread = recv(cp->remotefd, buffer, sizeof(buffer), 0); if(nread > 0) { nwrite = send(cp->clientfd, (char *)buffer, (SEND_TYPE_ARG3)nread, 0); if(nwrite != nread) return 1; cp->fromremote += nwrite; } else return 1; } return 0; } /* sockfdp is a pointer to an established stream or CURL_SOCKET_BAD if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must accept() */ static bool incoming(curl_socket_t listenfd) { fd_set fds_read; fd_set fds_write; fd_set fds_err; int clients = 0; /* connected clients */ struct perclient c[2]; memset(c, 0, sizeof(c)); if(got_exit_signal) { logmsg("signalled to die, exiting..."); return FALSE; } #ifdef HAVE_GETPPID /* As a last resort, quit if socks5 process becomes orphan. */ if(getppid() <= 1) { logmsg("process becomes orphan, exiting"); return FALSE; } #endif do { int i; ssize_t rc; int error = 0; curl_socket_t sockfd = listenfd; int maxfd = (int)sockfd; FD_ZERO(&fds_read); FD_ZERO(&fds_write); FD_ZERO(&fds_err); /* there's always a socket to wait for */ FD_SET(sockfd, &fds_read); for(i = 0; i < 2; i++) { if(c[i].used) { curl_socket_t fd = c[i].clientfd; FD_SET(fd, &fds_read); if((int)fd > maxfd) maxfd = (int)fd; fd = c[i].remotefd; FD_SET(fd, &fds_read); if((int)fd > maxfd) maxfd = (int)fd; } } do { /* select() blocking behavior call on blocking descriptors please */ rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, NULL); if(got_exit_signal) { logmsg("signalled to die, exiting..."); return FALSE; } } while((rc == -1) && ((error = errno) == EINTR)); if(rc < 0) { logmsg("select() failed with error: (%d) %s", error, strerror(error)); return FALSE; } if((clients < 2) && FD_ISSET(sockfd, &fds_read)) { curl_socket_t newfd = accept(sockfd, NULL, NULL); if(CURL_SOCKET_BAD == newfd) { error = SOCKERRNO; logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s", sockfd, error, strerror(error)); } else { curl_socket_t remotefd; logmsg("====> Client connect, fd %d. Read config from %s", newfd, configfile); remotefd = sockit(newfd); /* SOCKS until done */ if(remotefd == CURL_SOCKET_BAD) { logmsg("====> Client disconnect"); sclose(newfd); } else { struct perclient *cp = &c[0]; logmsg("====> Tunnel transfer"); if(c[0].used) cp = &c[1]; cp->fromremote = 0; cp->fromclient = 0; cp->clientfd = newfd; cp->remotefd = remotefd; cp->used = TRUE; clients++; } } } for(i = 0; i < 2; i++) { struct perclient *cp = &c[i]; if(cp->used) { if(tunnel(cp, &fds_read)) { logmsg("SOCKS transfer completed. Bytes: < %zu > %zu", cp->fromremote, cp->fromclient); sclose(cp->clientfd); sclose(cp->remotefd); cp->used = FALSE; clients--; } } } } while(clients); return TRUE; } static curl_socket_t sockdaemon(curl_socket_t sock, unsigned short *listenport) { /* passive daemon style */ srvr_sockaddr_union_t listener; int flag; int rc; int totdelay = 0; int maxretr = 10; int delay = 20; int attempt = 0; int error = 0; do { attempt++; flag = 1; rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, sizeof(flag)); if(rc) { error = SOCKERRNO; logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", error, strerror(error)); if(maxretr) { rc = wait_ms(delay); if(rc) { /* should not happen */ error = errno; logmsg("wait_ms() failed with error: (%d) %s", error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } if(got_exit_signal) { logmsg("signalled to die, exiting..."); sclose(sock); return CURL_SOCKET_BAD; } totdelay += delay; delay *= 2; /* double the sleep for next attempt */ } } } while(rc && maxretr--); if(rc) { logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s", attempt, totdelay, error, strerror(error)); logmsg("Continuing anyway..."); } /* When the specified listener port is zero, it is actually a request to let the system choose a non-zero available port. */ #ifdef ENABLE_IPV6 if(!use_ipv6) { #endif memset(&listener.sa4, 0, sizeof(listener.sa4)); listener.sa4.sin_family = AF_INET; listener.sa4.sin_addr.s_addr = INADDR_ANY; listener.sa4.sin_port = htons(*listenport); rc = bind(sock, &listener.sa, sizeof(listener.sa4)); #ifdef ENABLE_IPV6 } else { memset(&listener.sa6, 0, sizeof(listener.sa6)); listener.sa6.sin6_family = AF_INET6; listener.sa6.sin6_addr = in6addr_any; listener.sa6.sin6_port = htons(*listenport); rc = bind(sock, &listener.sa, sizeof(listener.sa6)); } #endif /* ENABLE_IPV6 */ if(rc) { error = SOCKERRNO; logmsg("Error binding socket on port %hu: (%d) %s", *listenport, error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } if(!*listenport) { /* The system was supposed to choose a port number, figure out which port we actually got and update the listener port value with it. */ curl_socklen_t la_size; srvr_sockaddr_union_t localaddr; #ifdef ENABLE_IPV6 if(!use_ipv6) #endif la_size = sizeof(localaddr.sa4); #ifdef ENABLE_IPV6 else la_size = sizeof(localaddr.sa6); #endif memset(&localaddr.sa, 0, (size_t)la_size); if(getsockname(sock, &localaddr.sa, &la_size) < 0) { error = SOCKERRNO; logmsg("getsockname() failed with error: (%d) %s", error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } switch(localaddr.sa.sa_family) { case AF_INET: *listenport = ntohs(localaddr.sa4.sin_port); break; #ifdef ENABLE_IPV6 case AF_INET6: *listenport = ntohs(localaddr.sa6.sin6_port); break; #endif default: break; } if(!*listenport) { /* Real failure, listener port shall not be zero beyond this point. */ logmsg("Apparently getsockname() succeeded, with listener port zero."); logmsg("A valid reason for this failure is a binary built without"); logmsg("proper network library linkage. This might not be the only"); logmsg("reason, but double check it before anything else."); sclose(sock); return CURL_SOCKET_BAD; } } /* start accepting connections */ rc = listen(sock, 5); if(0 != rc) { error = SOCKERRNO; logmsg("listen(%d, 5) failed with error: (%d) %s", sock, error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } return sock; } int main(int argc, char *argv[]) { curl_socket_t sock = CURL_SOCKET_BAD; curl_socket_t msgsock = CURL_SOCKET_BAD; int wrotepidfile = 0; int wroteportfile = 0; const char *pidname = ".socksd.pid"; const char *portname = NULL; /* none by default */ bool juggle_again; int error; int arg = 1; while(argc>arg) { if(!strcmp("--version", argv[arg])) { printf("socksd IPv4%s\n", #ifdef ENABLE_IPV6 "/IPv6" #else "" #endif ); return 0; } else if(!strcmp("--pidfile", argv[arg])) { arg++; if(argc>arg) pidname = argv[arg++]; } else if(!strcmp("--portfile", argv[arg])) { arg++; if(argc>arg) portname = argv[arg++]; } else if(!strcmp("--config", argv[arg])) { arg++; if(argc>arg) configfile = argv[arg++]; } else if(!strcmp("--backend", argv[arg])) { arg++; if(argc>arg) backendaddr = argv[arg++]; } else if(!strcmp("--backendport", argv[arg])) { arg++; if(argc>arg) backendport = (unsigned short)atoi(argv[arg++]); } else if(!strcmp("--logfile", argv[arg])) { arg++; if(argc>arg) serverlogfile = argv[arg++]; } else if(!strcmp("--ipv6", argv[arg])) { #ifdef ENABLE_IPV6 ipv_inuse = "IPv6"; use_ipv6 = TRUE; #endif arg++; } else if(!strcmp("--ipv4", argv[arg])) { /* for completeness, we support this option as well */ #ifdef ENABLE_IPV6 ipv_inuse = "IPv4"; use_ipv6 = FALSE; #endif arg++; } else if(!strcmp("--port", argv[arg])) { arg++; if(argc>arg) { char *endptr; unsigned long ulnum = strtoul(argv[arg], &endptr, 10); port = curlx_ultous(ulnum); arg++; } } else { puts("Usage: socksd [option]\n" " --backend [ipv4 addr]\n" " --backendport [TCP port]\n" " --config [file]\n" " --version\n" " --logfile [file]\n" " --pidfile [file]\n" " --portfile [file]\n" " --ipv4\n" " --ipv6\n" " --bindonly\n" " --port [port]\n"); return 0; } } #ifdef WIN32 win32_init(); atexit(win32_cleanup); setmode(fileno(stdin), O_BINARY); setmode(fileno(stdout), O_BINARY); setmode(fileno(stderr), O_BINARY); #endif install_signal_handlers(false); #ifdef ENABLE_IPV6 if(!use_ipv6) #endif sock = socket(AF_INET, SOCK_STREAM, 0); #ifdef ENABLE_IPV6 else sock = socket(AF_INET6, SOCK_STREAM, 0); #endif if(CURL_SOCKET_BAD == sock) { error = SOCKERRNO; logmsg("Error creating socket: (%d) %s", error, strerror(error)); goto socks5_cleanup; } { /* passive daemon style */ sock = sockdaemon(sock, &port); if(CURL_SOCKET_BAD == sock) { goto socks5_cleanup; } msgsock = CURL_SOCKET_BAD; /* no stream socket yet */ } logmsg("Running %s version", ipv_inuse); logmsg("Listening on port %hu", port); wrotepidfile = write_pidfile(pidname); if(!wrotepidfile) { goto socks5_cleanup; } if(portname) { wroteportfile = write_portfile(portname, port); if(!wroteportfile) { goto socks5_cleanup; } } do { juggle_again = incoming(sock); } while(juggle_again); socks5_cleanup: if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD)) sclose(msgsock); if(sock != CURL_SOCKET_BAD) sclose(sock); if(wrotepidfile) unlink(pidname); if(wroteportfile) unlink(portname); restore_signal_handlers(false); if(got_exit_signal) { logmsg("============> socksd exits with signal (%d)", exit_signal); /* * To properly set the return status of the process we * must raise the same signal SIGINT or SIGTERM that we * caught and let the old handler take care of it. */ raise(exit_signal); } logmsg("============> socksd quits"); return 0; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/tftpd.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * * Trivial file transfer protocol server. * * This code includes many modifications by Jim Guyton <guyton@rand-unix> * * This source file was started based on netkit-tftpd 0.17 * Heavily modified for curl's test suite */ /* * Copyright (C) 2005 - 2021, Daniel Stenberg, <[email protected]>, et al. * Copyright (c) 1983, Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "server_setup.h" #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_ARPA_TFTP_H #include <arpa/tftp.h> #else #include "tftp.h" #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_SYS_FILIO_H /* FIONREAD on Solaris 7 */ #include <sys/filio.h> #endif #ifdef HAVE_SETJMP_H #include <setjmp.h> #endif #ifdef HAVE_PWD_H #include <pwd.h> #endif #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ #include "getpart.h" #include "util.h" #include "server_sockaddr.h" /* include memdebug.h last */ #include "memdebug.h" /***************************************************************************** * STRUCT DECLARATIONS AND DEFINES * *****************************************************************************/ #ifndef PKTSIZE #define PKTSIZE (SEGSIZE + 4) /* SEGSIZE defined in arpa/tftp.h */ #endif struct testcase { char *buffer; /* holds the file data to send to the client */ size_t bufsize; /* size of the data in buffer */ char *rptr; /* read pointer into the buffer */ size_t rcount; /* amount of data left to read of the file */ long testno; /* test case number */ int ofile; /* file descriptor for output file when uploading to us */ int writedelay; /* number of seconds between each packet */ }; struct formats { const char *f_mode; int f_convert; }; struct errmsg { int e_code; const char *e_msg; }; typedef union { struct tftphdr hdr; char storage[PKTSIZE]; } tftphdr_storage_t; /* * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE. */ struct bf { int counter; /* size of data in buffer, or flag */ tftphdr_storage_t buf; /* room for data packet */ }; #define BF_ALLOC -3 /* alloc'd but not yet filled */ #define BF_FREE -2 /* free */ #define opcode_RRQ 1 #define opcode_WRQ 2 #define opcode_DATA 3 #define opcode_ACK 4 #define opcode_ERROR 5 #define TIMEOUT 5 #undef MIN #define MIN(x,y) ((x)<(y)?(x):(y)) #ifndef DEFAULT_LOGFILE #define DEFAULT_LOGFILE "log/tftpd.log" #endif #define REQUEST_DUMP "log/server.input" #define DEFAULT_PORT 8999 /* UDP */ /***************************************************************************** * GLOBAL VARIABLES * *****************************************************************************/ static struct errmsg errmsgs[] = { { EUNDEF, "Undefined error code" }, { ENOTFOUND, "File not found" }, { EACCESS, "Access violation" }, { ENOSPACE, "Disk full or allocation exceeded" }, { EBADOP, "Illegal TFTP operation" }, { EBADID, "Unknown transfer ID" }, { EEXISTS, "File already exists" }, { ENOUSER, "No such user" }, { -1, 0 } }; static const struct formats formata[] = { { "netascii", 1 }, { "octet", 0 }, { NULL, 0 } }; static struct bf bfs[2]; static int nextone; /* index of next buffer to use */ static int current; /* index of buffer in use */ /* control flags for crlf conversions */ static int newline = 0; /* fillbuf: in middle of newline expansion */ static int prevchar = -1; /* putbuf: previous char (cr check) */ static tftphdr_storage_t buf; static tftphdr_storage_t ackbuf; static srvr_sockaddr_union_t from; static curl_socklen_t fromlen; static curl_socket_t peer = CURL_SOCKET_BAD; static unsigned int timeout; static unsigned int maxtimeout = 5 * TIMEOUT; #ifdef ENABLE_IPV6 static bool use_ipv6 = FALSE; #endif static const char *ipv_inuse = "IPv4"; const char *serverlogfile = DEFAULT_LOGFILE; static const char *pidname = ".tftpd.pid"; static const char *portname = NULL; /* none by default */ static int serverlogslocked = 0; static int wrotepidfile = 0; static int wroteportfile = 0; #ifdef HAVE_SIGSETJMP static sigjmp_buf timeoutbuf; #endif #if defined(HAVE_ALARM) && defined(SIGALRM) static const unsigned int rexmtval = TIMEOUT; #endif /***************************************************************************** * FUNCTION PROTOTYPES * *****************************************************************************/ static struct tftphdr *rw_init(int); static struct tftphdr *w_init(void); static struct tftphdr *r_init(void); static void read_ahead(struct testcase *test, int convert); static ssize_t write_behind(struct testcase *test, int convert); static int synchnet(curl_socket_t); static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size); static int validate_access(struct testcase *test, const char *fname, int mode); static void sendtftp(struct testcase *test, const struct formats *pf); static void recvtftp(struct testcase *test, const struct formats *pf); static void nak(int error); #if defined(HAVE_ALARM) && defined(SIGALRM) static void mysignal(int sig, void (*handler)(int)); static void timer(int signum); static void justtimeout(int signum); #endif /* HAVE_ALARM && SIGALRM */ /***************************************************************************** * FUNCTION IMPLEMENTATIONS * *****************************************************************************/ #if defined(HAVE_ALARM) && defined(SIGALRM) /* * Like signal(), but with well-defined semantics. */ static void mysignal(int sig, void (*handler)(int)) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = handler; sigaction(sig, &sa, NULL); } static void timer(int signum) { (void)signum; logmsg("alarm!"); timeout += rexmtval; if(timeout >= maxtimeout) { if(wrotepidfile) { wrotepidfile = 0; unlink(pidname); } if(wroteportfile) { wroteportfile = 0; unlink(portname); } if(serverlogslocked) { serverlogslocked = 0; clear_advisor_read_lock(SERVERLOGS_LOCK); } exit(1); } #ifdef HAVE_SIGSETJMP siglongjmp(timeoutbuf, 1); #endif } static void justtimeout(int signum) { (void)signum; } #endif /* HAVE_ALARM && SIGALRM */ /* * init for either read-ahead or write-behind. * zero for write-behind, one for read-head. */ static struct tftphdr *rw_init(int x) { newline = 0; /* init crlf flag */ prevchar = -1; bfs[0].counter = BF_ALLOC; /* pass out the first buffer */ current = 0; bfs[1].counter = BF_FREE; nextone = x; /* ahead or behind? */ return &bfs[0].buf.hdr; } static struct tftphdr *w_init(void) { return rw_init(0); /* write-behind */ } static struct tftphdr *r_init(void) { return rw_init(1); /* read-ahead */ } /* Have emptied current buffer by sending to net and getting ack. Free it and return next buffer filled with data. */ static int readit(struct testcase *test, struct tftphdr **dpp, int convert /* if true, convert to ascii */) { struct bf *b; bfs[current].counter = BF_FREE; /* free old one */ current = !current; /* "incr" current */ b = &bfs[current]; /* look at new buffer */ if(b->counter == BF_FREE) /* if it's empty */ read_ahead(test, convert); /* fill it */ *dpp = &b->buf.hdr; /* set caller's ptr */ return b->counter; } /* * fill the input buffer, doing ascii conversions if requested * conversions are lf -> cr, lf and cr -> cr, nul */ static void read_ahead(struct testcase *test, int convert /* if true, convert to ascii */) { int i; char *p; int c; struct bf *b; struct tftphdr *dp; b = &bfs[nextone]; /* look at "next" buffer */ if(b->counter != BF_FREE) /* nop if not free */ return; nextone = !nextone; /* "incr" next buffer ptr */ dp = &b->buf.hdr; if(convert == 0) { /* The former file reading code did this: b->counter = read(fileno(file), dp->th_data, SEGSIZE); */ size_t copy_n = MIN(SEGSIZE, test->rcount); memcpy(dp->th_data, test->rptr, copy_n); /* decrease amount, advance pointer */ test->rcount -= copy_n; test->rptr += copy_n; b->counter = (int)copy_n; return; } p = dp->th_data; for(i = 0 ; i < SEGSIZE; i++) { if(newline) { if(prevchar == '\n') c = '\n'; /* lf to cr,lf */ else c = '\0'; /* cr to cr,nul */ newline = 0; } else { if(test->rcount) { c = test->rptr[0]; test->rptr++; test->rcount--; } else break; if(c == '\n' || c == '\r') { prevchar = c; c = '\r'; newline = 1; } } *p++ = (char)c; } b->counter = (int)(p - dp->th_data); } /* Update count associated with the buffer, get new buffer from the queue. Calls write_behind only if next buffer not available. */ static int writeit(struct testcase *test, struct tftphdr * volatile *dpp, int ct, int convert) { bfs[current].counter = ct; /* set size of data to write */ current = !current; /* switch to other buffer */ if(bfs[current].counter != BF_FREE) /* if not free */ write_behind(test, convert); /* flush it */ bfs[current].counter = BF_ALLOC; /* mark as alloc'd */ *dpp = &bfs[current].buf.hdr; return ct; /* this is a lie of course */ } /* * Output a buffer to a file, converting from netascii if requested. * CR, NUL -> CR and CR, LF => LF. * Note spec is undefined if we get CR as last byte of file or a * CR followed by anything else. In this case we leave it alone. */ static ssize_t write_behind(struct testcase *test, int convert) { char *writebuf; int count; int ct; char *p; int c; /* current character */ struct bf *b; struct tftphdr *dp; b = &bfs[nextone]; if(b->counter < -1) /* anything to flush? */ return 0; /* just nop if nothing to do */ if(!test->ofile) { char outfile[256]; msnprintf(outfile, sizeof(outfile), "log/upload.%ld", test->testno); #ifdef WIN32 test->ofile = open(outfile, O_CREAT|O_RDWR|O_BINARY, 0777); #else test->ofile = open(outfile, O_CREAT|O_RDWR, 0777); #endif if(test->ofile == -1) { logmsg("Couldn't create and/or open file %s for upload!", outfile); return -1; /* failure! */ } } count = b->counter; /* remember byte count */ b->counter = BF_FREE; /* reset flag */ dp = &b->buf.hdr; nextone = !nextone; /* incr for next time */ writebuf = dp->th_data; if(count <= 0) return -1; /* nak logic? */ if(convert == 0) return write(test->ofile, writebuf, count); p = writebuf; ct = count; while(ct--) { /* loop over the buffer */ c = *p++; /* pick up a character */ if(prevchar == '\r') { /* if prev char was cr */ if(c == '\n') /* if have cr,lf then just */ lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */ else if(c == '\0') /* if have cr,nul then */ goto skipit; /* just skip over the putc */ /* else just fall through and allow it */ } /* formerly putc(c, file); */ if(1 != write(test->ofile, &c, 1)) break; skipit: prevchar = c; } return count; } /* When an error has occurred, it is possible that the two sides are out of * synch. Ie: that what I think is the other side's response to packet N is * really their response to packet N-1. * * So, to try to prevent that, we flush all the input queued up for us on the * network connection on our host. * * We return the number of packets we flushed (mostly for reporting when trace * is active). */ static int synchnet(curl_socket_t f /* socket to flush */) { #if defined(HAVE_IOCTLSOCKET) unsigned long i; #else int i; #endif int j = 0; char rbuf[PKTSIZE]; srvr_sockaddr_union_t fromaddr; curl_socklen_t fromaddrlen; for(;;) { #if defined(HAVE_IOCTLSOCKET) (void) ioctlsocket(f, FIONREAD, &i); #else (void) ioctl(f, FIONREAD, &i); #endif if(i) { j++; #ifdef ENABLE_IPV6 if(!use_ipv6) #endif fromaddrlen = sizeof(fromaddr.sa4); #ifdef ENABLE_IPV6 else fromaddrlen = sizeof(fromaddr.sa6); #endif (void) recvfrom(f, rbuf, sizeof(rbuf), 0, &fromaddr.sa, &fromaddrlen); } else break; } return j; } int main(int argc, char **argv) { srvr_sockaddr_union_t me; struct tftphdr *tp; ssize_t n = 0; int arg = 1; unsigned short port = DEFAULT_PORT; curl_socket_t sock = CURL_SOCKET_BAD; int flag; int rc; int error; struct testcase test; int result = 0; memset(&test, 0, sizeof(test)); while(argc>arg) { if(!strcmp("--version", argv[arg])) { printf("tftpd IPv4%s\n", #ifdef ENABLE_IPV6 "/IPv6" #else "" #endif ); return 0; } else if(!strcmp("--pidfile", argv[arg])) { arg++; if(argc>arg) pidname = argv[arg++]; } else if(!strcmp("--portfile", argv[arg])) { arg++; if(argc>arg) portname = argv[arg++]; } else if(!strcmp("--logfile", argv[arg])) { arg++; if(argc>arg) serverlogfile = argv[arg++]; } else if(!strcmp("--ipv4", argv[arg])) { #ifdef ENABLE_IPV6 ipv_inuse = "IPv4"; use_ipv6 = FALSE; #endif arg++; } else if(!strcmp("--ipv6", argv[arg])) { #ifdef ENABLE_IPV6 ipv_inuse = "IPv6"; use_ipv6 = TRUE; #endif arg++; } else if(!strcmp("--port", argv[arg])) { arg++; if(argc>arg) { char *endptr; unsigned long ulnum = strtoul(argv[arg], &endptr, 10); port = curlx_ultous(ulnum); arg++; } } else if(!strcmp("--srcdir", argv[arg])) { arg++; if(argc>arg) { path = argv[arg]; arg++; } } else { puts("Usage: tftpd [option]\n" " --version\n" " --logfile [file]\n" " --pidfile [file]\n" " --portfile [file]\n" " --ipv4\n" " --ipv6\n" " --port [port]\n" " --srcdir [path]"); return 0; } } #ifdef WIN32 win32_init(); atexit(win32_cleanup); #endif install_signal_handlers(true); #ifdef ENABLE_IPV6 if(!use_ipv6) #endif sock = socket(AF_INET, SOCK_DGRAM, 0); #ifdef ENABLE_IPV6 else sock = socket(AF_INET6, SOCK_DGRAM, 0); #endif if(CURL_SOCKET_BAD == sock) { error = SOCKERRNO; logmsg("Error creating socket: (%d) %s", error, strerror(error)); result = 1; goto tftpd_cleanup; } flag = 1; if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, sizeof(flag))) { error = SOCKERRNO; logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", error, strerror(error)); result = 1; goto tftpd_cleanup; } #ifdef ENABLE_IPV6 if(!use_ipv6) { #endif memset(&me.sa4, 0, sizeof(me.sa4)); me.sa4.sin_family = AF_INET; me.sa4.sin_addr.s_addr = INADDR_ANY; me.sa4.sin_port = htons(port); rc = bind(sock, &me.sa, sizeof(me.sa4)); #ifdef ENABLE_IPV6 } else { memset(&me.sa6, 0, sizeof(me.sa6)); me.sa6.sin6_family = AF_INET6; me.sa6.sin6_addr = in6addr_any; me.sa6.sin6_port = htons(port); rc = bind(sock, &me.sa, sizeof(me.sa6)); } #endif /* ENABLE_IPV6 */ if(0 != rc) { error = SOCKERRNO; logmsg("Error binding socket on port %hu: (%d) %s", port, error, strerror(error)); result = 1; goto tftpd_cleanup; } if(!port) { /* The system was supposed to choose a port number, figure out which port we actually got and update the listener port value with it. */ curl_socklen_t la_size; srvr_sockaddr_union_t localaddr; #ifdef ENABLE_IPV6 if(!use_ipv6) #endif la_size = sizeof(localaddr.sa4); #ifdef ENABLE_IPV6 else la_size = sizeof(localaddr.sa6); #endif memset(&localaddr.sa, 0, (size_t)la_size); if(getsockname(sock, &localaddr.sa, &la_size) < 0) { error = SOCKERRNO; logmsg("getsockname() failed with error: (%d) %s", error, strerror(error)); sclose(sock); goto tftpd_cleanup; } switch(localaddr.sa.sa_family) { case AF_INET: port = ntohs(localaddr.sa4.sin_port); break; #ifdef ENABLE_IPV6 case AF_INET6: port = ntohs(localaddr.sa6.sin6_port); break; #endif default: break; } if(!port) { /* Real failure, listener port shall not be zero beyond this point. */ logmsg("Apparently getsockname() succeeded, with listener port zero."); logmsg("A valid reason for this failure is a binary built without"); logmsg("proper network library linkage. This might not be the only"); logmsg("reason, but double check it before anything else."); result = 2; goto tftpd_cleanup; } } wrotepidfile = write_pidfile(pidname); if(!wrotepidfile) { result = 1; goto tftpd_cleanup; } if(portname) { wroteportfile = write_portfile(portname, port); if(!wroteportfile) { result = 1; goto tftpd_cleanup; } } logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port); for(;;) { fromlen = sizeof(from); #ifdef ENABLE_IPV6 if(!use_ipv6) #endif fromlen = sizeof(from.sa4); #ifdef ENABLE_IPV6 else fromlen = sizeof(from.sa6); #endif n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0, &from.sa, &fromlen); if(got_exit_signal) break; if(n < 0) { logmsg("recvfrom"); result = 3; break; } set_advisor_read_lock(SERVERLOGS_LOCK); serverlogslocked = 1; #ifdef ENABLE_IPV6 if(!use_ipv6) { #endif from.sa4.sin_family = AF_INET; peer = socket(AF_INET, SOCK_DGRAM, 0); if(CURL_SOCKET_BAD == peer) { logmsg("socket"); result = 2; break; } if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) { logmsg("connect: fail"); result = 1; break; } #ifdef ENABLE_IPV6 } else { from.sa6.sin6_family = AF_INET6; peer = socket(AF_INET6, SOCK_DGRAM, 0); if(CURL_SOCKET_BAD == peer) { logmsg("socket"); result = 2; break; } if(connect(peer, &from.sa, sizeof(from.sa6)) < 0) { logmsg("connect: fail"); result = 1; break; } } #endif maxtimeout = 5*TIMEOUT; tp = &buf.hdr; tp->th_opcode = ntohs(tp->th_opcode); if(tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) { memset(&test, 0, sizeof(test)); if(do_tftp(&test, tp, n) < 0) break; free(test.buffer); } sclose(peer); peer = CURL_SOCKET_BAD; if(got_exit_signal) break; if(serverlogslocked) { serverlogslocked = 0; clear_advisor_read_lock(SERVERLOGS_LOCK); } logmsg("end of one transfer"); } tftpd_cleanup: if(test.ofile > 0) close(test.ofile); if((peer != sock) && (peer != CURL_SOCKET_BAD)) sclose(peer); if(sock != CURL_SOCKET_BAD) sclose(sock); if(got_exit_signal) logmsg("signalled to die"); if(wrotepidfile) unlink(pidname); if(wroteportfile) unlink(portname); if(serverlogslocked) { serverlogslocked = 0; clear_advisor_read_lock(SERVERLOGS_LOCK); } restore_signal_handlers(true); if(got_exit_signal) { logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)", ipv_inuse, (int)port, (long)getpid(), exit_signal); /* * To properly set the return status of the process we * must raise the same signal SIGINT or SIGTERM that we * caught and let the old handler take care of it. */ raise(exit_signal); } logmsg("========> tftpd quits"); return result; } /* * Handle initial connection protocol. */ static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size) { char *cp; int first = 1, ecode; const struct formats *pf; char *filename, *mode = NULL; #ifdef USE_WINSOCK DWORD recvtimeout, recvtimeoutbak; #endif const char *option = "mode"; /* mode is implicit */ int toggle = 1; /* Open request dump file. */ FILE *server = fopen(REQUEST_DUMP, "ab"); if(!server) { int error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Error opening file: %s", REQUEST_DUMP); return -1; } /* store input protocol */ fprintf(server, "opcode = %x\n", tp->th_opcode); cp = (char *)&tp->th_stuff; filename = cp; do { bool endofit = true; while(cp < &buf.storage[size]) { if(*cp == '\0') { endofit = false; break; } cp++; } if(endofit) /* no more options */ break; /* before increasing pointer, make sure it is still within the legal space */ if((cp + 1) < &buf.storage[size]) { ++cp; if(first) { /* store the mode since we need it later */ mode = cp; first = 0; } if(toggle) /* name/value pair: */ fprintf(server, "%s = %s\n", option, cp); else { /* store the name pointer */ option = cp; } toggle ^= 1; } else /* No more options */ break; } while(1); if(*cp) { nak(EBADOP); fclose(server); return 3; } /* store input protocol */ fprintf(server, "filename = %s\n", filename); for(cp = mode; cp && *cp; cp++) if(ISUPPER(*cp)) *cp = (char)tolower((int)*cp); /* store input protocol */ fclose(server); for(pf = formata; pf->f_mode; pf++) if(strcmp(pf->f_mode, mode) == 0) break; if(!pf->f_mode) { nak(EBADOP); return 2; } ecode = validate_access(test, filename, tp->th_opcode); if(ecode) { nak(ecode); return 1; } #ifdef USE_WINSOCK recvtimeout = sizeof(recvtimeoutbak); getsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, (char *)&recvtimeoutbak, (int *)&recvtimeout); recvtimeout = TIMEOUT*1000; setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, (const char *)&recvtimeout, sizeof(recvtimeout)); #endif if(tp->th_opcode == opcode_WRQ) recvtftp(test, pf); else sendtftp(test, pf); #ifdef USE_WINSOCK recvtimeout = recvtimeoutbak; setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO, (const char *)&recvtimeout, sizeof(recvtimeout)); #endif return 0; } /* Based on the testno, parse the correct server commands. */ static int parse_servercmd(struct testcase *req) { FILE *stream; int error; stream = test2fopen(req->testno); if(!stream) { error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg(" Couldn't open test file %ld", req->testno); return 1; /* done */ } else { char *orgcmd = NULL; char *cmd = NULL; size_t cmdsize = 0; int num = 0; /* get the custom server control "commands" */ error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream); fclose(stream); if(error) { logmsg("getpart() failed with error: %d", error); return 1; /* done */ } cmd = orgcmd; while(cmd && cmdsize) { char *check; if(1 == sscanf(cmd, "writedelay: %d", &num)) { logmsg("instructed to delay %d secs between packets", num); req->writedelay = num; } else { logmsg("Unknown <servercmd> instruction found: %s", cmd); } /* try to deal with CRLF or just LF */ check = strchr(cmd, '\r'); if(!check) check = strchr(cmd, '\n'); if(check) { /* get to the letter following the newline */ while((*check == '\r') || (*check == '\n')) check++; if(!*check) /* if we reached a zero, get out */ break; cmd = check; } else break; } free(orgcmd); } return 0; /* OK! */ } /* * Validate file access. */ static int validate_access(struct testcase *test, const char *filename, int mode) { char *ptr; logmsg("trying to get file: %s mode %x", filename, mode); if(!strncmp("verifiedserver", filename, 14)) { char weare[128]; size_t count = msnprintf(weare, sizeof(weare), "WE ROOLZ: %" CURL_FORMAT_CURL_OFF_T "\r\n", our_getpid()); logmsg("Are-we-friendly question received"); test->buffer = strdup(weare); test->rptr = test->buffer; /* set read pointer */ test->bufsize = count; /* set total count */ test->rcount = count; /* set data left to read */ return 0; /* fine */ } /* find the last slash */ ptr = strrchr(filename, '/'); if(ptr) { char partbuf[80]="data"; long partno; long testno; FILE *stream; ptr++; /* skip the slash */ /* skip all non-numericals following the slash */ while(*ptr && !ISDIGIT(*ptr)) ptr++; /* get the number */ testno = strtol(ptr, &ptr, 10); if(testno > 10000) { partno = testno % 10000; testno /= 10000; } else partno = 0; logmsg("requested test number %ld part %ld", testno, partno); test->testno = testno; (void)parse_servercmd(test); stream = test2fopen(testno); if(0 != partno) msnprintf(partbuf, sizeof(partbuf), "data%ld", partno); if(!stream) { int error = errno; logmsg("fopen() failed with error: %d %s", error, strerror(error)); logmsg("Couldn't open test file for test : %d", testno); return EACCESS; } else { size_t count; int error = getpart(&test->buffer, &count, "reply", partbuf, stream); fclose(stream); if(error) { logmsg("getpart() failed with error: %d", error); return EACCESS; } if(test->buffer) { test->rptr = test->buffer; /* set read pointer */ test->bufsize = count; /* set total count */ test->rcount = count; /* set data left to read */ } else return EACCESS; } } else { logmsg("no slash found in path"); return EACCESS; /* failure */ } logmsg("file opened and all is good"); return 0; } /* * Send the requested file. */ static void sendtftp(struct testcase *test, const struct formats *pf) { int size; ssize_t n; /* These are volatile to live through a siglongjmp */ volatile unsigned short sendblock; /* block count */ struct tftphdr * volatile sdp = r_init(); /* data buffer */ struct tftphdr * const sap = &ackbuf.hdr; /* ack buffer */ sendblock = 1; #if defined(HAVE_ALARM) && defined(SIGALRM) mysignal(SIGALRM, timer); #endif do { size = readit(test, (struct tftphdr **)&sdp, pf->f_convert); if(size < 0) { nak(errno + 100); return; } sdp->th_opcode = htons((unsigned short)opcode_DATA); sdp->th_block = htons(sendblock); timeout = 0; #ifdef HAVE_SIGSETJMP (void) sigsetjmp(timeoutbuf, 1); #endif if(test->writedelay) { logmsg("Pausing %d seconds before %d bytes", test->writedelay, size); wait_ms(1000*test->writedelay); } send_data: logmsg("write"); if(swrite(peer, sdp, size + 4) != size + 4) { logmsg("write: fail"); return; } read_ahead(test, pf->f_convert); for(;;) { #ifdef HAVE_ALARM alarm(rexmtval); /* read the ack */ #endif logmsg("read"); n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage)); logmsg("read: %zd", n); #ifdef HAVE_ALARM alarm(0); #endif if(got_exit_signal) return; if(n < 0) { logmsg("read: fail"); return; } sap->th_opcode = ntohs((unsigned short)sap->th_opcode); sap->th_block = ntohs(sap->th_block); if(sap->th_opcode == opcode_ERROR) { logmsg("got ERROR"); return; } if(sap->th_opcode == opcode_ACK) { if(sap->th_block == sendblock) { break; } /* Re-synchronize with the other side */ (void) synchnet(peer); if(sap->th_block == (sendblock-1)) { goto send_data; } } } sendblock++; } while(size == SEGSIZE); } /* * Receive a file. */ static void recvtftp(struct testcase *test, const struct formats *pf) { ssize_t n, size; /* These are volatile to live through a siglongjmp */ volatile unsigned short recvblock; /* block count */ struct tftphdr * volatile rdp; /* data buffer */ struct tftphdr *rap; /* ack buffer */ recvblock = 0; rdp = w_init(); #if defined(HAVE_ALARM) && defined(SIGALRM) mysignal(SIGALRM, timer); #endif rap = &ackbuf.hdr; do { timeout = 0; rap->th_opcode = htons((unsigned short)opcode_ACK); rap->th_block = htons(recvblock); recvblock++; #ifdef HAVE_SIGSETJMP (void) sigsetjmp(timeoutbuf, 1); #endif send_ack: logmsg("write"); if(swrite(peer, &ackbuf.storage[0], 4) != 4) { logmsg("write: fail"); goto abort; } write_behind(test, pf->f_convert); for(;;) { #ifdef HAVE_ALARM alarm(rexmtval); #endif logmsg("read"); n = sread(peer, rdp, PKTSIZE); logmsg("read: %zd", n); #ifdef HAVE_ALARM alarm(0); #endif if(got_exit_signal) goto abort; if(n < 0) { /* really? */ logmsg("read: fail"); goto abort; } rdp->th_opcode = ntohs((unsigned short)rdp->th_opcode); rdp->th_block = ntohs(rdp->th_block); if(rdp->th_opcode == opcode_ERROR) goto abort; if(rdp->th_opcode == opcode_DATA) { if(rdp->th_block == recvblock) { break; /* normal */ } /* Re-synchronize with the other side */ (void) synchnet(peer); if(rdp->th_block == (recvblock-1)) goto send_ack; /* rexmit */ } } size = writeit(test, &rdp, (int)(n - 4), pf->f_convert); if(size != (n-4)) { /* ahem */ if(size < 0) nak(errno + 100); else nak(ENOSPACE); goto abort; } } while(size == SEGSIZE); write_behind(test, pf->f_convert); /* close the output file as early as possible after upload completion */ if(test->ofile > 0) { close(test->ofile); test->ofile = 0; } rap->th_opcode = htons((unsigned short)opcode_ACK); /* send the "final" ack */ rap->th_block = htons(recvblock); (void) swrite(peer, &ackbuf.storage[0], 4); #if defined(HAVE_ALARM) && defined(SIGALRM) mysignal(SIGALRM, justtimeout); /* just abort read on timeout */ alarm(rexmtval); #endif /* normally times out and quits */ n = sread(peer, &buf.storage[0], sizeof(buf.storage)); #ifdef HAVE_ALARM alarm(0); #endif if(got_exit_signal) goto abort; if(n >= 4 && /* if read some data */ rdp->th_opcode == opcode_DATA && /* and got a data block */ recvblock == rdp->th_block) { /* then my last ack was lost */ (void) swrite(peer, &ackbuf.storage[0], 4); /* resend final ack */ } abort: /* make sure the output file is closed in case of abort */ if(test->ofile > 0) { close(test->ofile); test->ofile = 0; } return; } /* * Send a nak packet (error message). Error code passed in is one of the * standard TFTP codes, or a Unix errno offset by 100. */ static void nak(int error) { struct tftphdr *tp; int length; struct errmsg *pe; tp = &buf.hdr; tp->th_opcode = htons((unsigned short)opcode_ERROR); tp->th_code = htons((unsigned short)error); for(pe = errmsgs; pe->e_code >= 0; pe++) if(pe->e_code == error) break; if(pe->e_code < 0) { pe->e_msg = strerror(error - 100); tp->th_code = EUNDEF; /* set 'undef' errorcode */ } length = (int)strlen(pe->e_msg); /* we use memcpy() instead of strcpy() in order to avoid buffer overflow * report from glibc with FORTIFY_SOURCE */ memcpy(tp->th_msg, pe->e_msg, length + 1); length += 5; if(swrite(peer, &buf.storage[0], length) != length) logmsg("nak: fail\n"); }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/resolve.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" /* Purpose * * Resolve the given name, using system name resolve functions (NOT any * function provided by libcurl). Used to see if the name exists and thus if * we can allow a test case to use it for testing. * * Like if 'localhost' actual exists etc. * */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef _XOPEN_SOURCE_EXTENDED /* This define is "almost" required to build on HPUX 11 */ #include <arpa/inet.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ #include "util.h" /* include memdebug.h last */ #include "memdebug.h" static bool use_ipv6 = FALSE; static const char *ipv_inuse = "IPv4"; const char *serverlogfile = ""; /* for a util.c function we don't use */ int main(int argc, char *argv[]) { int arg = 1; const char *host = NULL; int rc = 0; while(argc>arg) { if(!strcmp("--version", argv[arg])) { printf("resolve IPv4%s\n", #if defined(CURLRES_IPV6) "/IPv6" #else "" #endif ); return 0; } else if(!strcmp("--ipv6", argv[arg])) { ipv_inuse = "IPv6"; use_ipv6 = TRUE; arg++; } else if(!strcmp("--ipv4", argv[arg])) { /* for completeness, we support this option as well */ ipv_inuse = "IPv4"; use_ipv6 = FALSE; arg++; } else { host = argv[arg++]; } } if(!host) { puts("Usage: resolve [option] <host>\n" " --version\n" " --ipv4" #if defined(CURLRES_IPV6) "\n --ipv6" #endif ); return 1; } #ifdef WIN32 win32_init(); atexit(win32_cleanup); #endif #if defined(CURLRES_IPV6) if(use_ipv6) { /* Check that the system has IPv6 enabled before checking the resolver */ curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0); if(s == CURL_SOCKET_BAD) /* an IPv6 address was requested and we can't get/use one */ rc = -1; else { sclose(s); } } if(rc == 0) { /* getaddrinfo() resolve */ struct addrinfo *ai; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = use_ipv6 ? PF_INET6 : PF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = 0; /* Use parenthesis around functions to stop them from being replaced by the macro in memdebug.h */ rc = (getaddrinfo)(host, "80", &hints, &ai); if(rc == 0) (freeaddrinfo)(ai); } #else if(use_ipv6) { puts("IPv6 support has been disabled in this program"); return 1; } else { /* gethostbyname() resolve */ struct hostent *he; he = gethostbyname(host); rc = !he; } #endif if(rc) printf("Resolving %s '%s' didn't work\n", ipv_inuse, host); return !!rc; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/mqttd.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" #include <stdlib.h> #include <string.h> #include "util.h" /* Function * * Accepts a TCP connection on a custom port (IPv4 or IPv6). Speaks MQTT. * * Read commands from FILE (set with --config). The commands control how to * act and is reset to defaults each client TCP connect. * * Config file keywords: * * TODO */ /* based on sockfilt.c */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETINET_IN6_H #include <netinet/in6.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ #include "getpart.h" #include "inet_pton.h" #include "util.h" #include "server_sockaddr.h" #include "warnless.h" /* include memdebug.h last */ #include "memdebug.h" #ifdef USE_WINSOCK #undef EINTR #define EINTR 4 /* errno.h value */ #undef EAGAIN #define EAGAIN 11 /* errno.h value */ #undef ENOMEM #define ENOMEM 12 /* errno.h value */ #undef EINVAL #define EINVAL 22 /* errno.h value */ #endif #define DEFAULT_PORT 1883 /* MQTT default port */ #ifndef DEFAULT_LOGFILE #define DEFAULT_LOGFILE "log/mqttd.log" #endif #ifndef DEFAULT_CONFIG #define DEFAULT_CONFIG "mqttd.config" #endif #define MQTT_MSG_CONNECT 0x10 #define MQTT_MSG_CONNACK 0x20 #define MQTT_MSG_PUBLISH 0x30 #define MQTT_MSG_PUBACK 0x40 #define MQTT_MSG_SUBSCRIBE 0x82 #define MQTT_MSG_SUBACK 0x90 #define MQTT_MSG_DISCONNECT 0xe0 #define MQTT_CONNACK_LEN 4 #define MQTT_SUBACK_LEN 5 #define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */ #define MQTT_HEADER_LEN 5 /* max 5 bytes */ struct configurable { unsigned char version; /* initial version byte in the request must match this */ bool publish_before_suback; bool short_publish; bool excessive_remaining; unsigned char error_connack; int testnum; }; #define REQUEST_DUMP "log/server.input" #define CONFIG_VERSION 5 static struct configurable config; const char *serverlogfile = DEFAULT_LOGFILE; static const char *configfile = DEFAULT_CONFIG; #ifdef ENABLE_IPV6 static bool use_ipv6 = FALSE; #endif static const char *ipv_inuse = "IPv4"; static unsigned short port = DEFAULT_PORT; static void resetdefaults(void) { logmsg("Reset to defaults"); config.version = CONFIG_VERSION; config.publish_before_suback = FALSE; config.short_publish = FALSE; config.excessive_remaining = FALSE; config.error_connack = 0; config.testnum = 0; } static unsigned char byteval(char *value) { unsigned long num = strtoul(value, NULL, 10); return num & 0xff; } static void getconfig(void) { FILE *fp = fopen(configfile, FOPEN_READTEXT); resetdefaults(); if(fp) { char buffer[512]; logmsg("parse config file"); while(fgets(buffer, sizeof(buffer), fp)) { char key[32]; char value[32]; if(2 == sscanf(buffer, "%31s %31s", key, value)) { if(!strcmp(key, "version")) { config.version = byteval(value); logmsg("version [%d] set", config.version); } else if(!strcmp(key, "PUBLISH-before-SUBACK")) { logmsg("PUBLISH-before-SUBACK set"); config.publish_before_suback = TRUE; } else if(!strcmp(key, "short-PUBLISH")) { logmsg("short-PUBLISH set"); config.short_publish = TRUE; } else if(!strcmp(key, "error-CONNACK")) { config.error_connack = byteval(value); logmsg("error-CONNACK = %d", config.error_connack); } else if(!strcmp(key, "Testnum")) { config.testnum = atoi(value); logmsg("testnum = %d", config.testnum); } else if(!strcmp(key, "excessive-remaining")) { logmsg("excessive-remaining set"); config.excessive_remaining = TRUE; } } } fclose(fp); } else { logmsg("No config file '%s' to read", configfile); } } static void loghex(unsigned char *buffer, ssize_t len) { char data[12000]; ssize_t i; unsigned char *ptr = buffer; char *optr = data; ssize_t width = 0; int left = sizeof(data); for(i = 0; i<len && (left >= 0); i++) { msnprintf(optr, left, "%02x", ptr[i]); width += 2; optr += 2; left -= 2; } if(width) logmsg("'%s'", data); } typedef enum { FROM_CLIENT, FROM_SERVER } mqttdir; static void logprotocol(mqttdir dir, const char *prefix, size_t remlen, FILE *output, unsigned char *buffer, ssize_t len) { char data[12000] = ""; ssize_t i; unsigned char *ptr = buffer; char *optr = data; int left = sizeof(data); for(i = 0; i<len && (left >= 0); i++) { msnprintf(optr, left, "%02x", ptr[i]); optr += 2; left -= 2; } fprintf(output, "%s %s %zx %s\n", dir == FROM_CLIENT? "client": "server", prefix, remlen, data); } /* return 0 on success */ static int connack(FILE *dump, curl_socket_t fd) { unsigned char packet[]={ MQTT_MSG_CONNACK, 0x02, 0x00, 0x00 }; ssize_t rc; packet[3] = config.error_connack; rc = swrite(fd, (char *)packet, sizeof(packet)); if(rc > 0) { logmsg("WROTE %d bytes [CONNACK]", rc); loghex(packet, rc); logprotocol(FROM_SERVER, "CONNACK", 2, dump, packet, sizeof(packet)); } if(rc == sizeof(packet)) { return 0; } return 1; } /* return 0 on success */ static int suback(FILE *dump, curl_socket_t fd, unsigned short packetid) { unsigned char packet[]={ MQTT_MSG_SUBACK, 0x03, 0, 0, /* filled in below */ 0x00 }; ssize_t rc; packet[2] = (unsigned char)(packetid >> 8); packet[3] = (unsigned char)(packetid & 0xff); rc = swrite(fd, (char *)packet, sizeof(packet)); if(rc == sizeof(packet)) { logmsg("WROTE %d bytes [SUBACK]", rc); loghex(packet, rc); logprotocol(FROM_SERVER, "SUBACK", 3, dump, packet, rc); return 0; } return 1; } #ifdef QOS /* return 0 on success */ static int puback(FILE *dump, curl_socket_t fd, unsigned short packetid) { unsigned char packet[]={ MQTT_MSG_PUBACK, 0x00, 0, 0 /* filled in below */ }; ssize_t rc; packet[2] = (unsigned char)(packetid >> 8); packet[3] = (unsigned char)(packetid & 0xff); rc = swrite(fd, (char *)packet, sizeof(packet)); if(rc == sizeof(packet)) { logmsg("WROTE %d bytes [PUBACK]", rc); loghex(packet, rc); logprotocol(FROM_SERVER, dump, packet, rc); return 0; } logmsg("Failed sending [PUBACK]"); return 1; } #endif /* return 0 on success */ static int disconnect(FILE *dump, curl_socket_t fd) { unsigned char packet[]={ MQTT_MSG_DISCONNECT, 0x00, }; ssize_t rc = swrite(fd, (char *)packet, sizeof(packet)); if(rc == sizeof(packet)) { logmsg("WROTE %d bytes [DISCONNECT]", rc); loghex(packet, rc); logprotocol(FROM_SERVER, "DISCONNECT", 0, dump, packet, rc); return 0; } logmsg("Failed sending [DISCONNECT]"); return 1; } /* do encodedByte = X MOD 128 X = X DIV 128 // if there are more data to encode, set the top bit of this byte if ( X > 0 ) encodedByte = encodedByte OR 128 endif 'output' encodedByte while ( X > 0 ) */ /* return number of bytes used */ static int encode_length(size_t packetlen, unsigned char *remlength) /* 4 bytes */ { int bytes = 0; unsigned char encode; do { encode = packetlen % 0x80; packetlen /= 0x80; if(packetlen) encode |= 0x80; remlength[bytes++] = encode; if(bytes > 3) { logmsg("too large packet!"); return 0; } } while(packetlen); return bytes; } static size_t decode_length(unsigned char *buf, size_t buflen, size_t *lenbytes) { size_t len = 0; size_t mult = 1; size_t i; unsigned char encoded = 0x80; for(i = 0; (i < buflen) && (encoded & 0x80); i++) { encoded = buf[i]; len += (encoded & 0x7f) * mult; mult *= 0x80; } if(lenbytes) *lenbytes = i; return len; } /* return 0 on success */ static int publish(FILE *dump, curl_socket_t fd, unsigned short packetid, char *topic, char *payload, size_t payloadlen) { size_t topiclen = strlen(topic); unsigned char *packet; size_t payloadindex; ssize_t remaininglength = topiclen + 2 + payloadlen; ssize_t packetlen; ssize_t sendamount; ssize_t rc; unsigned char rembuffer[4]; int encodedlen; if(config.excessive_remaining) { /* manually set illegal remaining length */ rembuffer[0] = 0xff; rembuffer[1] = 0xff; rembuffer[2] = 0xff; rembuffer[3] = 0x80; /* maximum allowed here by spec is 0x7f */ encodedlen = 4; } else encodedlen = encode_length(remaininglength, rembuffer); /* one packet type byte (possibly two more for packetid) */ packetlen = remaininglength + encodedlen + 1; packet = malloc(packetlen); if(!packet) return 1; packet[0] = MQTT_MSG_PUBLISH; /* TODO: set QoS? */ memcpy(&packet[1], rembuffer, encodedlen); (void)packetid; /* packet_id if QoS is set */ packet[1 + encodedlen] = (unsigned char)(topiclen >> 8); packet[2 + encodedlen] = (unsigned char)(topiclen & 0xff); memcpy(&packet[3 + encodedlen], topic, topiclen); payloadindex = 3 + topiclen + encodedlen; memcpy(&packet[payloadindex], payload, payloadlen); sendamount = packetlen; if(config.short_publish) sendamount -= 2; rc = swrite(fd, (char *)packet, sendamount); if(rc > 0) { logmsg("WROTE %d bytes [PUBLISH]", rc); loghex(packet, rc); logprotocol(FROM_SERVER, "PUBLISH", remaininglength, dump, packet, rc); } if(rc == packetlen) return 0; return 1; } #define MAX_TOPIC_LENGTH 65535 #define MAX_CLIENT_ID_LENGTH 32 static char topic[MAX_TOPIC_LENGTH + 1]; static int fixedheader(curl_socket_t fd, unsigned char *bytep, size_t *remaining_lengthp, size_t *remaining_length_bytesp) { /* get the fixed header */ unsigned char buffer[10]; /* get the first two bytes */ ssize_t rc = sread(fd, (char *)buffer, 2); int i; if(rc < 2) { logmsg("READ %d bytes [SHORT!]", rc); return 1; /* fail */ } logmsg("READ %d bytes", rc); loghex(buffer, rc); *bytep = buffer[0]; /* if the length byte has the top bit set, get the next one too */ i = 1; while(buffer[i] & 0x80) { i++; rc = sread(fd, (char *)&buffer[i], 1); if(rc != 1) { logmsg("Remaining Length broken"); return 1; } } *remaining_lengthp = decode_length(&buffer[1], i, remaining_length_bytesp); logmsg("Remaining Length: %ld [%d bytes]", (long) *remaining_lengthp, *remaining_length_bytesp); return 0; } static curl_socket_t mqttit(curl_socket_t fd) { size_t buff_size = 10*1024; unsigned char *buffer = NULL; ssize_t rc; unsigned char byte; unsigned short packet_id; size_t payload_len; size_t client_id_length; unsigned int topic_len; size_t remaining_length = 0; size_t bytes = 0; /* remaining length field size in bytes */ char client_id[MAX_CLIENT_ID_LENGTH]; long testno; FILE *stream = NULL; static const char protocol[7] = { 0x00, 0x04, /* protocol length */ 'M','Q','T','T', /* protocol name */ 0x04 /* protocol level */ }; FILE *dump = fopen(REQUEST_DUMP, "ab"); if(!dump) goto end; getconfig(); testno = config.testnum; if(testno) logmsg("Found test number %ld", testno); buffer = malloc(buff_size); if(!buffer) { logmsg("Out of memory, unable to allocate buffer"); goto end; } do { unsigned char usr_flag = 0x80; unsigned char passwd_flag = 0x40; unsigned char conn_flags; const size_t client_id_offset = 12; size_t start_usr; size_t start_passwd; /* get the fixed header */ rc = fixedheader(fd, &byte, &remaining_length, &bytes); if(rc) break; if(remaining_length >= buff_size) { buff_size = remaining_length; buffer = realloc(buffer, buff_size); if(!buffer) { logmsg("Failed realloc of size %lu", buff_size); goto end; } } if(remaining_length) { /* reading variable header and payload into buffer */ rc = sread(fd, (char *)buffer, remaining_length); if(rc > 0) { logmsg("READ %d bytes", rc); loghex(buffer, rc); } } if(byte == MQTT_MSG_CONNECT) { logprotocol(FROM_CLIENT, "CONNECT", remaining_length, dump, buffer, rc); if(memcmp(protocol, buffer, sizeof(protocol))) { logmsg("Protocol preamble mismatch"); goto end; } /* ignore the connect flag byte and two keepalive bytes */ payload_len = (buffer[10] << 8) | buffer[11]; /* first part of the payload is the client ID */ client_id_length = payload_len; /* checking if user and password flags were set */ conn_flags = buffer[7]; start_usr = client_id_offset + payload_len; if(usr_flag == (unsigned char)(conn_flags & usr_flag)) { logmsg("User flag is present in CONN flag"); payload_len += (buffer[start_usr] << 8) | buffer[start_usr + 1]; payload_len += 2; /* MSB and LSB for user length */ } start_passwd = client_id_offset + payload_len; if(passwd_flag == (char)(conn_flags & passwd_flag)) { logmsg("Password flag is present in CONN flags"); payload_len += (buffer[start_passwd] << 8) | buffer[start_passwd + 1]; payload_len += 2; /* MSB and LSB for password length */ } /* check the length of the payload */ if((ssize_t)payload_len != (rc - 12)) { logmsg("Payload length mismatch, expected %x got %x", rc - 12, payload_len); goto end; } /* check the length of the client ID */ else if((client_id_length + 1) > MAX_CLIENT_ID_LENGTH) { logmsg("Too large client id"); goto end; } memcpy(client_id, &buffer[12], client_id_length); client_id[client_id_length] = 0; logmsg("MQTT client connect accepted: %s", client_id); /* The first packet sent from the Server to the Client MUST be a CONNACK Packet */ if(connack(dump, fd)) { logmsg("failed sending CONNACK"); goto end; } } else if(byte == MQTT_MSG_SUBSCRIBE) { int error; char *data; size_t datalen; logprotocol(FROM_CLIENT, "SUBSCRIBE", remaining_length, dump, buffer, rc); logmsg("Incoming SUBSCRIBE"); if(rc < 6) { logmsg("Too small SUBSCRIBE"); goto end; } /* two bytes packet id */ packet_id = (unsigned short)((buffer[0] << 8) | buffer[1]); /* two bytes topic length */ topic_len = (buffer[2] << 8) | buffer[3]; if(topic_len != (remaining_length - 5)) { logmsg("Wrong topic length, got %d expected %d", topic_len, remaining_length - 5); goto end; } memcpy(topic, &buffer[4], topic_len); topic[topic_len] = 0; /* there's a QoS byte (two bits) after the topic */ logmsg("SUBSCRIBE to '%s' [%d]", topic, packet_id); stream = test2fopen(testno); error = getpart(&data, &datalen, "reply", "data", stream); if(!error) { if(!config.publish_before_suback) { if(suback(dump, fd, packet_id)) { logmsg("failed sending SUBACK"); goto end; } } if(publish(dump, fd, packet_id, topic, data, datalen)) { logmsg("PUBLISH failed"); goto end; } if(config.publish_before_suback) { if(suback(dump, fd, packet_id)) { logmsg("failed sending SUBACK"); goto end; } } } else { char *def = (char *)"this is random payload yes yes it is"; publish(dump, fd, packet_id, topic, def, strlen(def)); } disconnect(dump, fd); } else if((byte & 0xf0) == (MQTT_MSG_PUBLISH & 0xf0)) { size_t topiclen; logmsg("Incoming PUBLISH"); logprotocol(FROM_CLIENT, "PUBLISH", remaining_length, dump, buffer, rc); topiclen = (buffer[1 + bytes] << 8) | buffer[2 + bytes]; logmsg("Got %d bytes topic", topiclen); /* TODO: verify topiclen */ #ifdef QOS /* TODO: handle packetid if there is one. Send puback if QoS > 0 */ puback(dump, fd, 0); #endif /* expect a disconnect here */ /* get the request */ rc = sread(fd, (char *)&buffer[0], 2); logmsg("READ %d bytes [DISCONNECT]", rc); loghex(buffer, rc); logprotocol(FROM_CLIENT, "DISCONNECT", 0, dump, buffer, rc); goto end; } else { /* not supported (yet) */ goto end; } } while(1); end: if(buffer) free(buffer); if(dump) fclose(dump); if(stream) fclose(stream); return CURL_SOCKET_BAD; } /* sockfdp is a pointer to an established stream or CURL_SOCKET_BAD if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must accept() */ static bool incoming(curl_socket_t listenfd) { fd_set fds_read; fd_set fds_write; fd_set fds_err; int clients = 0; /* connected clients */ if(got_exit_signal) { logmsg("signalled to die, exiting..."); return FALSE; } #ifdef HAVE_GETPPID /* As a last resort, quit if socks5 process becomes orphan. */ if(getppid() <= 1) { logmsg("process becomes orphan, exiting"); return FALSE; } #endif do { ssize_t rc; int error = 0; curl_socket_t sockfd = listenfd; int maxfd = (int)sockfd; FD_ZERO(&fds_read); FD_ZERO(&fds_write); FD_ZERO(&fds_err); /* there's always a socket to wait for */ FD_SET(sockfd, &fds_read); do { /* select() blocking behavior call on blocking descriptors please */ rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, NULL); if(got_exit_signal) { logmsg("signalled to die, exiting..."); return FALSE; } } while((rc == -1) && ((error = SOCKERRNO) == EINTR)); if(rc < 0) { logmsg("select() failed with error: (%d) %s", error, strerror(error)); return FALSE; } if(FD_ISSET(sockfd, &fds_read)) { curl_socket_t newfd = accept(sockfd, NULL, NULL); if(CURL_SOCKET_BAD == newfd) { error = SOCKERRNO; logmsg("accept(%d, NULL, NULL) failed with error: (%d) %s", sockfd, error, strerror(error)); } else { logmsg("====> Client connect, fd %d. Read config from %s", newfd, configfile); set_advisor_read_lock(SERVERLOGS_LOCK); (void)mqttit(newfd); /* until done */ clear_advisor_read_lock(SERVERLOGS_LOCK); logmsg("====> Client disconnect"); sclose(newfd); } } } while(clients); return TRUE; } static curl_socket_t sockdaemon(curl_socket_t sock, unsigned short *listenport) { /* passive daemon style */ srvr_sockaddr_union_t listener; int flag; int rc; int totdelay = 0; int maxretr = 10; int delay = 20; int attempt = 0; int error = 0; do { attempt++; flag = 1; rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&flag, sizeof(flag)); if(rc) { error = SOCKERRNO; logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s", error, strerror(error)); if(maxretr) { rc = wait_ms(delay); if(rc) { /* should not happen */ logmsg("wait_ms() failed with error: %d", rc); sclose(sock); return CURL_SOCKET_BAD; } if(got_exit_signal) { logmsg("signalled to die, exiting..."); sclose(sock); return CURL_SOCKET_BAD; } totdelay += delay; delay *= 2; /* double the sleep for next attempt */ } } } while(rc && maxretr--); if(rc) { logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s", attempt, totdelay, error, strerror(error)); logmsg("Continuing anyway..."); } /* When the specified listener port is zero, it is actually a request to let the system choose a non-zero available port. */ #ifdef ENABLE_IPV6 if(!use_ipv6) { #endif memset(&listener.sa4, 0, sizeof(listener.sa4)); listener.sa4.sin_family = AF_INET; listener.sa4.sin_addr.s_addr = INADDR_ANY; listener.sa4.sin_port = htons(*listenport); rc = bind(sock, &listener.sa, sizeof(listener.sa4)); #ifdef ENABLE_IPV6 } else { memset(&listener.sa6, 0, sizeof(listener.sa6)); listener.sa6.sin6_family = AF_INET6; listener.sa6.sin6_addr = in6addr_any; listener.sa6.sin6_port = htons(*listenport); rc = bind(sock, &listener.sa, sizeof(listener.sa6)); } #endif /* ENABLE_IPV6 */ if(rc) { error = SOCKERRNO; logmsg("Error binding socket on port %hu: (%d) %s", *listenport, error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } if(!*listenport) { /* The system was supposed to choose a port number, figure out which port we actually got and update the listener port value with it. */ curl_socklen_t la_size; srvr_sockaddr_union_t localaddr; #ifdef ENABLE_IPV6 if(!use_ipv6) #endif la_size = sizeof(localaddr.sa4); #ifdef ENABLE_IPV6 else la_size = sizeof(localaddr.sa6); #endif memset(&localaddr.sa, 0, (size_t)la_size); if(getsockname(sock, &localaddr.sa, &la_size) < 0) { error = SOCKERRNO; logmsg("getsockname() failed with error: (%d) %s", error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } switch(localaddr.sa.sa_family) { case AF_INET: *listenport = ntohs(localaddr.sa4.sin_port); break; #ifdef ENABLE_IPV6 case AF_INET6: *listenport = ntohs(localaddr.sa6.sin6_port); break; #endif default: break; } if(!*listenport) { /* Real failure, listener port shall not be zero beyond this point. */ logmsg("Apparently getsockname() succeeded, with listener port zero."); logmsg("A valid reason for this failure is a binary built without"); logmsg("proper network library linkage. This might not be the only"); logmsg("reason, but double check it before anything else."); sclose(sock); return CURL_SOCKET_BAD; } } /* start accepting connections */ rc = listen(sock, 5); if(0 != rc) { error = SOCKERRNO; logmsg("listen(%d, 5) failed with error: (%d) %s", sock, error, strerror(error)); sclose(sock); return CURL_SOCKET_BAD; } return sock; } int main(int argc, char *argv[]) { curl_socket_t sock = CURL_SOCKET_BAD; curl_socket_t msgsock = CURL_SOCKET_BAD; int wrotepidfile = 0; int wroteportfile = 0; const char *pidname = ".mqttd.pid"; const char *portname = ".mqttd.port"; bool juggle_again; int error; int arg = 1; while(argc>arg) { if(!strcmp("--version", argv[arg])) { printf("mqttd IPv4%s\n", #ifdef ENABLE_IPV6 "/IPv6" #else "" #endif ); return 0; } else if(!strcmp("--pidfile", argv[arg])) { arg++; if(argc>arg) pidname = argv[arg++]; } else if(!strcmp("--portfile", argv[arg])) { arg++; if(argc>arg) portname = argv[arg++]; } else if(!strcmp("--config", argv[arg])) { arg++; if(argc>arg) configfile = argv[arg++]; } else if(!strcmp("--logfile", argv[arg])) { arg++; if(argc>arg) serverlogfile = argv[arg++]; } else if(!strcmp("--ipv6", argv[arg])) { #ifdef ENABLE_IPV6 ipv_inuse = "IPv6"; use_ipv6 = TRUE; #endif arg++; } else if(!strcmp("--ipv4", argv[arg])) { /* for completeness, we support this option as well */ #ifdef ENABLE_IPV6 ipv_inuse = "IPv4"; use_ipv6 = FALSE; #endif arg++; } else if(!strcmp("--port", argv[arg])) { arg++; if(argc>arg) { char *endptr; unsigned long ulnum = strtoul(argv[arg], &endptr, 10); if((endptr != argv[arg] + strlen(argv[arg])) || ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) { fprintf(stderr, "mqttd: invalid --port argument (%s)\n", argv[arg]); return 0; } port = curlx_ultous(ulnum); arg++; } } else { puts("Usage: mqttd [option]\n" " --config [file]\n" " --version\n" " --logfile [file]\n" " --pidfile [file]\n" " --portfile [file]\n" " --ipv4\n" " --ipv6\n" " --port [port]\n"); return 0; } } #ifdef WIN32 win32_init(); atexit(win32_cleanup); setmode(fileno(stdin), O_BINARY); setmode(fileno(stdout), O_BINARY); setmode(fileno(stderr), O_BINARY); #endif install_signal_handlers(FALSE); #ifdef ENABLE_IPV6 if(!use_ipv6) #endif sock = socket(AF_INET, SOCK_STREAM, 0); #ifdef ENABLE_IPV6 else sock = socket(AF_INET6, SOCK_STREAM, 0); #endif if(CURL_SOCKET_BAD == sock) { error = SOCKERRNO; logmsg("Error creating socket: (%d) %s", error, strerror(error)); goto mqttd_cleanup; } { /* passive daemon style */ sock = sockdaemon(sock, &port); if(CURL_SOCKET_BAD == sock) { goto mqttd_cleanup; } msgsock = CURL_SOCKET_BAD; /* no stream socket yet */ } logmsg("Running %s version", ipv_inuse); logmsg("Listening on port %hu", port); wrotepidfile = write_pidfile(pidname); if(!wrotepidfile) { goto mqttd_cleanup; } wroteportfile = write_portfile(portname, port); if(!wroteportfile) { goto mqttd_cleanup; } do { juggle_again = incoming(sock); } while(juggle_again); mqttd_cleanup: if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD)) sclose(msgsock); if(sock != CURL_SOCKET_BAD) sclose(sock); if(wrotepidfile) unlink(pidname); if(wroteportfile) unlink(portname); restore_signal_handlers(FALSE); if(got_exit_signal) { logmsg("============> mqttd exits with signal (%d)", exit_signal); /* * To properly set the return status of the process we * must raise the same signal SIGINT or SIGTERM that we * caught and let the old handler take care of it. */ raise(exit_signal); } logmsg("============> mqttd quits"); return 0; }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/util.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "server_setup.h" #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef _XOPEN_SOURCE_EXTENDED /* This define is "almost" required to build on HPUX 11 */ #include <arpa/inet.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_POLL_H #include <poll.h> #elif defined(HAVE_SYS_POLL_H) #include <sys/poll.h> #endif #ifdef __MINGW32__ #include <w32api.h> #endif #define ENABLE_CURLX_PRINTF /* make the curlx header define all printf() functions to use the curlx_* versions instead */ #include "curlx.h" /* from the private lib dir */ #include "getpart.h" #include "util.h" #include "timeval.h" #ifdef USE_WINSOCK #undef EINTR #define EINTR 4 /* errno.h value */ #undef EINVAL #define EINVAL 22 /* errno.h value */ #endif /* MinGW with w32api version < 3.6 declared in6addr_any as extern, but lacked the definition */ #if defined(ENABLE_IPV6) && defined(__MINGW32__) #if (__W32API_MAJOR_VERSION < 3) || \ ((__W32API_MAJOR_VERSION == 3) && (__W32API_MINOR_VERSION < 6)) const struct in6_addr in6addr_any = {{ IN6ADDR_ANY_INIT }}; #endif /* w32api < 3.6 */ #endif /* ENABLE_IPV6 && __MINGW32__*/ static struct timeval tvnow(void); /* This function returns a pointer to STATIC memory. It converts the given * binary lump to a hex formatted string usable for output in logs or * whatever. */ char *data_to_hex(char *data, size_t len) { static char buf[256*3]; size_t i; char *optr = buf; char *iptr = data; if(len > 255) len = 255; for(i = 0; i < len; i++) { if((data[i] >= 0x20) && (data[i] < 0x7f)) *optr++ = *iptr++; else { msnprintf(optr, 4, "%%%02x", *iptr++); optr += 3; } } *optr = 0; /* in case no sprintf was used */ return buf; } void logmsg(const char *msg, ...) { va_list ap; char buffer[2048 + 1]; FILE *logfp; struct timeval tv; time_t sec; struct tm *now; char timebuf[20]; static time_t epoch_offset; static int known_offset; if(!serverlogfile) { fprintf(stderr, "Error: serverlogfile not set\n"); return; } tv = tvnow(); if(!known_offset) { epoch_offset = time(NULL) - tv.tv_sec; known_offset = 1; } sec = epoch_offset + tv.tv_sec; /* !checksrc! disable BANNEDFUNC 1 */ now = localtime(&sec); /* not thread safe but we don't care */ msnprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld", (int)now->tm_hour, (int)now->tm_min, (int)now->tm_sec, (long)tv.tv_usec); va_start(ap, msg); mvsnprintf(buffer, sizeof(buffer), msg, ap); va_end(ap); logfp = fopen(serverlogfile, "ab"); if(logfp) { fprintf(logfp, "%s %s\n", timebuf, buffer); fclose(logfp); } else { int error = errno; fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error)); fprintf(stderr, "Error opening file: %s\n", serverlogfile); fprintf(stderr, "Msg not logged: %s %s\n", timebuf, buffer); } } #ifdef WIN32 /* use instead of perror() on generic windows */ void win32_perror(const char *msg) { char buf[512]; DWORD err = SOCKERRNO; if(!FormatMessageA((FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS), NULL, err, LANG_NEUTRAL, buf, sizeof(buf), NULL)) msnprintf(buf, sizeof(buf), "Unknown error %lu (%#lx)", err, err); if(msg) fprintf(stderr, "%s: ", msg); fprintf(stderr, "%s\n", buf); } #endif /* WIN32 */ #ifdef USE_WINSOCK void win32_init(void) { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(2, 2); err = WSAStartup(wVersionRequested, &wsaData); if(err) { perror("Winsock init failed"); logmsg("Error initialising winsock -- aborting"); exit(1); } if(LOBYTE(wsaData.wVersion) != LOBYTE(wVersionRequested) || HIBYTE(wsaData.wVersion) != HIBYTE(wVersionRequested) ) { WSACleanup(); perror("Winsock init failed"); logmsg("No suitable winsock.dll found -- aborting"); exit(1); } } void win32_cleanup(void) { WSACleanup(); } #endif /* USE_WINSOCK */ /* set by the main code to point to where the test dir is */ const char *path = "."; FILE *test2fopen(long testno) { FILE *stream; char filename[256]; /* first try the alternative, preprocessed, file */ msnprintf(filename, sizeof(filename), ALTTEST_DATA_PATH, ".", testno); stream = fopen(filename, "rb"); if(stream) return stream; /* then try the source version */ msnprintf(filename, sizeof(filename), TEST_DATA_PATH, path, testno); stream = fopen(filename, "rb"); return stream; } /* * Portable function used for waiting a specific amount of ms. * Waiting indefinitely with this function is not allowed, a * zero or negative timeout value will return immediately. * * Return values: * -1 = system call error, or invalid timeout value * 0 = specified timeout has elapsed */ int wait_ms(int timeout_ms) { #if !defined(MSDOS) && !defined(USE_WINSOCK) #ifndef HAVE_POLL_FINE struct timeval pending_tv; #endif struct timeval initial_tv; int pending_ms; #endif int r = 0; if(!timeout_ms) return 0; if(timeout_ms < 0) { errno = EINVAL; return -1; } #if defined(MSDOS) delay(timeout_ms); #elif defined(USE_WINSOCK) Sleep(timeout_ms); #else pending_ms = timeout_ms; initial_tv = tvnow(); do { int error; #if defined(HAVE_POLL_FINE) r = poll(NULL, 0, pending_ms); #else pending_tv.tv_sec = pending_ms / 1000; pending_tv.tv_usec = (pending_ms % 1000) * 1000; r = select(0, NULL, NULL, NULL, &pending_tv); #endif /* HAVE_POLL_FINE */ if(r != -1) break; error = errno; if(error && (error != EINTR)) break; pending_ms = timeout_ms - (int)timediff(tvnow(), initial_tv); if(pending_ms <= 0) break; } while(r == -1); #endif /* USE_WINSOCK */ if(r) r = -1; return r; } curl_off_t our_getpid(void) { curl_off_t pid; pid = (curl_off_t)getpid(); #if defined(WIN32) || defined(_WIN32) /* store pid + 65536 to avoid conflict with Cygwin/msys PIDs, see also: * - https://cygwin.com/git/?p=newlib-cygwin.git;a=commit; ↵ * h=b5e1003722cb14235c4f166be72c09acdffc62ea * - https://cygwin.com/git/?p=newlib-cygwin.git;a=commit; ↵ * h=448cf5aa4b429d5a9cebf92a0da4ab4b5b6d23fe */ pid += 65536; #endif return pid; } int write_pidfile(const char *filename) { FILE *pidfile; curl_off_t pid; pid = our_getpid(); pidfile = fopen(filename, "wb"); if(!pidfile) { logmsg("Couldn't write pid file: %s %s", filename, strerror(errno)); return 0; /* fail */ } fprintf(pidfile, "%" CURL_FORMAT_CURL_OFF_T "\n", pid); fclose(pidfile); logmsg("Wrote pid %" CURL_FORMAT_CURL_OFF_T " to %s", pid, filename); return 1; /* success */ } /* store the used port number in a file */ int write_portfile(const char *filename, int port) { FILE *portfile = fopen(filename, "wb"); if(!portfile) { logmsg("Couldn't write port file: %s %s", filename, strerror(errno)); return 0; /* fail */ } fprintf(portfile, "%d\n", port); fclose(portfile); logmsg("Wrote port %d to %s", port, filename); return 1; /* success */ } void set_advisor_read_lock(const char *filename) { FILE *lockfile; int error = 0; int res; do { lockfile = fopen(filename, "wb"); } while(!lockfile && ((error = errno) == EINTR)); if(!lockfile) { logmsg("Error creating lock file %s error: %d %s", filename, error, strerror(error)); return; } do { res = fclose(lockfile); } while(res && ((error = errno) == EINTR)); if(res) logmsg("Error closing lock file %s error: %d %s", filename, error, strerror(error)); } void clear_advisor_read_lock(const char *filename) { int error = 0; int res; /* ** Log all removal failures. Even those due to file not existing. ** This allows to detect if unexpectedly the file has already been ** removed by a process different than the one that should do this. */ do { res = unlink(filename); } while(res && ((error = errno) == EINTR)); if(res) logmsg("Error removing lock file %s error: %d %s", filename, error, strerror(error)); } /* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because its behavior is altered by the current locale. */ static char raw_toupper(char in) { #if !defined(CURL_DOES_CONVERSIONS) if(in >= 'a' && in <= 'z') return (char)('A' + in - 'a'); #else switch(in) { case 'a': return 'A'; case 'b': return 'B'; case 'c': return 'C'; case 'd': return 'D'; case 'e': return 'E'; case 'f': return 'F'; case 'g': return 'G'; case 'h': return 'H'; case 'i': return 'I'; case 'j': return 'J'; case 'k': return 'K'; case 'l': return 'L'; case 'm': return 'M'; case 'n': return 'N'; case 'o': return 'O'; case 'p': return 'P'; case 'q': return 'Q'; case 'r': return 'R'; case 's': return 'S'; case 't': return 'T'; case 'u': return 'U'; case 'v': return 'V'; case 'w': return 'W'; case 'x': return 'X'; case 'y': return 'Y'; case 'z': return 'Z'; } #endif return in; } int strncasecompare(const char *first, const char *second, size_t max) { while(*first && *second && max) { if(raw_toupper(*first) != raw_toupper(*second)) { break; } max--; first++; second++; } if(0 == max) return 1; /* they are equal this far */ return raw_toupper(*first) == raw_toupper(*second); } #if defined(WIN32) && !defined(MSDOS) static struct timeval tvnow(void) { /* ** GetTickCount() is available on _all_ Windows versions from W95 up ** to nowadays. Returns milliseconds elapsed since last system boot, ** increases monotonically and wraps once 49.7 days have elapsed. ** ** GetTickCount64() is available on Windows version from Windows Vista ** and Windows Server 2008 up to nowadays. The resolution of the ** function is limited to the resolution of the system timer, which ** is typically in the range of 10 milliseconds to 16 milliseconds. */ struct timeval now; #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) && \ (!defined(__MINGW32__) || defined(__MINGW64_VERSION_MAJOR)) ULONGLONG milliseconds = GetTickCount64(); #else DWORD milliseconds = GetTickCount(); #endif now.tv_sec = (long)(milliseconds / 1000); now.tv_usec = (long)((milliseconds % 1000) * 1000); return now; } #elif defined(HAVE_CLOCK_GETTIME_MONOTONIC) static struct timeval tvnow(void) { /* ** clock_gettime() is granted to be increased monotonically when the ** monotonic clock is queried. Time starting point is unspecified, it ** could be the system start-up time, the Epoch, or something else, ** in any case the time starting point does not change once that the ** system has started up. */ struct timeval now; struct timespec tsnow; if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) { now.tv_sec = tsnow.tv_sec; now.tv_usec = (int)(tsnow.tv_nsec / 1000); } /* ** Even when the configure process has truly detected monotonic clock ** availability, it might happen that it is not actually available at ** run-time. When this occurs simply fallback to other time source. */ #ifdef HAVE_GETTIMEOFDAY else (void)gettimeofday(&now, NULL); #else else { now.tv_sec = time(NULL); now.tv_usec = 0; } #endif return now; } #elif defined(HAVE_GETTIMEOFDAY) static struct timeval tvnow(void) { /* ** gettimeofday() is not granted to be increased monotonically, due to ** clock drifting and external source time synchronization it can jump ** forward or backward in time. */ struct timeval now; (void)gettimeofday(&now, NULL); return now; } #else static struct timeval tvnow(void) { /* ** time() returns the value of time in seconds since the Epoch. */ struct timeval now; now.tv_sec = time(NULL); now.tv_usec = 0; return now; } #endif long timediff(struct timeval newer, struct timeval older) { timediff_t diff = newer.tv_sec-older.tv_sec; if(diff >= (LONG_MAX/1000)) return LONG_MAX; else if(diff <= (LONG_MIN/1000)) return LONG_MIN; return (long)(newer.tv_sec-older.tv_sec)*1000+ (long)(newer.tv_usec-older.tv_usec)/1000; } /* vars used to keep around previous signal handlers */ typedef void (*SIGHANDLER_T)(int); #ifdef SIGHUP static SIGHANDLER_T old_sighup_handler = SIG_ERR; #endif #ifdef SIGPIPE static SIGHANDLER_T old_sigpipe_handler = SIG_ERR; #endif #ifdef SIGALRM static SIGHANDLER_T old_sigalrm_handler = SIG_ERR; #endif #ifdef SIGINT static SIGHANDLER_T old_sigint_handler = SIG_ERR; #endif #ifdef SIGTERM static SIGHANDLER_T old_sigterm_handler = SIG_ERR; #endif #if defined(SIGBREAK) && defined(WIN32) static SIGHANDLER_T old_sigbreak_handler = SIG_ERR; #endif #ifdef WIN32 static DWORD thread_main_id = 0; static HANDLE thread_main_window = NULL; static HWND hidden_main_window = NULL; #endif /* var which if set indicates that the program should finish execution */ volatile int got_exit_signal = 0; /* if next is set indicates the first signal handled in exit_signal_handler */ volatile int exit_signal = 0; #ifdef WIN32 /* event which if set indicates that the program should finish */ HANDLE exit_event = NULL; #endif /* signal handler that will be triggered to indicate that the program * should finish its execution in a controlled manner as soon as possible. * The first time this is called it will set got_exit_signal to one and * store in exit_signal the signal that triggered its execution. */ static void exit_signal_handler(int signum) { int old_errno = errno; logmsg("exit_signal_handler: %d", signum); if(got_exit_signal == 0) { got_exit_signal = 1; exit_signal = signum; #ifdef WIN32 if(exit_event) (void)SetEvent(exit_event); #endif } (void)signal(signum, exit_signal_handler); errno = old_errno; } #ifdef WIN32 /* CTRL event handler for Windows Console applications to simulate * SIGINT, SIGTERM and SIGBREAK on CTRL events and trigger signal handler. * * Background information from MSDN: * SIGINT is not supported for any Win32 application. When a CTRL+C * interrupt occurs, Win32 operating systems generate a new thread * to specifically handle that interrupt. This can cause a single-thread * application, such as one in UNIX, to become multithreaded and cause * unexpected behavior. * [...] * The SIGILL and SIGTERM signals are not generated under Windows. * They are included for ANSI compatibility. Therefore, you can set * signal handlers for these signals by using signal, and you can also * explicitly generate these signals by calling raise. Source: * https://docs.microsoft.com/de-de/cpp/c-runtime-library/reference/signal */ static BOOL WINAPI ctrl_event_handler(DWORD dwCtrlType) { int signum = 0; logmsg("ctrl_event_handler: %d", dwCtrlType); switch(dwCtrlType) { #ifdef SIGINT case CTRL_C_EVENT: signum = SIGINT; break; #endif #ifdef SIGTERM case CTRL_CLOSE_EVENT: signum = SIGTERM; break; #endif #ifdef SIGBREAK case CTRL_BREAK_EVENT: signum = SIGBREAK; break; #endif default: return FALSE; } if(signum) { logmsg("ctrl_event_handler: %d -> %d", dwCtrlType, signum); raise(signum); } return TRUE; } /* Window message handler for Windows applications to add support * for graceful process termination via taskkill (without /f) which * sends WM_CLOSE to all Windows of a process (even hidden ones). * * Therefore we create and run a hidden Window in a separate thread * to receive and handle the WM_CLOSE message as SIGTERM signal. */ static LRESULT CALLBACK main_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { int signum = 0; if(hwnd == hidden_main_window) { switch(uMsg) { #ifdef SIGTERM case WM_CLOSE: signum = SIGTERM; break; #endif case WM_DESTROY: PostQuitMessage(0); break; } if(signum) { logmsg("main_window_proc: %d -> %d", uMsg, signum); raise(signum); } } return DefWindowProc(hwnd, uMsg, wParam, lParam); } /* Window message queue loop for hidden main window, details see above. */ static DWORD WINAPI main_window_loop(LPVOID lpParameter) { WNDCLASS wc; BOOL ret; MSG msg; ZeroMemory(&wc, sizeof(wc)); wc.lpfnWndProc = (WNDPROC)main_window_proc; wc.hInstance = (HINSTANCE)lpParameter; wc.lpszClassName = TEXT("MainWClass"); if(!RegisterClass(&wc)) { perror("RegisterClass failed"); return (DWORD)-1; } hidden_main_window = CreateWindowEx(0, TEXT("MainWClass"), TEXT("Recv WM_CLOSE msg"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, (HWND)NULL, (HMENU)NULL, wc.hInstance, (LPVOID)NULL); if(!hidden_main_window) { perror("CreateWindowEx failed"); return (DWORD)-1; } do { ret = GetMessage(&msg, NULL, 0, 0); if(ret == -1) { perror("GetMessage failed"); return (DWORD)-1; } else if(ret) { if(msg.message == WM_APP) { DestroyWindow(hidden_main_window); } else if(msg.hwnd && !TranslateMessage(&msg)) { DispatchMessage(&msg); } } } while(ret); hidden_main_window = NULL; return (DWORD)msg.wParam; } #endif static SIGHANDLER_T set_signal(int signum, SIGHANDLER_T handler, bool restartable) { #if defined(HAVE_SIGACTION) && defined(SA_RESTART) struct sigaction sa, oldsa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, signum); sa.sa_flags = restartable? SA_RESTART: 0; if(sigaction(signum, &sa, &oldsa)) return SIG_ERR; return oldsa.sa_handler; #else SIGHANDLER_T oldhdlr = signal(signum, handler); #ifdef HAVE_SIGINTERRUPT if(oldhdlr != SIG_ERR) siginterrupt(signum, (int) restartable); #else (void) restartable; #endif return oldhdlr; #endif } void install_signal_handlers(bool keep_sigalrm) { #ifdef WIN32 /* setup windows exit event before any signal can trigger */ exit_event = CreateEvent(NULL, TRUE, FALSE, NULL); if(!exit_event) logmsg("cannot create exit event"); #endif #ifdef SIGHUP /* ignore SIGHUP signal */ old_sighup_handler = set_signal(SIGHUP, SIG_IGN, FALSE); if(old_sighup_handler == SIG_ERR) logmsg("cannot install SIGHUP handler: %s", strerror(errno)); #endif #ifdef SIGPIPE /* ignore SIGPIPE signal */ old_sigpipe_handler = set_signal(SIGPIPE, SIG_IGN, FALSE); if(old_sigpipe_handler == SIG_ERR) logmsg("cannot install SIGPIPE handler: %s", strerror(errno)); #endif #ifdef SIGALRM if(!keep_sigalrm) { /* ignore SIGALRM signal */ old_sigalrm_handler = set_signal(SIGALRM, SIG_IGN, FALSE); if(old_sigalrm_handler == SIG_ERR) logmsg("cannot install SIGALRM handler: %s", strerror(errno)); } #else (void)keep_sigalrm; #endif #ifdef SIGINT /* handle SIGINT signal with our exit_signal_handler */ old_sigint_handler = set_signal(SIGINT, exit_signal_handler, TRUE); if(old_sigint_handler == SIG_ERR) logmsg("cannot install SIGINT handler: %s", strerror(errno)); #endif #ifdef SIGTERM /* handle SIGTERM signal with our exit_signal_handler */ old_sigterm_handler = set_signal(SIGTERM, exit_signal_handler, TRUE); if(old_sigterm_handler == SIG_ERR) logmsg("cannot install SIGTERM handler: %s", strerror(errno)); #endif #if defined(SIGBREAK) && defined(WIN32) /* handle SIGBREAK signal with our exit_signal_handler */ old_sigbreak_handler = set_signal(SIGBREAK, exit_signal_handler, TRUE); if(old_sigbreak_handler == SIG_ERR) logmsg("cannot install SIGBREAK handler: %s", strerror(errno)); #endif #ifdef WIN32 if(!SetConsoleCtrlHandler(ctrl_event_handler, TRUE)) logmsg("cannot install CTRL event handler"); thread_main_window = CreateThread(NULL, 0, &main_window_loop, (LPVOID)GetModuleHandle(NULL), 0, &thread_main_id); if(!thread_main_window || !thread_main_id) logmsg("cannot start main window loop"); #endif } void restore_signal_handlers(bool keep_sigalrm) { #ifdef SIGHUP if(SIG_ERR != old_sighup_handler) (void) set_signal(SIGHUP, old_sighup_handler, FALSE); #endif #ifdef SIGPIPE if(SIG_ERR != old_sigpipe_handler) (void) set_signal(SIGPIPE, old_sigpipe_handler, FALSE); #endif #ifdef SIGALRM if(!keep_sigalrm) { if(SIG_ERR != old_sigalrm_handler) (void) set_signal(SIGALRM, old_sigalrm_handler, FALSE); } #else (void)keep_sigalrm; #endif #ifdef SIGINT if(SIG_ERR != old_sigint_handler) (void) set_signal(SIGINT, old_sigint_handler, FALSE); #endif #ifdef SIGTERM if(SIG_ERR != old_sigterm_handler) (void) set_signal(SIGTERM, old_sigterm_handler, FALSE); #endif #if defined(SIGBREAK) && defined(WIN32) if(SIG_ERR != old_sigbreak_handler) (void) set_signal(SIGBREAK, old_sigbreak_handler, FALSE); #endif #ifdef WIN32 (void)SetConsoleCtrlHandler(ctrl_event_handler, FALSE); if(thread_main_window && thread_main_id) { if(PostThreadMessage(thread_main_id, WM_APP, 0, 0)) { if(WaitForSingleObjectEx(thread_main_window, INFINITE, TRUE)) { if(CloseHandle(thread_main_window)) { thread_main_window = NULL; thread_main_id = 0; } } } } if(exit_event) { if(CloseHandle(exit_event)) { exit_event = NULL; } } #endif }
0
repos/gpt4all.zig/src/zig-libcurl/curl/tests
repos/gpt4all.zig/src/zig-libcurl/curl/tests/server/disabled.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * The purpose of this tool is to figure out which, if any, features that are * disabled which should otherwise exist and work. These aren't visible in * regular curl -V output. * * Disabled protocols are visible in curl_version_info() and are not included * in this table. */ #include "curl_setup.h" #include "multihandle.h" /* for ENABLE_WAKEUP */ #include <stdio.h> static const char *disabled[]={ #ifdef CURL_DISABLE_COOKIES "cookies", #endif #ifdef CURL_DISABLE_CRYPTO_AUTH "crypto", #endif #ifdef CURL_DISABLE_DOH "DoH", #endif #ifdef CURL_DISABLE_HTTP_AUTH "HTTP-auth", #endif #ifdef CURL_DISABLE_MIME "Mime", #endif #ifdef CURL_DISABLE_NETRC "netrc", #endif #ifdef CURL_DISABLE_PARSEDATE "parsedate", #endif #ifdef CURL_DISABLE_PROXY "proxy", #endif #ifdef CURL_DISABLE_SHUFFLE_DNS "shuffle-dns", #endif #ifdef CURL_DISABLE_TYPECHECK "typecheck", #endif #ifdef CURL_DISABLE_VERBOSE_STRINGS "verbose-strings", #endif #ifndef ENABLE_WAKEUP "wakeup", #endif NULL }; int main(void) { int i; for(i = 0; disabled[i]; i++) printf("%s\n", disabled[i]); return 0; }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/include/README.md
# include Public include files for libcurl, external users. They're all placed in the curl subdirectory here for better fit in any kind of environment. You must include files from here using... #include <curl/curl.h> ... style and point the compiler's include path to the directory holding the curl subdirectory. It makes it more likely to survive future modifications. The public curl include files can be shared freely between different platforms and different architectures.
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/curl.h
#ifndef CURLINC_CURL_H #define CURLINC_CURL_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * If you have libcurl problems, all docs and details are found here: * https://curl.se/libcurl/ */ #ifdef CURL_NO_OLDIES #define CURL_STRICTER #endif #include "curlver.h" /* libcurl version defines */ #include "system.h" /* determine things run-time */ /* * Define CURL_WIN32 when build target is Win32 API */ #if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && \ !defined(__SYMBIAN32__) #define CURL_WIN32 #endif #include <stdio.h> #include <limits.h> #if (defined(__FreeBSD__) && (__FreeBSD__ >= 2)) || defined(__MidnightBSD__) /* Needed for __FreeBSD_version or __MidnightBSD_version symbol definition */ #include <osreldate.h> #endif /* The include stuff here below is mainly for time_t! */ #include <sys/types.h> #include <time.h> #if defined(CURL_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) #if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \ defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)) /* The check above prevents the winsock2 inclusion if winsock.h already was included, since they can't co-exist without problems */ #include <winsock2.h> #include <ws2tcpip.h> #endif #endif /* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish libc5-based Linux systems. Only include it on systems that are known to require it! */ #if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \ defined(__CYGWIN__) || defined(AMIGA) || defined(__NuttX__) || \ (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) || \ (defined(__MidnightBSD_version) && (__MidnightBSD_version < 100000)) || \ defined(__VXWORKS__) #include <sys/select.h> #endif #if !defined(CURL_WIN32) && !defined(_WIN32_WCE) #include <sys/socket.h> #endif #if !defined(CURL_WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__) #include <sys/time.h> #endif #ifdef __BEOS__ #include <support/SupportDefs.h> #endif /* Compatibility for non-Clang compilers */ #ifndef __has_declspec_attribute # define __has_declspec_attribute(x) 0 #endif #ifdef __cplusplus extern "C" { #endif #if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) typedef struct Curl_easy CURL; typedef struct Curl_share CURLSH; #else typedef void CURL; typedef void CURLSH; #endif /* * libcurl external API function linkage decorations. */ #ifdef CURL_STATICLIB # define CURL_EXTERN #elif defined(CURL_WIN32) || defined(__SYMBIAN32__) || \ (__has_declspec_attribute(dllexport) && \ __has_declspec_attribute(dllimport)) # if defined(BUILDING_LIBCURL) # define CURL_EXTERN __declspec(dllexport) # else # define CURL_EXTERN __declspec(dllimport) # endif #elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS) # define CURL_EXTERN CURL_EXTERN_SYMBOL #else # define CURL_EXTERN #endif #ifndef curl_socket_typedef /* socket typedef */ #if defined(CURL_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) typedef SOCKET curl_socket_t; #define CURL_SOCKET_BAD INVALID_SOCKET #else typedef int curl_socket_t; #define CURL_SOCKET_BAD -1 #endif #define curl_socket_typedef #endif /* curl_socket_typedef */ /* enum for the different supported SSL backends */ typedef enum { CURLSSLBACKEND_NONE = 0, CURLSSLBACKEND_OPENSSL = 1, CURLSSLBACKEND_GNUTLS = 2, CURLSSLBACKEND_NSS = 3, CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */ CURLSSLBACKEND_GSKIT = 5, CURLSSLBACKEND_POLARSSL = 6, CURLSSLBACKEND_WOLFSSL = 7, CURLSSLBACKEND_SCHANNEL = 8, CURLSSLBACKEND_SECURETRANSPORT = 9, CURLSSLBACKEND_AXTLS = 10, /* never used since 7.63.0 */ CURLSSLBACKEND_MBEDTLS = 11, CURLSSLBACKEND_MESALINK = 12, CURLSSLBACKEND_BEARSSL = 13, CURLSSLBACKEND_RUSTLS = 14 } curl_sslbackend; /* aliases for library clones and renames */ #define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL #define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL /* deprecated names: */ #define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL #define CURLSSLBACKEND_DARWINSSL CURLSSLBACKEND_SECURETRANSPORT struct curl_httppost { struct curl_httppost *next; /* next entry in the list */ char *name; /* pointer to allocated name */ long namelength; /* length of name length */ char *contents; /* pointer to allocated data contents */ long contentslength; /* length of contents field, see also CURL_HTTPPOST_LARGE */ char *buffer; /* pointer to allocated buffer contents */ long bufferlength; /* length of buffer field */ char *contenttype; /* Content-Type */ struct curl_slist *contentheader; /* list of extra headers for this form */ struct curl_httppost *more; /* if one field name has more than one file, this link should link to following files */ long flags; /* as defined below */ /* specified content is a file name */ #define CURL_HTTPPOST_FILENAME (1<<0) /* specified content is a file name */ #define CURL_HTTPPOST_READFILE (1<<1) /* name is only stored pointer do not free in formfree */ #define CURL_HTTPPOST_PTRNAME (1<<2) /* contents is only stored pointer do not free in formfree */ #define CURL_HTTPPOST_PTRCONTENTS (1<<3) /* upload file from buffer */ #define CURL_HTTPPOST_BUFFER (1<<4) /* upload file from pointer contents */ #define CURL_HTTPPOST_PTRBUFFER (1<<5) /* upload file contents by using the regular read callback to get the data and pass the given pointer as custom pointer */ #define CURL_HTTPPOST_CALLBACK (1<<6) /* use size in 'contentlen', added in 7.46.0 */ #define CURL_HTTPPOST_LARGE (1<<7) char *showfilename; /* The file name to show. If not set, the actual file name will be used (if this is a file part) */ void *userp; /* custom pointer used for HTTPPOST_CALLBACK posts */ curl_off_t contentlen; /* alternative length of contents field. Used if CURL_HTTPPOST_LARGE is set. Added in 7.46.0 */ }; /* This is a return code for the progress callback that, when returned, will signal libcurl to continue executing the default progress function */ #define CURL_PROGRESSFUNC_CONTINUE 0x10000001 /* This is the CURLOPT_PROGRESSFUNCTION callback prototype. It is now considered deprecated but was the only choice up until 7.31.0 */ typedef int (*curl_progress_callback)(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); /* This is the CURLOPT_XFERINFOFUNCTION callback prototype. It was introduced in 7.32.0, avoids the use of floating point numbers and provides more detailed information. */ typedef int (*curl_xferinfo_callback)(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow); #ifndef CURL_MAX_READ_SIZE /* The maximum receive buffer size configurable via CURLOPT_BUFFERSIZE. */ #define CURL_MAX_READ_SIZE 524288 #endif #ifndef CURL_MAX_WRITE_SIZE /* Tests have proven that 20K is a very bad buffer size for uploads on Windows, while 16K for some odd reason performed a lot better. We do the ifndef check to allow this value to easier be changed at build time for those who feel adventurous. The practical minimum is about 400 bytes since libcurl uses a buffer of this size as a scratch area (unrelated to network send operations). */ #define CURL_MAX_WRITE_SIZE 16384 #endif #ifndef CURL_MAX_HTTP_HEADER /* The only reason to have a max limit for this is to avoid the risk of a bad server feeding libcurl with a never-ending header that will cause reallocs infinitely */ #define CURL_MAX_HTTP_HEADER (100*1024) #endif /* This is a magic return code for the write callback that, when returned, will signal libcurl to pause receiving on the current transfer. */ #define CURL_WRITEFUNC_PAUSE 0x10000001 typedef size_t (*curl_write_callback)(char *buffer, size_t size, size_t nitems, void *outstream); /* This callback will be called when a new resolver request is made */ typedef int (*curl_resolver_start_callback)(void *resolver_state, void *reserved, void *userdata); /* enumeration of file types */ typedef enum { CURLFILETYPE_FILE = 0, CURLFILETYPE_DIRECTORY, CURLFILETYPE_SYMLINK, CURLFILETYPE_DEVICE_BLOCK, CURLFILETYPE_DEVICE_CHAR, CURLFILETYPE_NAMEDPIPE, CURLFILETYPE_SOCKET, CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */ CURLFILETYPE_UNKNOWN /* should never occur */ } curlfiletype; #define CURLFINFOFLAG_KNOWN_FILENAME (1<<0) #define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1) #define CURLFINFOFLAG_KNOWN_TIME (1<<2) #define CURLFINFOFLAG_KNOWN_PERM (1<<3) #define CURLFINFOFLAG_KNOWN_UID (1<<4) #define CURLFINFOFLAG_KNOWN_GID (1<<5) #define CURLFINFOFLAG_KNOWN_SIZE (1<<6) #define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7) /* Information about a single file, used when doing FTP wildcard matching */ struct curl_fileinfo { char *filename; curlfiletype filetype; time_t time; /* always zero! */ unsigned int perm; int uid; int gid; curl_off_t size; long int hardlinks; struct { /* If some of these fields is not NULL, it is a pointer to b_data. */ char *time; char *perm; char *user; char *group; char *target; /* pointer to the target filename of a symlink */ } strings; unsigned int flags; /* used internally */ char *b_data; size_t b_size; size_t b_used; }; /* return codes for CURLOPT_CHUNK_BGN_FUNCTION */ #define CURL_CHUNK_BGN_FUNC_OK 0 #define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */ #define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */ /* if splitting of data transfer is enabled, this callback is called before download of an individual chunk started. Note that parameter "remains" works only for FTP wildcard downloading (for now), otherwise is not used */ typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, void *ptr, int remains); /* return codes for CURLOPT_CHUNK_END_FUNCTION */ #define CURL_CHUNK_END_FUNC_OK 0 #define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */ /* If splitting of data transfer is enabled this callback is called after download of an individual chunk finished. Note! After this callback was set then it have to be called FOR ALL chunks. Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. This is the reason why we don't need "transfer_info" parameter in this callback and we are not interested in "remains" parameter too. */ typedef long (*curl_chunk_end_callback)(void *ptr); /* return codes for FNMATCHFUNCTION */ #define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ #define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */ #define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ /* callback type for wildcard downloading pattern matching. If the string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */ typedef int (*curl_fnmatch_callback)(void *ptr, const char *pattern, const char *string); /* These are the return codes for the seek callbacks */ #define CURL_SEEKFUNC_OK 0 #define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ #define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so libcurl might try other means instead */ typedef int (*curl_seek_callback)(void *instream, curl_off_t offset, int origin); /* 'whence' */ /* This is a return code for the read callback that, when returned, will signal libcurl to immediately abort the current transfer. */ #define CURL_READFUNC_ABORT 0x10000000 /* This is a return code for the read callback that, when returned, will signal libcurl to pause sending data on the current transfer. */ #define CURL_READFUNC_PAUSE 0x10000001 /* Return code for when the trailing headers' callback has terminated without any errors*/ #define CURL_TRAILERFUNC_OK 0 /* Return code for when was an error in the trailing header's list and we want to abort the request */ #define CURL_TRAILERFUNC_ABORT 1 typedef size_t (*curl_read_callback)(char *buffer, size_t size, size_t nitems, void *instream); typedef int (*curl_trailer_callback)(struct curl_slist **list, void *userdata); typedef enum { CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */ CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */ CURLSOCKTYPE_LAST /* never use */ } curlsocktype; /* The return code from the sockopt_callback can signal information back to libcurl: */ #define CURL_SOCKOPT_OK 0 #define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return CURLE_ABORTED_BY_CALLBACK */ #define CURL_SOCKOPT_ALREADY_CONNECTED 2 typedef int (*curl_sockopt_callback)(void *clientp, curl_socket_t curlfd, curlsocktype purpose); struct curl_sockaddr { int family; int socktype; int protocol; unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it turned really ugly and painful on the systems that lack this type */ struct sockaddr addr; }; typedef curl_socket_t (*curl_opensocket_callback)(void *clientp, curlsocktype purpose, struct curl_sockaddr *address); typedef int (*curl_closesocket_callback)(void *clientp, curl_socket_t item); typedef enum { CURLIOE_OK, /* I/O operation successful */ CURLIOE_UNKNOWNCMD, /* command was unknown to callback */ CURLIOE_FAILRESTART, /* failed to restart the read */ CURLIOE_LAST /* never use */ } curlioerr; typedef enum { CURLIOCMD_NOP, /* no operation */ CURLIOCMD_RESTARTREAD, /* restart the read stream from start */ CURLIOCMD_LAST /* never use */ } curliocmd; typedef curlioerr (*curl_ioctl_callback)(CURL *handle, int cmd, void *clientp); #ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS /* * The following typedef's are signatures of malloc, free, realloc, strdup and * calloc respectively. Function pointers of these types can be passed to the * curl_global_init_mem() function to set user defined memory management * callback routines. */ typedef void *(*curl_malloc_callback)(size_t size); typedef void (*curl_free_callback)(void *ptr); typedef void *(*curl_realloc_callback)(void *ptr, size_t size); typedef char *(*curl_strdup_callback)(const char *str); typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); #define CURL_DID_MEMORY_FUNC_TYPEDEFS #endif /* the kind of data that is passed to information_callback*/ typedef enum { CURLINFO_TEXT = 0, CURLINFO_HEADER_IN, /* 1 */ CURLINFO_HEADER_OUT, /* 2 */ CURLINFO_DATA_IN, /* 3 */ CURLINFO_DATA_OUT, /* 4 */ CURLINFO_SSL_DATA_IN, /* 5 */ CURLINFO_SSL_DATA_OUT, /* 6 */ CURLINFO_END } curl_infotype; typedef int (*curl_debug_callback) (CURL *handle, /* the handle/transfer this concerns */ curl_infotype type, /* what kind of data */ char *data, /* points to the data */ size_t size, /* size of the data pointed to */ void *userptr); /* whatever the user please */ /* This is the CURLOPT_PREREQFUNCTION callback prototype. */ typedef int (*curl_prereq_callback)(void *clientp, char *conn_primary_ip, char *conn_local_ip, int conn_primary_port, int conn_local_port); /* Return code for when the pre-request callback has terminated without any errors */ #define CURL_PREREQFUNC_OK 0 /* Return code for when the pre-request callback wants to abort the request */ #define CURL_PREREQFUNC_ABORT 1 /* All possible error codes from all sorts of curl functions. Future versions may return other values, stay prepared. Always add new return codes last. Never *EVER* remove any. The return codes must remain the same! */ typedef enum { CURLE_OK = 0, CURLE_UNSUPPORTED_PROTOCOL, /* 1 */ CURLE_FAILED_INIT, /* 2 */ CURLE_URL_MALFORMAT, /* 3 */ CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for 7.17.0, reused in April 2011 for 7.21.5] */ CURLE_COULDNT_RESOLVE_PROXY, /* 5 */ CURLE_COULDNT_RESOLVE_HOST, /* 6 */ CURLE_COULDNT_CONNECT, /* 7 */ CURLE_WEIRD_SERVER_REPLY, /* 8 */ CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server due to lack of access - when login fails this is not returned. */ CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for 7.15.4, reused in Dec 2011 for 7.24.0]*/ CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */ CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server [was obsoleted in August 2007 for 7.17.0, reused in Dec 2011 for 7.24.0]*/ CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */ CURLE_FTP_WEIRD_227_FORMAT, /* 14 */ CURLE_FTP_CANT_GET_HOST, /* 15 */ CURLE_HTTP2, /* 16 - A problem in the http2 framing layer. [was obsoleted in August 2007 for 7.17.0, reused in July 2014 for 7.38.0] */ CURLE_FTP_COULDNT_SET_TYPE, /* 17 */ CURLE_PARTIAL_FILE, /* 18 */ CURLE_FTP_COULDNT_RETR_FILE, /* 19 */ CURLE_OBSOLETE20, /* 20 - NOT USED */ CURLE_QUOTE_ERROR, /* 21 - quote command failure */ CURLE_HTTP_RETURNED_ERROR, /* 22 */ CURLE_WRITE_ERROR, /* 23 */ CURLE_OBSOLETE24, /* 24 - NOT USED */ CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ CURLE_READ_ERROR, /* 26 - couldn't open/read from file */ CURLE_OUT_OF_MEMORY, /* 27 */ /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error instead of a memory allocation error if CURL_DOES_CONVERSIONS is defined */ CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ CURLE_OBSOLETE29, /* 29 - NOT USED */ CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ CURLE_OBSOLETE32, /* 32 - NOT USED */ CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */ CURLE_HTTP_POST_ERROR, /* 34 */ CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */ CURLE_FILE_COULDNT_READ_FILE, /* 37 */ CURLE_LDAP_CANNOT_BIND, /* 38 */ CURLE_LDAP_SEARCH_FAILED, /* 39 */ CURLE_OBSOLETE40, /* 40 - NOT USED */ CURLE_FUNCTION_NOT_FOUND, /* 41 - NOT USED starting with 7.53.0 */ CURLE_ABORTED_BY_CALLBACK, /* 42 */ CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */ CURLE_OBSOLETE44, /* 44 - NOT USED */ CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ CURLE_OBSOLETE46, /* 46 - NOT USED */ CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */ CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ CURLE_SETOPT_OPTION_SYNTAX, /* 49 - Malformed setopt option */ CURLE_OBSOLETE50, /* 50 - NOT USED */ CURLE_OBSOLETE51, /* 51 - NOT USED */ CURLE_GOT_NOTHING, /* 52 - when this is a specific error */ CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */ CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as default */ CURLE_SEND_ERROR, /* 55 - failed sending network data */ CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ CURLE_OBSOLETE57, /* 57 - NOT IN USE */ CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */ CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint wasn't verified fine */ CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */ CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */ CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind that failed */ CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */ CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not accepted and we failed to login */ CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */ CURLE_TFTP_PERM, /* 69 - permission problem on server */ CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */ CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */ CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */ CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */ CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */ CURLE_CONV_FAILED, /* 75 - conversion failed */ CURLE_CONV_REQD, /* 76 - caller must register conversion callbacks using curl_easy_setopt options CURLOPT_CONV_FROM_NETWORK_FUNCTION, CURLOPT_CONV_TO_NETWORK_FUNCTION, and CURLOPT_CONV_FROM_UTF8_FUNCTION */ CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing or wrong format */ CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */ CURLE_SSH, /* 79 - error from the SSH layer, somewhat generic so the error message will be of interest when this has happened */ CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL connection */ CURLE_AGAIN, /* 81 - socket is not ready for send/recv, wait till it's ready and try again (Added in 7.18.2) */ CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or wrong format (Added in 7.19.0) */ CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in 7.19.0) */ CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */ CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */ CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */ CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */ CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */ CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the session will be queued */ CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not match */ CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */ CURLE_HTTP2_STREAM, /* 92 - stream error in HTTP/2 framing layer */ CURLE_RECURSIVE_API_CALL, /* 93 - an api function was called from inside a callback */ CURLE_AUTH_ERROR, /* 94 - an authentication function returned an error */ CURLE_HTTP3, /* 95 - An HTTP/3 layer problem */ CURLE_QUIC_CONNECT_ERROR, /* 96 - QUIC connection error */ CURLE_PROXY, /* 97 - proxy handshake error */ CURLE_SSL_CLIENTCERT, /* 98 - client-side certificate required */ CURL_LAST /* never use! */ } CURLcode; #ifndef CURL_NO_OLDIES /* define this to test if your app builds with all the obsolete stuff removed! */ /* Previously obsolete error code re-used in 7.38.0 */ #define CURLE_OBSOLETE16 CURLE_HTTP2 /* Previously obsolete error codes re-used in 7.24.0 */ #define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED #define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT /* compatibility with older names */ #define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING #define CURLE_FTP_WEIRD_SERVER_REPLY CURLE_WEIRD_SERVER_REPLY /* The following were added in 7.62.0 */ #define CURLE_SSL_CACERT CURLE_PEER_FAILED_VERIFICATION /* The following were added in 7.21.5, April 2011 */ #define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION /* Added for 7.78.0 */ #define CURLE_TELNET_OPTION_SYNTAX CURLE_SETOPT_OPTION_SYNTAX /* The following were added in 7.17.1 */ /* These are scheduled to disappear by 2009 */ #define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION /* The following were added in 7.17.0 */ /* These are scheduled to disappear by 2009 */ #define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */ #define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46 #define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44 #define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10 #define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16 #define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32 #define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29 #define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12 #define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20 #define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40 #define CURLE_MALFORMAT_USER CURLE_OBSOLETE24 #define CURLE_SHARE_IN_USE CURLE_OBSOLETE57 #define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN #define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED #define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE #define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR #define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL #define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS #define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR #define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED /* The following were added earlier */ #define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT #define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR #define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED #define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED #define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE #define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME /* This was the error code 50 in 7.7.3 and a few earlier versions, this is no longer used by libcurl but is instead #defined here only to not make programs break */ #define CURLE_ALREADY_COMPLETE 99999 /* Provide defines for really old option names */ #define CURLOPT_FILE CURLOPT_WRITEDATA /* name changed in 7.9.7 */ #define CURLOPT_INFILE CURLOPT_READDATA /* name changed in 7.9.7 */ #define CURLOPT_WRITEHEADER CURLOPT_HEADERDATA /* Since long deprecated options with no code in the lib that does anything with them. */ #define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40 #define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72 #endif /*!CURL_NO_OLDIES*/ /* * Proxy error codes. Returned in CURLINFO_PROXY_ERROR if CURLE_PROXY was * return for the transfers. */ typedef enum { CURLPX_OK, CURLPX_BAD_ADDRESS_TYPE, CURLPX_BAD_VERSION, CURLPX_CLOSED, CURLPX_GSSAPI, CURLPX_GSSAPI_PERMSG, CURLPX_GSSAPI_PROTECTION, CURLPX_IDENTD, CURLPX_IDENTD_DIFFER, CURLPX_LONG_HOSTNAME, CURLPX_LONG_PASSWD, CURLPX_LONG_USER, CURLPX_NO_AUTH, CURLPX_RECV_ADDRESS, CURLPX_RECV_AUTH, CURLPX_RECV_CONNECT, CURLPX_RECV_REQACK, CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED, CURLPX_REPLY_COMMAND_NOT_SUPPORTED, CURLPX_REPLY_CONNECTION_REFUSED, CURLPX_REPLY_GENERAL_SERVER_FAILURE, CURLPX_REPLY_HOST_UNREACHABLE, CURLPX_REPLY_NETWORK_UNREACHABLE, CURLPX_REPLY_NOT_ALLOWED, CURLPX_REPLY_TTL_EXPIRED, CURLPX_REPLY_UNASSIGNED, CURLPX_REQUEST_FAILED, CURLPX_RESOLVE_HOST, CURLPX_SEND_AUTH, CURLPX_SEND_CONNECT, CURLPX_SEND_REQUEST, CURLPX_UNKNOWN_FAIL, CURLPX_UNKNOWN_MODE, CURLPX_USER_REJECTED, CURLPX_LAST /* never use */ } CURLproxycode; /* This prototype applies to all conversion callbacks */ typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ void *ssl_ctx, /* actually an OpenSSL or WolfSSL SSL_CTX, or an mbedTLS mbedtls_ssl_config */ void *userptr); typedef enum { CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use CONNECT HTTP/1.1 */ CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT HTTP/1.0 */ CURLPROXY_HTTPS = 2, /* added in 7.52.0 */ CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already in 7.10 */ CURLPROXY_SOCKS5 = 5, /* added in 7.10 */ CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */ CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the host name rather than the IP address. added in 7.18.0 */ } curl_proxytype; /* this enum was added in 7.10 */ /* * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options: * * CURLAUTH_NONE - No HTTP authentication * CURLAUTH_BASIC - HTTP Basic authentication (default) * CURLAUTH_DIGEST - HTTP Digest authentication * CURLAUTH_NEGOTIATE - HTTP Negotiate (SPNEGO) authentication * CURLAUTH_GSSNEGOTIATE - Alias for CURLAUTH_NEGOTIATE (deprecated) * CURLAUTH_NTLM - HTTP NTLM authentication * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper * CURLAUTH_BEARER - HTTP Bearer token authentication * CURLAUTH_ONLY - Use together with a single other type to force no * authentication or just that single type * CURLAUTH_ANY - All fine types set * CURLAUTH_ANYSAFE - All fine types except Basic */ #define CURLAUTH_NONE ((unsigned long)0) #define CURLAUTH_BASIC (((unsigned long)1)<<0) #define CURLAUTH_DIGEST (((unsigned long)1)<<1) #define CURLAUTH_NEGOTIATE (((unsigned long)1)<<2) /* Deprecated since the advent of CURLAUTH_NEGOTIATE */ #define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE /* Used for CURLOPT_SOCKS5_AUTH to stay terminologically correct */ #define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE #define CURLAUTH_NTLM (((unsigned long)1)<<3) #define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4) #define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) #define CURLAUTH_BEARER (((unsigned long)1)<<6) #define CURLAUTH_AWS_SIGV4 (((unsigned long)1)<<7) #define CURLAUTH_ONLY (((unsigned long)1)<<31) #define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE) #define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE)) #define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */ #define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */ #define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */ #define CURLSSH_AUTH_PASSWORD (1<<1) /* password */ #define CURLSSH_AUTH_HOST (1<<2) /* host key files */ #define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */ #define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */ #define CURLSSH_AUTH_GSSAPI (1<<5) /* gssapi (kerberos, ...) */ #define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY #define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */ #define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */ #define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */ #define CURL_ERROR_SIZE 256 enum curl_khtype { CURLKHTYPE_UNKNOWN, CURLKHTYPE_RSA1, CURLKHTYPE_RSA, CURLKHTYPE_DSS, CURLKHTYPE_ECDSA, CURLKHTYPE_ED25519 }; struct curl_khkey { const char *key; /* points to a null-terminated string encoded with base64 if len is zero, otherwise to the "raw" data */ size_t len; enum curl_khtype keytype; }; /* this is the set of return values expected from the curl_sshkeycallback callback */ enum curl_khstat { CURLKHSTAT_FINE_ADD_TO_FILE, CURLKHSTAT_FINE, CURLKHSTAT_REJECT, /* reject the connection, return an error */ CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so this causes a CURLE_DEFER error but otherwise the connection will be left intact etc */ CURLKHSTAT_FINE_REPLACE, /* accept and replace the wrong key*/ CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */ }; /* this is the set of status codes pass in to the callback */ enum curl_khmatch { CURLKHMATCH_OK, /* match */ CURLKHMATCH_MISMATCH, /* host found, key mismatch! */ CURLKHMATCH_MISSING, /* no matching host/key found */ CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */ }; typedef int (*curl_sshkeycallback) (CURL *easy, /* easy handle */ const struct curl_khkey *knownkey, /* known */ const struct curl_khkey *foundkey, /* found */ enum curl_khmatch, /* libcurl's view on the keys */ void *clientp); /* custom pointer passed from app */ /* parameter for the CURLOPT_USE_SSL option */ typedef enum { CURLUSESSL_NONE, /* do not attempt to use SSL */ CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */ CURLUSESSL_CONTROL, /* SSL for the control connection or fail */ CURLUSESSL_ALL, /* SSL for all communication or fail */ CURLUSESSL_LAST /* not an option, never use */ } curl_usessl; /* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */ /* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the name of improving interoperability with older servers. Some SSL libraries have introduced work-arounds for this flaw but those work-arounds sometimes make the SSL communication fail. To regain functionality with those broken servers, a user can this way allow the vulnerability back. */ #define CURLSSLOPT_ALLOW_BEAST (1<<0) /* - NO_REVOKE tells libcurl to disable certificate revocation checks for those SSL backends where such behavior is present. */ #define CURLSSLOPT_NO_REVOKE (1<<1) /* - NO_PARTIALCHAIN tells libcurl to *NOT* accept a partial certificate chain if possible. The OpenSSL backend has this ability. */ #define CURLSSLOPT_NO_PARTIALCHAIN (1<<2) /* - REVOKE_BEST_EFFORT tells libcurl to ignore certificate revocation offline checks and ignore missing revocation list for those SSL backends where such behavior is present. */ #define CURLSSLOPT_REVOKE_BEST_EFFORT (1<<3) /* - CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of operating system. Currently implemented under MS-Windows. */ #define CURLSSLOPT_NATIVE_CA (1<<4) /* - CURLSSLOPT_AUTO_CLIENT_CERT tells libcurl to automatically locate and use a client certificate for authentication. (Schannel) */ #define CURLSSLOPT_AUTO_CLIENT_CERT (1<<5) /* The default connection attempt delay in milliseconds for happy eyeballs. CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS.3 and happy-eyeballs-timeout-ms.d document this value, keep them in sync. */ #define CURL_HET_DEFAULT 200L /* The default connection upkeep interval in milliseconds. */ #define CURL_UPKEEP_INTERVAL_DEFAULT 60000L #ifndef CURL_NO_OLDIES /* define this to test if your app builds with all the obsolete stuff removed! */ /* Backwards compatibility with older names */ /* These are scheduled to disappear by 2009 */ #define CURLFTPSSL_NONE CURLUSESSL_NONE #define CURLFTPSSL_TRY CURLUSESSL_TRY #define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL #define CURLFTPSSL_ALL CURLUSESSL_ALL #define CURLFTPSSL_LAST CURLUSESSL_LAST #define curl_ftpssl curl_usessl #endif /*!CURL_NO_OLDIES*/ /* parameter for the CURLOPT_FTP_SSL_CCC option */ typedef enum { CURLFTPSSL_CCC_NONE, /* do not send CCC */ CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */ CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */ CURLFTPSSL_CCC_LAST /* not an option, never use */ } curl_ftpccc; /* parameter for the CURLOPT_FTPSSLAUTH option */ typedef enum { CURLFTPAUTH_DEFAULT, /* let libcurl decide */ CURLFTPAUTH_SSL, /* use "AUTH SSL" */ CURLFTPAUTH_TLS, /* use "AUTH TLS" */ CURLFTPAUTH_LAST /* not an option, never use */ } curl_ftpauth; /* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */ typedef enum { CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */ CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD again if MKD succeeded, for SFTP this does similar magic */ CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD again even if MKD failed! */ CURLFTP_CREATE_DIR_LAST /* not an option, never use */ } curl_ftpcreatedir; /* parameter for the CURLOPT_FTP_FILEMETHOD option */ typedef enum { CURLFTPMETHOD_DEFAULT, /* let libcurl pick */ CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */ CURLFTPMETHOD_NOCWD, /* no CWD at all */ CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */ CURLFTPMETHOD_LAST /* not an option, never use */ } curl_ftpmethod; /* bitmask defines for CURLOPT_HEADEROPT */ #define CURLHEADER_UNIFIED 0 #define CURLHEADER_SEPARATE (1<<0) /* CURLALTSVC_* are bits for the CURLOPT_ALTSVC_CTRL option */ #define CURLALTSVC_READONLYFILE (1<<2) #define CURLALTSVC_H1 (1<<3) #define CURLALTSVC_H2 (1<<4) #define CURLALTSVC_H3 (1<<5) struct curl_hstsentry { char *name; size_t namelen; unsigned int includeSubDomains:1; char expire[18]; /* YYYYMMDD HH:MM:SS [null-terminated] */ }; struct curl_index { size_t index; /* the provided entry's "index" or count */ size_t total; /* total number of entries to save */ }; typedef enum { CURLSTS_OK, CURLSTS_DONE, CURLSTS_FAIL } CURLSTScode; typedef CURLSTScode (*curl_hstsread_callback)(CURL *easy, struct curl_hstsentry *e, void *userp); typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy, struct curl_hstsentry *e, struct curl_index *i, void *userp); /* CURLHSTS_* are bits for the CURLOPT_HSTS option */ #define CURLHSTS_ENABLE (long)(1<<0) #define CURLHSTS_READONLYFILE (long)(1<<1) /* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */ #define CURLPROTO_HTTP (1<<0) #define CURLPROTO_HTTPS (1<<1) #define CURLPROTO_FTP (1<<2) #define CURLPROTO_FTPS (1<<3) #define CURLPROTO_SCP (1<<4) #define CURLPROTO_SFTP (1<<5) #define CURLPROTO_TELNET (1<<6) #define CURLPROTO_LDAP (1<<7) #define CURLPROTO_LDAPS (1<<8) #define CURLPROTO_DICT (1<<9) #define CURLPROTO_FILE (1<<10) #define CURLPROTO_TFTP (1<<11) #define CURLPROTO_IMAP (1<<12) #define CURLPROTO_IMAPS (1<<13) #define CURLPROTO_POP3 (1<<14) #define CURLPROTO_POP3S (1<<15) #define CURLPROTO_SMTP (1<<16) #define CURLPROTO_SMTPS (1<<17) #define CURLPROTO_RTSP (1<<18) #define CURLPROTO_RTMP (1<<19) #define CURLPROTO_RTMPT (1<<20) #define CURLPROTO_RTMPE (1<<21) #define CURLPROTO_RTMPTE (1<<22) #define CURLPROTO_RTMPS (1<<23) #define CURLPROTO_RTMPTS (1<<24) #define CURLPROTO_GOPHER (1<<25) #define CURLPROTO_SMB (1<<26) #define CURLPROTO_SMBS (1<<27) #define CURLPROTO_MQTT (1<<28) #define CURLPROTO_GOPHERS (1<<29) #define CURLPROTO_ALL (~0) /* enable everything */ /* long may be 32 or 64 bits, but we should never depend on anything else but 32 */ #define CURLOPTTYPE_LONG 0 #define CURLOPTTYPE_OBJECTPOINT 10000 #define CURLOPTTYPE_FUNCTIONPOINT 20000 #define CURLOPTTYPE_OFF_T 30000 #define CURLOPTTYPE_BLOB 40000 /* *STRINGPOINT is an alias for OBJECTPOINT to allow tools to extract the string options from the header file */ #define CURLOPT(na,t,nu) na = t + nu /* CURLOPT aliases that make no run-time difference */ /* 'char *' argument to a string with a trailing zero */ #define CURLOPTTYPE_STRINGPOINT CURLOPTTYPE_OBJECTPOINT /* 'struct curl_slist *' argument */ #define CURLOPTTYPE_SLISTPOINT CURLOPTTYPE_OBJECTPOINT /* 'void *' argument passed untouched to callback */ #define CURLOPTTYPE_CBPOINT CURLOPTTYPE_OBJECTPOINT /* 'long' argument with a set of values/bitmask */ #define CURLOPTTYPE_VALUES CURLOPTTYPE_LONG /* * All CURLOPT_* values. */ typedef enum { /* This is the FILE * or void * the regular output should be written to. */ CURLOPT(CURLOPT_WRITEDATA, CURLOPTTYPE_CBPOINT, 1), /* The full URL to get/put */ CURLOPT(CURLOPT_URL, CURLOPTTYPE_STRINGPOINT, 2), /* Port number to connect to, if other than default. */ CURLOPT(CURLOPT_PORT, CURLOPTTYPE_LONG, 3), /* Name of proxy to use. */ CURLOPT(CURLOPT_PROXY, CURLOPTTYPE_STRINGPOINT, 4), /* "user:password;options" to use when fetching. */ CURLOPT(CURLOPT_USERPWD, CURLOPTTYPE_STRINGPOINT, 5), /* "user:password" to use with proxy. */ CURLOPT(CURLOPT_PROXYUSERPWD, CURLOPTTYPE_STRINGPOINT, 6), /* Range to get, specified as an ASCII string. */ CURLOPT(CURLOPT_RANGE, CURLOPTTYPE_STRINGPOINT, 7), /* not used */ /* Specified file stream to upload from (use as input): */ CURLOPT(CURLOPT_READDATA, CURLOPTTYPE_CBPOINT, 9), /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE * bytes big. */ CURLOPT(CURLOPT_ERRORBUFFER, CURLOPTTYPE_OBJECTPOINT, 10), /* Function that will be called to store the output (instead of fwrite). The * parameters will use fwrite() syntax, make sure to follow them. */ CURLOPT(CURLOPT_WRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 11), /* Function that will be called to read the input (instead of fread). The * parameters will use fread() syntax, make sure to follow them. */ CURLOPT(CURLOPT_READFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 12), /* Time-out the read operation after this amount of seconds */ CURLOPT(CURLOPT_TIMEOUT, CURLOPTTYPE_LONG, 13), /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about * how large the file being sent really is. That allows better error * checking and better verifies that the upload was successful. -1 means * unknown size. * * For large file support, there is also a _LARGE version of the key * which takes an off_t type, allowing platforms with larger off_t * sizes to handle larger files. See below for INFILESIZE_LARGE. */ CURLOPT(CURLOPT_INFILESIZE, CURLOPTTYPE_LONG, 14), /* POST static input fields. */ CURLOPT(CURLOPT_POSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 15), /* Set the referrer page (needed by some CGIs) */ CURLOPT(CURLOPT_REFERER, CURLOPTTYPE_STRINGPOINT, 16), /* Set the FTP PORT string (interface name, named or numerical IP address) Use i.e '-' to use default address. */ CURLOPT(CURLOPT_FTPPORT, CURLOPTTYPE_STRINGPOINT, 17), /* Set the User-Agent string (examined by some CGIs) */ CURLOPT(CURLOPT_USERAGENT, CURLOPTTYPE_STRINGPOINT, 18), /* If the download receives less than "low speed limit" bytes/second * during "low speed time" seconds, the operations is aborted. * You could i.e if you have a pretty high speed connection, abort if * it is less than 2000 bytes/sec during 20 seconds. */ /* Set the "low speed limit" */ CURLOPT(CURLOPT_LOW_SPEED_LIMIT, CURLOPTTYPE_LONG, 19), /* Set the "low speed time" */ CURLOPT(CURLOPT_LOW_SPEED_TIME, CURLOPTTYPE_LONG, 20), /* Set the continuation offset. * * Note there is also a _LARGE version of this key which uses * off_t types, allowing for large file offsets on platforms which * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. */ CURLOPT(CURLOPT_RESUME_FROM, CURLOPTTYPE_LONG, 21), /* Set cookie in request: */ CURLOPT(CURLOPT_COOKIE, CURLOPTTYPE_STRINGPOINT, 22), /* This points to a linked list of headers, struct curl_slist kind. This list is also used for RTSP (in spite of its name) */ CURLOPT(CURLOPT_HTTPHEADER, CURLOPTTYPE_SLISTPOINT, 23), /* This points to a linked list of post entries, struct curl_httppost */ CURLOPT(CURLOPT_HTTPPOST, CURLOPTTYPE_OBJECTPOINT, 24), /* name of the file keeping your private SSL-certificate */ CURLOPT(CURLOPT_SSLCERT, CURLOPTTYPE_STRINGPOINT, 25), /* password for the SSL or SSH private key */ CURLOPT(CURLOPT_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 26), /* send TYPE parameter? */ CURLOPT(CURLOPT_CRLF, CURLOPTTYPE_LONG, 27), /* send linked-list of QUOTE commands */ CURLOPT(CURLOPT_QUOTE, CURLOPTTYPE_SLISTPOINT, 28), /* send FILE * or void * to store headers to, if you use a callback it is simply passed to the callback unmodified */ CURLOPT(CURLOPT_HEADERDATA, CURLOPTTYPE_CBPOINT, 29), /* point to a file to read the initial cookies from, also enables "cookie awareness" */ CURLOPT(CURLOPT_COOKIEFILE, CURLOPTTYPE_STRINGPOINT, 31), /* What version to specifically try to use. See CURL_SSLVERSION defines below. */ CURLOPT(CURLOPT_SSLVERSION, CURLOPTTYPE_VALUES, 32), /* What kind of HTTP time condition to use, see defines */ CURLOPT(CURLOPT_TIMECONDITION, CURLOPTTYPE_VALUES, 33), /* Time to use with the above condition. Specified in number of seconds since 1 Jan 1970 */ CURLOPT(CURLOPT_TIMEVALUE, CURLOPTTYPE_LONG, 34), /* 35 = OBSOLETE */ /* Custom request, for customizing the get command like HTTP: DELETE, TRACE and others FTP: to use a different list command */ CURLOPT(CURLOPT_CUSTOMREQUEST, CURLOPTTYPE_STRINGPOINT, 36), /* FILE handle to use instead of stderr */ CURLOPT(CURLOPT_STDERR, CURLOPTTYPE_OBJECTPOINT, 37), /* 38 is not used */ /* send linked-list of post-transfer QUOTE commands */ CURLOPT(CURLOPT_POSTQUOTE, CURLOPTTYPE_SLISTPOINT, 39), /* OBSOLETE, do not use! */ CURLOPT(CURLOPT_OBSOLETE40, CURLOPTTYPE_OBJECTPOINT, 40), /* talk a lot */ CURLOPT(CURLOPT_VERBOSE, CURLOPTTYPE_LONG, 41), /* throw the header out too */ CURLOPT(CURLOPT_HEADER, CURLOPTTYPE_LONG, 42), /* shut off the progress meter */ CURLOPT(CURLOPT_NOPROGRESS, CURLOPTTYPE_LONG, 43), /* use HEAD to get http document */ CURLOPT(CURLOPT_NOBODY, CURLOPTTYPE_LONG, 44), /* no output on http error codes >= 400 */ CURLOPT(CURLOPT_FAILONERROR, CURLOPTTYPE_LONG, 45), /* this is an upload */ CURLOPT(CURLOPT_UPLOAD, CURLOPTTYPE_LONG, 46), /* HTTP POST method */ CURLOPT(CURLOPT_POST, CURLOPTTYPE_LONG, 47), /* bare names when listing directories */ CURLOPT(CURLOPT_DIRLISTONLY, CURLOPTTYPE_LONG, 48), /* Append instead of overwrite on upload! */ CURLOPT(CURLOPT_APPEND, CURLOPTTYPE_LONG, 50), /* Specify whether to read the user+password from the .netrc or the URL. * This must be one of the CURL_NETRC_* enums below. */ CURLOPT(CURLOPT_NETRC, CURLOPTTYPE_VALUES, 51), /* use Location: Luke! */ CURLOPT(CURLOPT_FOLLOWLOCATION, CURLOPTTYPE_LONG, 52), /* transfer data in text/ASCII format */ CURLOPT(CURLOPT_TRANSFERTEXT, CURLOPTTYPE_LONG, 53), /* HTTP PUT */ CURLOPT(CURLOPT_PUT, CURLOPTTYPE_LONG, 54), /* 55 = OBSOLETE */ /* DEPRECATED * Function that will be called instead of the internal progress display * function. This function should be defined as the curl_progress_callback * prototype defines. */ CURLOPT(CURLOPT_PROGRESSFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 56), /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION callbacks */ CURLOPT(CURLOPT_XFERINFODATA, CURLOPTTYPE_CBPOINT, 57), #define CURLOPT_PROGRESSDATA CURLOPT_XFERINFODATA /* We want the referrer field set automatically when following locations */ CURLOPT(CURLOPT_AUTOREFERER, CURLOPTTYPE_LONG, 58), /* Port of the proxy, can be set in the proxy string as well with: "[host]:[port]" */ CURLOPT(CURLOPT_PROXYPORT, CURLOPTTYPE_LONG, 59), /* size of the POST input data, if strlen() is not good to use */ CURLOPT(CURLOPT_POSTFIELDSIZE, CURLOPTTYPE_LONG, 60), /* tunnel non-http operations through a HTTP proxy */ CURLOPT(CURLOPT_HTTPPROXYTUNNEL, CURLOPTTYPE_LONG, 61), /* Set the interface string to use as outgoing network interface */ CURLOPT(CURLOPT_INTERFACE, CURLOPTTYPE_STRINGPOINT, 62), /* Set the krb4/5 security level, this also enables krb4/5 awareness. This * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string * is set but doesn't match one of these, 'private' will be used. */ CURLOPT(CURLOPT_KRBLEVEL, CURLOPTTYPE_STRINGPOINT, 63), /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ CURLOPT(CURLOPT_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 64), /* The CApath or CAfile used to validate the peer certificate this option is used only if SSL_VERIFYPEER is true */ CURLOPT(CURLOPT_CAINFO, CURLOPTTYPE_STRINGPOINT, 65), /* 66 = OBSOLETE */ /* 67 = OBSOLETE */ /* Maximum number of http redirects to follow */ CURLOPT(CURLOPT_MAXREDIRS, CURLOPTTYPE_LONG, 68), /* Pass a long set to 1 to get the date of the requested document (if possible)! Pass a zero to shut it off. */ CURLOPT(CURLOPT_FILETIME, CURLOPTTYPE_LONG, 69), /* This points to a linked list of telnet options */ CURLOPT(CURLOPT_TELNETOPTIONS, CURLOPTTYPE_SLISTPOINT, 70), /* Max amount of cached alive connections */ CURLOPT(CURLOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 71), /* OBSOLETE, do not use! */ CURLOPT(CURLOPT_OBSOLETE72, CURLOPTTYPE_LONG, 72), /* 73 = OBSOLETE */ /* Set to explicitly use a new connection for the upcoming transfer. Do not use this unless you're absolutely sure of this, as it makes the operation slower and is less friendly for the network. */ CURLOPT(CURLOPT_FRESH_CONNECT, CURLOPTTYPE_LONG, 74), /* Set to explicitly forbid the upcoming transfer's connection to be re-used when done. Do not use this unless you're absolutely sure of this, as it makes the operation slower and is less friendly for the network. */ CURLOPT(CURLOPT_FORBID_REUSE, CURLOPTTYPE_LONG, 75), /* Set to a file name that contains random data for libcurl to use to seed the random engine when doing SSL connects. */ CURLOPT(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76), /* Set to the Entropy Gathering Daemon socket pathname */ CURLOPT(CURLOPT_EGDSOCKET, CURLOPTTYPE_STRINGPOINT, 77), /* Time-out connect operations after this amount of seconds, if connects are OK within this time, then fine... This only aborts the connect phase. */ CURLOPT(CURLOPT_CONNECTTIMEOUT, CURLOPTTYPE_LONG, 78), /* Function that will be called to store headers (instead of fwrite). The * parameters will use fwrite() syntax, make sure to follow them. */ CURLOPT(CURLOPT_HEADERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 79), /* Set this to force the HTTP request to get back to GET. Only really usable if POST, PUT or a custom request have been used first. */ CURLOPT(CURLOPT_HTTPGET, CURLOPTTYPE_LONG, 80), /* Set if we should verify the Common name from the peer certificate in ssl * handshake, set 1 to check existence, 2 to ensure that it matches the * provided hostname. */ CURLOPT(CURLOPT_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 81), /* Specify which file name to write all known cookies in after completed operation. Set file name to "-" (dash) to make it go to stdout. */ CURLOPT(CURLOPT_COOKIEJAR, CURLOPTTYPE_STRINGPOINT, 82), /* Specify which SSL ciphers to use */ CURLOPT(CURLOPT_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 83), /* Specify which HTTP version to use! This must be set to one of the CURL_HTTP_VERSION* enums set below. */ CURLOPT(CURLOPT_HTTP_VERSION, CURLOPTTYPE_VALUES, 84), /* Specifically switch on or off the FTP engine's use of the EPSV command. By default, that one will always be attempted before the more traditional PASV command. */ CURLOPT(CURLOPT_FTP_USE_EPSV, CURLOPTTYPE_LONG, 85), /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ CURLOPT(CURLOPT_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 86), /* name of the file keeping your private SSL-key */ CURLOPT(CURLOPT_SSLKEY, CURLOPTTYPE_STRINGPOINT, 87), /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ CURLOPT(CURLOPT_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 88), /* crypto engine for the SSL-sub system */ CURLOPT(CURLOPT_SSLENGINE, CURLOPTTYPE_STRINGPOINT, 89), /* set the crypto engine for the SSL-sub system as default the param has no meaning... */ CURLOPT(CURLOPT_SSLENGINE_DEFAULT, CURLOPTTYPE_LONG, 90), /* Non-zero value means to use the global dns cache */ /* DEPRECATED, do not use! */ CURLOPT(CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOPTTYPE_LONG, 91), /* DNS cache timeout */ CURLOPT(CURLOPT_DNS_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 92), /* send linked-list of pre-transfer QUOTE commands */ CURLOPT(CURLOPT_PREQUOTE, CURLOPTTYPE_SLISTPOINT, 93), /* set the debug function */ CURLOPT(CURLOPT_DEBUGFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 94), /* set the data for the debug function */ CURLOPT(CURLOPT_DEBUGDATA, CURLOPTTYPE_CBPOINT, 95), /* mark this as start of a cookie session */ CURLOPT(CURLOPT_COOKIESESSION, CURLOPTTYPE_LONG, 96), /* The CApath directory used to validate the peer certificate this option is used only if SSL_VERIFYPEER is true */ CURLOPT(CURLOPT_CAPATH, CURLOPTTYPE_STRINGPOINT, 97), /* Instruct libcurl to use a smaller receive buffer */ CURLOPT(CURLOPT_BUFFERSIZE, CURLOPTTYPE_LONG, 98), /* Instruct libcurl to not use any signal/alarm handlers, even when using timeouts. This option is useful for multi-threaded applications. See libcurl-the-guide for more background information. */ CURLOPT(CURLOPT_NOSIGNAL, CURLOPTTYPE_LONG, 99), /* Provide a CURLShare for mutexing non-ts data */ CURLOPT(CURLOPT_SHARE, CURLOPTTYPE_OBJECTPOINT, 100), /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default), CURLPROXY_HTTPS, CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5. */ CURLOPT(CURLOPT_PROXYTYPE, CURLOPTTYPE_VALUES, 101), /* Set the Accept-Encoding string. Use this to tell a server you would like the response to be compressed. Before 7.21.6, this was known as CURLOPT_ENCODING */ CURLOPT(CURLOPT_ACCEPT_ENCODING, CURLOPTTYPE_STRINGPOINT, 102), /* Set pointer to private data */ CURLOPT(CURLOPT_PRIVATE, CURLOPTTYPE_OBJECTPOINT, 103), /* Set aliases for HTTP 200 in the HTTP Response header */ CURLOPT(CURLOPT_HTTP200ALIASES, CURLOPTTYPE_SLISTPOINT, 104), /* Continue to send authentication (user+password) when following locations, even when hostname changed. This can potentially send off the name and password to whatever host the server decides. */ CURLOPT(CURLOPT_UNRESTRICTED_AUTH, CURLOPTTYPE_LONG, 105), /* Specifically switch on or off the FTP engine's use of the EPRT command ( it also disables the LPRT attempt). By default, those ones will always be attempted before the good old traditional PORT command. */ CURLOPT(CURLOPT_FTP_USE_EPRT, CURLOPTTYPE_LONG, 106), /* Set this to a bitmask value to enable the particular authentications methods you like. Use this in combination with CURLOPT_USERPWD. Note that setting multiple bits may cause extra network round-trips. */ CURLOPT(CURLOPT_HTTPAUTH, CURLOPTTYPE_VALUES, 107), /* Set the ssl context callback function, currently only for OpenSSL or WolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument. The function must match the curl_ssl_ctx_callback prototype. */ CURLOPT(CURLOPT_SSL_CTX_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 108), /* Set the userdata for the ssl context callback function's third argument */ CURLOPT(CURLOPT_SSL_CTX_DATA, CURLOPTTYPE_CBPOINT, 109), /* FTP Option that causes missing dirs to be created on the remote server. In 7.19.4 we introduced the convenience enums for this option using the CURLFTP_CREATE_DIR prefix. */ CURLOPT(CURLOPT_FTP_CREATE_MISSING_DIRS, CURLOPTTYPE_LONG, 110), /* Set this to a bitmask value to enable the particular authentications methods you like. Use this in combination with CURLOPT_PROXYUSERPWD. Note that setting multiple bits may cause extra network round-trips. */ CURLOPT(CURLOPT_PROXYAUTH, CURLOPTTYPE_VALUES, 111), /* FTP option that changes the timeout, in seconds, associated with getting a response. This is different from transfer timeout time and essentially places a demand on the FTP server to acknowledge commands in a timely manner. */ CURLOPT(CURLOPT_FTP_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112), #define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to tell libcurl to use those IP versions only. This only has effect on systems with support for more than one, i.e IPv4 _and_ IPv6. */ CURLOPT(CURLOPT_IPRESOLVE, CURLOPTTYPE_VALUES, 113), /* Set this option to limit the size of a file that will be downloaded from an HTTP or FTP server. Note there is also _LARGE version which adds large file support for platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ CURLOPT(CURLOPT_MAXFILESIZE, CURLOPTTYPE_LONG, 114), /* See the comment for INFILESIZE above, but in short, specifies * the size of the file being uploaded. -1 means unknown. */ CURLOPT(CURLOPT_INFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 115), /* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version * of this; look above for RESUME_FROM. */ CURLOPT(CURLOPT_RESUME_FROM_LARGE, CURLOPTTYPE_OFF_T, 116), /* Sets the maximum size of data that will be downloaded from * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. */ CURLOPT(CURLOPT_MAXFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 117), /* Set this option to the file name of your .netrc file you want libcurl to parse (using the CURLOPT_NETRC option). If not set, libcurl will do a poor attempt to find the user's home directory and check for a .netrc file in there. */ CURLOPT(CURLOPT_NETRC_FILE, CURLOPTTYPE_STRINGPOINT, 118), /* Enable SSL/TLS for FTP, pick one of: CURLUSESSL_TRY - try using SSL, proceed anyway otherwise CURLUSESSL_CONTROL - SSL for the control connection or fail CURLUSESSL_ALL - SSL for all communication or fail */ CURLOPT(CURLOPT_USE_SSL, CURLOPTTYPE_VALUES, 119), /* The _LARGE version of the standard POSTFIELDSIZE option */ CURLOPT(CURLOPT_POSTFIELDSIZE_LARGE, CURLOPTTYPE_OFF_T, 120), /* Enable/disable the TCP Nagle algorithm */ CURLOPT(CURLOPT_TCP_NODELAY, CURLOPTTYPE_LONG, 121), /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ /* 123 OBSOLETE. Gone in 7.16.0 */ /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ /* 127 OBSOLETE. Gone in 7.16.0 */ /* 128 OBSOLETE. Gone in 7.16.0 */ /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option can be used to change libcurl's default action which is to first try "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK response has been received. Available parameters are: CURLFTPAUTH_DEFAULT - let libcurl decide CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL */ CURLOPT(CURLOPT_FTPSSLAUTH, CURLOPTTYPE_VALUES, 129), CURLOPT(CURLOPT_IOCTLFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 130), CURLOPT(CURLOPT_IOCTLDATA, CURLOPTTYPE_CBPOINT, 131), /* 132 OBSOLETE. Gone in 7.16.0 */ /* 133 OBSOLETE. Gone in 7.16.0 */ /* null-terminated string for pass on to the FTP server when asked for "account" info */ CURLOPT(CURLOPT_FTP_ACCOUNT, CURLOPTTYPE_STRINGPOINT, 134), /* feed cookie into cookie engine */ CURLOPT(CURLOPT_COOKIELIST, CURLOPTTYPE_STRINGPOINT, 135), /* ignore Content-Length */ CURLOPT(CURLOPT_IGNORE_CONTENT_LENGTH, CURLOPTTYPE_LONG, 136), /* Set to non-zero to skip the IP address received in a 227 PASV FTP server response. Typically used for FTP-SSL purposes but is not restricted to that. libcurl will then instead use the same IP address it used for the control connection. */ CURLOPT(CURLOPT_FTP_SKIP_PASV_IP, CURLOPTTYPE_LONG, 137), /* Select "file method" to use when doing FTP, see the curl_ftpmethod above. */ CURLOPT(CURLOPT_FTP_FILEMETHOD, CURLOPTTYPE_VALUES, 138), /* Local port number to bind the socket to */ CURLOPT(CURLOPT_LOCALPORT, CURLOPTTYPE_LONG, 139), /* Number of ports to try, including the first one set with LOCALPORT. Thus, setting it to 1 will make no additional attempts but the first. */ CURLOPT(CURLOPT_LOCALPORTRANGE, CURLOPTTYPE_LONG, 140), /* no transfer, set up connection and let application use the socket by extracting it with CURLINFO_LASTSOCKET */ CURLOPT(CURLOPT_CONNECT_ONLY, CURLOPTTYPE_LONG, 141), /* Function that will be called to convert from the network encoding (instead of using the iconv calls in libcurl) */ CURLOPT(CURLOPT_CONV_FROM_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 142), /* Function that will be called to convert to the network encoding (instead of using the iconv calls in libcurl) */ CURLOPT(CURLOPT_CONV_TO_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 143), /* Function that will be called to convert from UTF8 (instead of using the iconv calls in libcurl) Note that this is used only for SSL certificate processing */ CURLOPT(CURLOPT_CONV_FROM_UTF8_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 144), /* if the connection proceeds too quickly then need to slow it down */ /* limit-rate: maximum number of bytes per second to send or receive */ CURLOPT(CURLOPT_MAX_SEND_SPEED_LARGE, CURLOPTTYPE_OFF_T, 145), CURLOPT(CURLOPT_MAX_RECV_SPEED_LARGE, CURLOPTTYPE_OFF_T, 146), /* Pointer to command string to send if USER/PASS fails. */ CURLOPT(CURLOPT_FTP_ALTERNATIVE_TO_USER, CURLOPTTYPE_STRINGPOINT, 147), /* callback function for setting socket options */ CURLOPT(CURLOPT_SOCKOPTFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 148), CURLOPT(CURLOPT_SOCKOPTDATA, CURLOPTTYPE_CBPOINT, 149), /* set to 0 to disable session ID re-use for this transfer, default is enabled (== 1) */ CURLOPT(CURLOPT_SSL_SESSIONID_CACHE, CURLOPTTYPE_LONG, 150), /* allowed SSH authentication methods */ CURLOPT(CURLOPT_SSH_AUTH_TYPES, CURLOPTTYPE_VALUES, 151), /* Used by scp/sftp to do public/private key authentication */ CURLOPT(CURLOPT_SSH_PUBLIC_KEYFILE, CURLOPTTYPE_STRINGPOINT, 152), CURLOPT(CURLOPT_SSH_PRIVATE_KEYFILE, CURLOPTTYPE_STRINGPOINT, 153), /* Send CCC (Clear Command Channel) after authentication */ CURLOPT(CURLOPT_FTP_SSL_CCC, CURLOPTTYPE_LONG, 154), /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */ CURLOPT(CURLOPT_TIMEOUT_MS, CURLOPTTYPE_LONG, 155), CURLOPT(CURLOPT_CONNECTTIMEOUT_MS, CURLOPTTYPE_LONG, 156), /* set to zero to disable the libcurl's decoding and thus pass the raw body data to the application even when it is encoded/compressed */ CURLOPT(CURLOPT_HTTP_TRANSFER_DECODING, CURLOPTTYPE_LONG, 157), CURLOPT(CURLOPT_HTTP_CONTENT_DECODING, CURLOPTTYPE_LONG, 158), /* Permission used when creating new files and directories on the remote server for protocols that support it, SFTP/SCP/FILE */ CURLOPT(CURLOPT_NEW_FILE_PERMS, CURLOPTTYPE_LONG, 159), CURLOPT(CURLOPT_NEW_DIRECTORY_PERMS, CURLOPTTYPE_LONG, 160), /* Set the behavior of POST when redirecting. Values must be set to one of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */ CURLOPT(CURLOPT_POSTREDIR, CURLOPTTYPE_VALUES, 161), /* used by scp/sftp to verify the host's public key */ CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, CURLOPTTYPE_STRINGPOINT, 162), /* Callback function for opening socket (instead of socket(2)). Optionally, callback is able change the address or refuse to connect returning CURL_SOCKET_BAD. The callback should have type curl_opensocket_callback */ CURLOPT(CURLOPT_OPENSOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 163), CURLOPT(CURLOPT_OPENSOCKETDATA, CURLOPTTYPE_CBPOINT, 164), /* POST volatile input fields. */ CURLOPT(CURLOPT_COPYPOSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 165), /* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */ CURLOPT(CURLOPT_PROXY_TRANSFER_MODE, CURLOPTTYPE_LONG, 166), /* Callback function for seeking in the input stream */ CURLOPT(CURLOPT_SEEKFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 167), CURLOPT(CURLOPT_SEEKDATA, CURLOPTTYPE_CBPOINT, 168), /* CRL file */ CURLOPT(CURLOPT_CRLFILE, CURLOPTTYPE_STRINGPOINT, 169), /* Issuer certificate */ CURLOPT(CURLOPT_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 170), /* (IPv6) Address scope */ CURLOPT(CURLOPT_ADDRESS_SCOPE, CURLOPTTYPE_LONG, 171), /* Collect certificate chain info and allow it to get retrievable with CURLINFO_CERTINFO after the transfer is complete. */ CURLOPT(CURLOPT_CERTINFO, CURLOPTTYPE_LONG, 172), /* "name" and "pwd" to use when fetching. */ CURLOPT(CURLOPT_USERNAME, CURLOPTTYPE_STRINGPOINT, 173), CURLOPT(CURLOPT_PASSWORD, CURLOPTTYPE_STRINGPOINT, 174), /* "name" and "pwd" to use with Proxy when fetching. */ CURLOPT(CURLOPT_PROXYUSERNAME, CURLOPTTYPE_STRINGPOINT, 175), CURLOPT(CURLOPT_PROXYPASSWORD, CURLOPTTYPE_STRINGPOINT, 176), /* Comma separated list of hostnames defining no-proxy zones. These should match both hostnames directly, and hostnames within a domain. For example, local.com will match local.com and www.local.com, but NOT notlocal.com or www.notlocal.com. For compatibility with other implementations of this, .local.com will be considered to be the same as local.com. A single * is the only valid wildcard, and effectively disables the use of proxy. */ CURLOPT(CURLOPT_NOPROXY, CURLOPTTYPE_STRINGPOINT, 177), /* block size for TFTP transfers */ CURLOPT(CURLOPT_TFTP_BLKSIZE, CURLOPTTYPE_LONG, 178), /* Socks Service */ /* DEPRECATED, do not use! */ CURLOPT(CURLOPT_SOCKS5_GSSAPI_SERVICE, CURLOPTTYPE_STRINGPOINT, 179), /* Socks Service */ CURLOPT(CURLOPT_SOCKS5_GSSAPI_NEC, CURLOPTTYPE_LONG, 180), /* set the bitmask for the protocols that are allowed to be used for the transfer, which thus helps the app which takes URLs from users or other external inputs and want to restrict what protocol(s) to deal with. Defaults to CURLPROTO_ALL. */ CURLOPT(CURLOPT_PROTOCOLS, CURLOPTTYPE_LONG, 181), /* set the bitmask for the protocols that libcurl is allowed to follow to, as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs to be set in both bitmasks to be allowed to get redirected to. */ CURLOPT(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182), /* set the SSH knownhost file name to use */ CURLOPT(CURLOPT_SSH_KNOWNHOSTS, CURLOPTTYPE_STRINGPOINT, 183), /* set the SSH host key callback, must point to a curl_sshkeycallback function */ CURLOPT(CURLOPT_SSH_KEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 184), /* set the SSH host key callback custom pointer */ CURLOPT(CURLOPT_SSH_KEYDATA, CURLOPTTYPE_CBPOINT, 185), /* set the SMTP mail originator */ CURLOPT(CURLOPT_MAIL_FROM, CURLOPTTYPE_STRINGPOINT, 186), /* set the list of SMTP mail receiver(s) */ CURLOPT(CURLOPT_MAIL_RCPT, CURLOPTTYPE_SLISTPOINT, 187), /* FTP: send PRET before PASV */ CURLOPT(CURLOPT_FTP_USE_PRET, CURLOPTTYPE_LONG, 188), /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */ CURLOPT(CURLOPT_RTSP_REQUEST, CURLOPTTYPE_VALUES, 189), /* The RTSP session identifier */ CURLOPT(CURLOPT_RTSP_SESSION_ID, CURLOPTTYPE_STRINGPOINT, 190), /* The RTSP stream URI */ CURLOPT(CURLOPT_RTSP_STREAM_URI, CURLOPTTYPE_STRINGPOINT, 191), /* The Transport: header to use in RTSP requests */ CURLOPT(CURLOPT_RTSP_TRANSPORT, CURLOPTTYPE_STRINGPOINT, 192), /* Manually initialize the client RTSP CSeq for this handle */ CURLOPT(CURLOPT_RTSP_CLIENT_CSEQ, CURLOPTTYPE_LONG, 193), /* Manually initialize the server RTSP CSeq for this handle */ CURLOPT(CURLOPT_RTSP_SERVER_CSEQ, CURLOPTTYPE_LONG, 194), /* The stream to pass to INTERLEAVEFUNCTION. */ CURLOPT(CURLOPT_INTERLEAVEDATA, CURLOPTTYPE_CBPOINT, 195), /* Let the application define a custom write method for RTP data */ CURLOPT(CURLOPT_INTERLEAVEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 196), /* Turn on wildcard matching */ CURLOPT(CURLOPT_WILDCARDMATCH, CURLOPTTYPE_LONG, 197), /* Directory matching callback called before downloading of an individual file (chunk) started */ CURLOPT(CURLOPT_CHUNK_BGN_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 198), /* Directory matching callback called after the file (chunk) was downloaded, or skipped */ CURLOPT(CURLOPT_CHUNK_END_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 199), /* Change match (fnmatch-like) callback for wildcard matching */ CURLOPT(CURLOPT_FNMATCH_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 200), /* Let the application define custom chunk data pointer */ CURLOPT(CURLOPT_CHUNK_DATA, CURLOPTTYPE_CBPOINT, 201), /* FNMATCH_FUNCTION user pointer */ CURLOPT(CURLOPT_FNMATCH_DATA, CURLOPTTYPE_CBPOINT, 202), /* send linked-list of name:port:address sets */ CURLOPT(CURLOPT_RESOLVE, CURLOPTTYPE_SLISTPOINT, 203), /* Set a username for authenticated TLS */ CURLOPT(CURLOPT_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 204), /* Set a password for authenticated TLS */ CURLOPT(CURLOPT_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 205), /* Set authentication type for authenticated TLS */ CURLOPT(CURLOPT_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 206), /* Set to 1 to enable the "TE:" header in HTTP requests to ask for compressed transfer-encoded responses. Set to 0 to disable the use of TE: in outgoing requests. The current default is 0, but it might change in a future libcurl release. libcurl will ask for the compressed methods it knows of, and if that isn't any, it will not ask for transfer-encoding at all even if this option is set to 1. */ CURLOPT(CURLOPT_TRANSFER_ENCODING, CURLOPTTYPE_LONG, 207), /* Callback function for closing socket (instead of close(2)). The callback should have type curl_closesocket_callback */ CURLOPT(CURLOPT_CLOSESOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 208), CURLOPT(CURLOPT_CLOSESOCKETDATA, CURLOPTTYPE_CBPOINT, 209), /* allow GSSAPI credential delegation */ CURLOPT(CURLOPT_GSSAPI_DELEGATION, CURLOPTTYPE_VALUES, 210), /* Set the name servers to use for DNS resolution */ CURLOPT(CURLOPT_DNS_SERVERS, CURLOPTTYPE_STRINGPOINT, 211), /* Time-out accept operations (currently for FTP only) after this amount of milliseconds. */ CURLOPT(CURLOPT_ACCEPTTIMEOUT_MS, CURLOPTTYPE_LONG, 212), /* Set TCP keepalive */ CURLOPT(CURLOPT_TCP_KEEPALIVE, CURLOPTTYPE_LONG, 213), /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */ CURLOPT(CURLOPT_TCP_KEEPIDLE, CURLOPTTYPE_LONG, 214), CURLOPT(CURLOPT_TCP_KEEPINTVL, CURLOPTTYPE_LONG, 215), /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */ CURLOPT(CURLOPT_SSL_OPTIONS, CURLOPTTYPE_VALUES, 216), /* Set the SMTP auth originator */ CURLOPT(CURLOPT_MAIL_AUTH, CURLOPTTYPE_STRINGPOINT, 217), /* Enable/disable SASL initial response */ CURLOPT(CURLOPT_SASL_IR, CURLOPTTYPE_LONG, 218), /* Function that will be called instead of the internal progress display * function. This function should be defined as the curl_xferinfo_callback * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */ CURLOPT(CURLOPT_XFERINFOFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 219), /* The XOAUTH2 bearer token */ CURLOPT(CURLOPT_XOAUTH2_BEARER, CURLOPTTYPE_STRINGPOINT, 220), /* Set the interface string to use as outgoing network * interface for DNS requests. * Only supported by the c-ares DNS backend */ CURLOPT(CURLOPT_DNS_INTERFACE, CURLOPTTYPE_STRINGPOINT, 221), /* Set the local IPv4 address to use for outgoing DNS requests. * Only supported by the c-ares DNS backend */ CURLOPT(CURLOPT_DNS_LOCAL_IP4, CURLOPTTYPE_STRINGPOINT, 222), /* Set the local IPv6 address to use for outgoing DNS requests. * Only supported by the c-ares DNS backend */ CURLOPT(CURLOPT_DNS_LOCAL_IP6, CURLOPTTYPE_STRINGPOINT, 223), /* Set authentication options directly */ CURLOPT(CURLOPT_LOGIN_OPTIONS, CURLOPTTYPE_STRINGPOINT, 224), /* Enable/disable TLS NPN extension (http2 over ssl might fail without) */ CURLOPT(CURLOPT_SSL_ENABLE_NPN, CURLOPTTYPE_LONG, 225), /* Enable/disable TLS ALPN extension (http2 over ssl might fail without) */ CURLOPT(CURLOPT_SSL_ENABLE_ALPN, CURLOPTTYPE_LONG, 226), /* Time to wait for a response to a HTTP request containing an * Expect: 100-continue header before sending the data anyway. */ CURLOPT(CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPTTYPE_LONG, 227), /* This points to a linked list of headers used for proxy requests only, struct curl_slist kind */ CURLOPT(CURLOPT_PROXYHEADER, CURLOPTTYPE_SLISTPOINT, 228), /* Pass in a bitmask of "header options" */ CURLOPT(CURLOPT_HEADEROPT, CURLOPTTYPE_VALUES, 229), /* The public key in DER form used to validate the peer public key this option is used only if SSL_VERIFYPEER is true */ CURLOPT(CURLOPT_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 230), /* Path to Unix domain socket */ CURLOPT(CURLOPT_UNIX_SOCKET_PATH, CURLOPTTYPE_STRINGPOINT, 231), /* Set if we should verify the certificate status. */ CURLOPT(CURLOPT_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 232), /* Set if we should enable TLS false start. */ CURLOPT(CURLOPT_SSL_FALSESTART, CURLOPTTYPE_LONG, 233), /* Do not squash dot-dot sequences */ CURLOPT(CURLOPT_PATH_AS_IS, CURLOPTTYPE_LONG, 234), /* Proxy Service Name */ CURLOPT(CURLOPT_PROXY_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 235), /* Service Name */ CURLOPT(CURLOPT_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 236), /* Wait/don't wait for pipe/mutex to clarify */ CURLOPT(CURLOPT_PIPEWAIT, CURLOPTTYPE_LONG, 237), /* Set the protocol used when curl is given a URL without a protocol */ CURLOPT(CURLOPT_DEFAULT_PROTOCOL, CURLOPTTYPE_STRINGPOINT, 238), /* Set stream weight, 1 - 256 (default is 16) */ CURLOPT(CURLOPT_STREAM_WEIGHT, CURLOPTTYPE_LONG, 239), /* Set stream dependency on another CURL handle */ CURLOPT(CURLOPT_STREAM_DEPENDS, CURLOPTTYPE_OBJECTPOINT, 240), /* Set E-xclusive stream dependency on another CURL handle */ CURLOPT(CURLOPT_STREAM_DEPENDS_E, CURLOPTTYPE_OBJECTPOINT, 241), /* Do not send any tftp option requests to the server */ CURLOPT(CURLOPT_TFTP_NO_OPTIONS, CURLOPTTYPE_LONG, 242), /* Linked-list of host:port:connect-to-host:connect-to-port, overrides the URL's host:port (only for the network layer) */ CURLOPT(CURLOPT_CONNECT_TO, CURLOPTTYPE_SLISTPOINT, 243), /* Set TCP Fast Open */ CURLOPT(CURLOPT_TCP_FASTOPEN, CURLOPTTYPE_LONG, 244), /* Continue to send data if the server responds early with an * HTTP status code >= 300 */ CURLOPT(CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPTTYPE_LONG, 245), /* The CApath or CAfile used to validate the proxy certificate this option is used only if PROXY_SSL_VERIFYPEER is true */ CURLOPT(CURLOPT_PROXY_CAINFO, CURLOPTTYPE_STRINGPOINT, 246), /* The CApath directory used to validate the proxy certificate this option is used only if PROXY_SSL_VERIFYPEER is true */ CURLOPT(CURLOPT_PROXY_CAPATH, CURLOPTTYPE_STRINGPOINT, 247), /* Set if we should verify the proxy in ssl handshake, set 1 to verify. */ CURLOPT(CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 248), /* Set if we should verify the Common name from the proxy certificate in ssl * handshake, set 1 to check existence, 2 to ensure that it matches * the provided hostname. */ CURLOPT(CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 249), /* What version to specifically try to use for proxy. See CURL_SSLVERSION defines below. */ CURLOPT(CURLOPT_PROXY_SSLVERSION, CURLOPTTYPE_VALUES, 250), /* Set a username for authenticated TLS for proxy */ CURLOPT(CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 251), /* Set a password for authenticated TLS for proxy */ CURLOPT(CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 252), /* Set authentication type for authenticated TLS for proxy */ CURLOPT(CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 253), /* name of the file keeping your private SSL-certificate for proxy */ CURLOPT(CURLOPT_PROXY_SSLCERT, CURLOPTTYPE_STRINGPOINT, 254), /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") for proxy */ CURLOPT(CURLOPT_PROXY_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 255), /* name of the file keeping your private SSL-key for proxy */ CURLOPT(CURLOPT_PROXY_SSLKEY, CURLOPTTYPE_STRINGPOINT, 256), /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") for proxy */ CURLOPT(CURLOPT_PROXY_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 257), /* password for the SSL private key for proxy */ CURLOPT(CURLOPT_PROXY_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 258), /* Specify which SSL ciphers to use for proxy */ CURLOPT(CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 259), /* CRL file for proxy */ CURLOPT(CURLOPT_PROXY_CRLFILE, CURLOPTTYPE_STRINGPOINT, 260), /* Enable/disable specific SSL features with a bitmask for proxy, see CURLSSLOPT_* */ CURLOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLOPTTYPE_LONG, 261), /* Name of pre proxy to use. */ CURLOPT(CURLOPT_PRE_PROXY, CURLOPTTYPE_STRINGPOINT, 262), /* The public key in DER form used to validate the proxy public key this option is used only if PROXY_SSL_VERIFYPEER is true */ CURLOPT(CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 263), /* Path to an abstract Unix domain socket */ CURLOPT(CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPTTYPE_STRINGPOINT, 264), /* Suppress proxy CONNECT response headers from user callbacks */ CURLOPT(CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPTTYPE_LONG, 265), /* The request target, instead of extracted from the URL */ CURLOPT(CURLOPT_REQUEST_TARGET, CURLOPTTYPE_STRINGPOINT, 266), /* bitmask of allowed auth methods for connections to SOCKS5 proxies */ CURLOPT(CURLOPT_SOCKS5_AUTH, CURLOPTTYPE_LONG, 267), /* Enable/disable SSH compression */ CURLOPT(CURLOPT_SSH_COMPRESSION, CURLOPTTYPE_LONG, 268), /* Post MIME data. */ CURLOPT(CURLOPT_MIMEPOST, CURLOPTTYPE_OBJECTPOINT, 269), /* Time to use with the CURLOPT_TIMECONDITION. Specified in number of seconds since 1 Jan 1970. */ CURLOPT(CURLOPT_TIMEVALUE_LARGE, CURLOPTTYPE_OFF_T, 270), /* Head start in milliseconds to give happy eyeballs. */ CURLOPT(CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPTTYPE_LONG, 271), /* Function that will be called before a resolver request is made */ CURLOPT(CURLOPT_RESOLVER_START_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 272), /* User data to pass to the resolver start callback. */ CURLOPT(CURLOPT_RESOLVER_START_DATA, CURLOPTTYPE_CBPOINT, 273), /* send HAProxy PROXY protocol header? */ CURLOPT(CURLOPT_HAPROXYPROTOCOL, CURLOPTTYPE_LONG, 274), /* shuffle addresses before use when DNS returns multiple */ CURLOPT(CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPTTYPE_LONG, 275), /* Specify which TLS 1.3 ciphers suites to use */ CURLOPT(CURLOPT_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 276), CURLOPT(CURLOPT_PROXY_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 277), /* Disallow specifying username/login in URL. */ CURLOPT(CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPTTYPE_LONG, 278), /* DNS-over-HTTPS URL */ CURLOPT(CURLOPT_DOH_URL, CURLOPTTYPE_STRINGPOINT, 279), /* Preferred buffer size to use for uploads */ CURLOPT(CURLOPT_UPLOAD_BUFFERSIZE, CURLOPTTYPE_LONG, 280), /* Time in ms between connection upkeep calls for long-lived connections. */ CURLOPT(CURLOPT_UPKEEP_INTERVAL_MS, CURLOPTTYPE_LONG, 281), /* Specify URL using CURL URL API. */ CURLOPT(CURLOPT_CURLU, CURLOPTTYPE_OBJECTPOINT, 282), /* add trailing data just after no more data is available */ CURLOPT(CURLOPT_TRAILERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 283), /* pointer to be passed to HTTP_TRAILER_FUNCTION */ CURLOPT(CURLOPT_TRAILERDATA, CURLOPTTYPE_CBPOINT, 284), /* set this to 1L to allow HTTP/0.9 responses or 0L to disallow */ CURLOPT(CURLOPT_HTTP09_ALLOWED, CURLOPTTYPE_LONG, 285), /* alt-svc control bitmask */ CURLOPT(CURLOPT_ALTSVC_CTRL, CURLOPTTYPE_LONG, 286), /* alt-svc cache file name to possibly read from/write to */ CURLOPT(CURLOPT_ALTSVC, CURLOPTTYPE_STRINGPOINT, 287), /* maximum age (idle time) of a connection to consider it for reuse * (in seconds) */ CURLOPT(CURLOPT_MAXAGE_CONN, CURLOPTTYPE_LONG, 288), /* SASL authorisation identity */ CURLOPT(CURLOPT_SASL_AUTHZID, CURLOPTTYPE_STRINGPOINT, 289), /* allow RCPT TO command to fail for some recipients */ CURLOPT(CURLOPT_MAIL_RCPT_ALLLOWFAILS, CURLOPTTYPE_LONG, 290), /* the private SSL-certificate as a "blob" */ CURLOPT(CURLOPT_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 291), CURLOPT(CURLOPT_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 292), CURLOPT(CURLOPT_PROXY_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 293), CURLOPT(CURLOPT_PROXY_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 294), CURLOPT(CURLOPT_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 295), /* Issuer certificate for proxy */ CURLOPT(CURLOPT_PROXY_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 296), CURLOPT(CURLOPT_PROXY_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 297), /* the EC curves requested by the TLS client (RFC 8422, 5.1); * OpenSSL support via 'set_groups'/'set_curves': * https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set1_groups.html */ CURLOPT(CURLOPT_SSL_EC_CURVES, CURLOPTTYPE_STRINGPOINT, 298), /* HSTS bitmask */ CURLOPT(CURLOPT_HSTS_CTRL, CURLOPTTYPE_LONG, 299), /* HSTS file name */ CURLOPT(CURLOPT_HSTS, CURLOPTTYPE_STRINGPOINT, 300), /* HSTS read callback */ CURLOPT(CURLOPT_HSTSREADFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 301), CURLOPT(CURLOPT_HSTSREADDATA, CURLOPTTYPE_CBPOINT, 302), /* HSTS write callback */ CURLOPT(CURLOPT_HSTSWRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 303), CURLOPT(CURLOPT_HSTSWRITEDATA, CURLOPTTYPE_CBPOINT, 304), /* Parameters for V4 signature */ CURLOPT(CURLOPT_AWS_SIGV4, CURLOPTTYPE_STRINGPOINT, 305), /* Same as CURLOPT_SSL_VERIFYPEER but for DoH (DNS-over-HTTPS) servers. */ CURLOPT(CURLOPT_DOH_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 306), /* Same as CURLOPT_SSL_VERIFYHOST but for DoH (DNS-over-HTTPS) servers. */ CURLOPT(CURLOPT_DOH_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 307), /* Same as CURLOPT_SSL_VERIFYSTATUS but for DoH (DNS-over-HTTPS) servers. */ CURLOPT(CURLOPT_DOH_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 308), /* The CA certificates as "blob" used to validate the peer certificate this option is used only if SSL_VERIFYPEER is true */ CURLOPT(CURLOPT_CAINFO_BLOB, CURLOPTTYPE_BLOB, 309), /* The CA certificates as "blob" used to validate the proxy certificate this option is used only if PROXY_SSL_VERIFYPEER is true */ CURLOPT(CURLOPT_PROXY_CAINFO_BLOB, CURLOPTTYPE_BLOB, 310), /* used by scp/sftp to verify the host's public key */ CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256, CURLOPTTYPE_STRINGPOINT, 311), /* Function that will be called immediately before the initial request is made on a connection (after any protocol negotiation step). */ CURLOPT(CURLOPT_PREREQFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 312), /* Data passed to the CURLOPT_PREREQFUNCTION callback */ CURLOPT(CURLOPT_PREREQDATA, CURLOPTTYPE_CBPOINT, 313), /* maximum age (since creation) of a connection to consider it for reuse * (in seconds) */ CURLOPT(CURLOPT_MAXLIFETIME_CONN, CURLOPTTYPE_LONG, 314), CURLOPT_LASTENTRY /* the last unused */ } CURLoption; #ifndef CURL_NO_OLDIES /* define this to test if your app builds with all the obsolete stuff removed! */ /* Backwards compatibility with older names */ /* These are scheduled to disappear by 2011 */ /* This was added in version 7.19.1 */ #define CURLOPT_POST301 CURLOPT_POSTREDIR /* These are scheduled to disappear by 2009 */ /* The following were added in 7.17.0 */ #define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD #define CURLOPT_FTPAPPEND CURLOPT_APPEND #define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY #define CURLOPT_FTP_SSL CURLOPT_USE_SSL /* The following were added earlier */ #define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD #define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL #else /* This is set if CURL_NO_OLDIES is defined at compile-time */ #undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ #endif /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host name resolves addresses using more than one IP protocol version, this option might be handy to force libcurl to use a specific IP version. */ #define CURL_IPRESOLVE_WHATEVER 0 /* default, uses addresses to all IP versions that your system allows */ #define CURL_IPRESOLVE_V4 1 /* uses only IPv4 addresses/connections */ #define CURL_IPRESOLVE_V6 2 /* uses only IPv6 addresses/connections */ /* three convenient "aliases" that follow the name scheme better */ #define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER /* These enums are for use with the CURLOPT_HTTP_VERSION option. */ enum { CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd like the library to choose the best possible for us! */ CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ CURL_HTTP_VERSION_2_0, /* please use HTTP 2 in the request */ CURL_HTTP_VERSION_2TLS, /* use version 2 for HTTPS, version 1.1 for HTTP */ CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, /* please use HTTP 2 without HTTP/1.1 Upgrade */ CURL_HTTP_VERSION_3 = 30, /* Makes use of explicit HTTP/3 without fallback. Use CURLOPT_ALTSVC to enable HTTP/3 upgrade */ CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */ }; /* Convenience definition simple because the name of the version is HTTP/2 and not 2.0. The 2_0 version of the enum name was set while the version was still planned to be 2.0 and we stick to it for compatibility. */ #define CURL_HTTP_VERSION_2 CURL_HTTP_VERSION_2_0 /* * Public API enums for RTSP requests */ enum { CURL_RTSPREQ_NONE, /* first in list */ CURL_RTSPREQ_OPTIONS, CURL_RTSPREQ_DESCRIBE, CURL_RTSPREQ_ANNOUNCE, CURL_RTSPREQ_SETUP, CURL_RTSPREQ_PLAY, CURL_RTSPREQ_PAUSE, CURL_RTSPREQ_TEARDOWN, CURL_RTSPREQ_GET_PARAMETER, CURL_RTSPREQ_SET_PARAMETER, CURL_RTSPREQ_RECORD, CURL_RTSPREQ_RECEIVE, CURL_RTSPREQ_LAST /* last in list */ }; /* These enums are for use with the CURLOPT_NETRC option. */ enum CURL_NETRC_OPTION { CURL_NETRC_IGNORED, /* The .netrc will never be read. * This is the default. */ CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred * to one in the .netrc. */ CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored. * Unless one is set programmatically, the .netrc * will be queried. */ CURL_NETRC_LAST }; enum { CURL_SSLVERSION_DEFAULT, CURL_SSLVERSION_TLSv1, /* TLS 1.x */ CURL_SSLVERSION_SSLv2, CURL_SSLVERSION_SSLv3, CURL_SSLVERSION_TLSv1_0, CURL_SSLVERSION_TLSv1_1, CURL_SSLVERSION_TLSv1_2, CURL_SSLVERSION_TLSv1_3, CURL_SSLVERSION_LAST /* never use, keep last */ }; enum { CURL_SSLVERSION_MAX_NONE = 0, CURL_SSLVERSION_MAX_DEFAULT = (CURL_SSLVERSION_TLSv1 << 16), CURL_SSLVERSION_MAX_TLSv1_0 = (CURL_SSLVERSION_TLSv1_0 << 16), CURL_SSLVERSION_MAX_TLSv1_1 = (CURL_SSLVERSION_TLSv1_1 << 16), CURL_SSLVERSION_MAX_TLSv1_2 = (CURL_SSLVERSION_TLSv1_2 << 16), CURL_SSLVERSION_MAX_TLSv1_3 = (CURL_SSLVERSION_TLSv1_3 << 16), /* never use, keep last */ CURL_SSLVERSION_MAX_LAST = (CURL_SSLVERSION_LAST << 16) }; enum CURL_TLSAUTH { CURL_TLSAUTH_NONE, CURL_TLSAUTH_SRP, CURL_TLSAUTH_LAST /* never use, keep last */ }; /* symbols to use with CURLOPT_POSTREDIR. CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303 can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302 | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */ #define CURL_REDIR_GET_ALL 0 #define CURL_REDIR_POST_301 1 #define CURL_REDIR_POST_302 2 #define CURL_REDIR_POST_303 4 #define CURL_REDIR_POST_ALL \ (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303) typedef enum { CURL_TIMECOND_NONE, CURL_TIMECOND_IFMODSINCE, CURL_TIMECOND_IFUNMODSINCE, CURL_TIMECOND_LASTMOD, CURL_TIMECOND_LAST } curl_TimeCond; /* Special size_t value signaling a null-terminated string. */ #define CURL_ZERO_TERMINATED ((size_t) -1) /* curl_strequal() and curl_strnequal() are subject for removal in a future release */ CURL_EXTERN int curl_strequal(const char *s1, const char *s2); CURL_EXTERN int curl_strnequal(const char *s1, const char *s2, size_t n); /* Mime/form handling support. */ typedef struct curl_mime curl_mime; /* Mime context. */ typedef struct curl_mimepart curl_mimepart; /* Mime part context. */ /* * NAME curl_mime_init() * * DESCRIPTION * * Create a mime context and return its handle. The easy parameter is the * target handle. */ CURL_EXTERN curl_mime *curl_mime_init(CURL *easy); /* * NAME curl_mime_free() * * DESCRIPTION * * release a mime handle and its substructures. */ CURL_EXTERN void curl_mime_free(curl_mime *mime); /* * NAME curl_mime_addpart() * * DESCRIPTION * * Append a new empty part to the given mime context and return a handle to * the created part. */ CURL_EXTERN curl_mimepart *curl_mime_addpart(curl_mime *mime); /* * NAME curl_mime_name() * * DESCRIPTION * * Set mime/form part name. */ CURL_EXTERN CURLcode curl_mime_name(curl_mimepart *part, const char *name); /* * NAME curl_mime_filename() * * DESCRIPTION * * Set mime part remote file name. */ CURL_EXTERN CURLcode curl_mime_filename(curl_mimepart *part, const char *filename); /* * NAME curl_mime_type() * * DESCRIPTION * * Set mime part type. */ CURL_EXTERN CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype); /* * NAME curl_mime_encoder() * * DESCRIPTION * * Set mime data transfer encoder. */ CURL_EXTERN CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding); /* * NAME curl_mime_data() * * DESCRIPTION * * Set mime part data source from memory data, */ CURL_EXTERN CURLcode curl_mime_data(curl_mimepart *part, const char *data, size_t datasize); /* * NAME curl_mime_filedata() * * DESCRIPTION * * Set mime part data source from named file. */ CURL_EXTERN CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename); /* * NAME curl_mime_data_cb() * * DESCRIPTION * * Set mime part data source from callback function. */ CURL_EXTERN CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize, curl_read_callback readfunc, curl_seek_callback seekfunc, curl_free_callback freefunc, void *arg); /* * NAME curl_mime_subparts() * * DESCRIPTION * * Set mime part data source from subparts. */ CURL_EXTERN CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts); /* * NAME curl_mime_headers() * * DESCRIPTION * * Set mime part headers. */ CURL_EXTERN CURLcode curl_mime_headers(curl_mimepart *part, struct curl_slist *headers, int take_ownership); typedef enum { CURLFORM_NOTHING, /********* the first one is unused ************/ CURLFORM_COPYNAME, CURLFORM_PTRNAME, CURLFORM_NAMELENGTH, CURLFORM_COPYCONTENTS, CURLFORM_PTRCONTENTS, CURLFORM_CONTENTSLENGTH, CURLFORM_FILECONTENT, CURLFORM_ARRAY, CURLFORM_OBSOLETE, CURLFORM_FILE, CURLFORM_BUFFER, CURLFORM_BUFFERPTR, CURLFORM_BUFFERLENGTH, CURLFORM_CONTENTTYPE, CURLFORM_CONTENTHEADER, CURLFORM_FILENAME, CURLFORM_END, CURLFORM_OBSOLETE2, CURLFORM_STREAM, CURLFORM_CONTENTLEN, /* added in 7.46.0, provide a curl_off_t length */ CURLFORM_LASTENTRY /* the last unused */ } CURLformoption; /* structure to be used as parameter for CURLFORM_ARRAY */ struct curl_forms { CURLformoption option; const char *value; }; /* use this for multipart formpost building */ /* Returns code for curl_formadd() * * Returns: * CURL_FORMADD_OK on success * CURL_FORMADD_MEMORY if the FormInfo allocation fails * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form * CURL_FORMADD_NULL if a null pointer was given for a char * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated * CURL_FORMADD_MEMORY if some allocation for string copying failed. * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array * ***************************************************************************/ typedef enum { CURL_FORMADD_OK, /* first, no error */ CURL_FORMADD_MEMORY, CURL_FORMADD_OPTION_TWICE, CURL_FORMADD_NULL, CURL_FORMADD_UNKNOWN_OPTION, CURL_FORMADD_INCOMPLETE, CURL_FORMADD_ILLEGAL_ARRAY, CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */ CURL_FORMADD_LAST /* last */ } CURLFORMcode; /* * NAME curl_formadd() * * DESCRIPTION * * Pretty advanced function for building multi-part formposts. Each invoke * adds one part that together construct a full post. Then use * CURLOPT_HTTPPOST to send it off to libcurl. */ CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost, struct curl_httppost **last_post, ...); /* * callback function for curl_formget() * The void *arg pointer will be the one passed as second argument to * curl_formget(). * The character buffer passed to it must not be freed. * Should return the buffer length passed to it as the argument "len" on * success. */ typedef size_t (*curl_formget_callback)(void *arg, const char *buf, size_t len); /* * NAME curl_formget() * * DESCRIPTION * * Serialize a curl_httppost struct built with curl_formadd(). * Accepts a void pointer as second argument which will be passed to * the curl_formget_callback function. * Returns 0 on success. */ CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg, curl_formget_callback append); /* * NAME curl_formfree() * * DESCRIPTION * * Free a multipart formpost previously built with curl_formadd(). */ CURL_EXTERN void curl_formfree(struct curl_httppost *form); /* * NAME curl_getenv() * * DESCRIPTION * * Returns a malloc()'ed string that MUST be curl_free()ed after usage is * complete. DEPRECATED - see lib/README.curlx */ CURL_EXTERN char *curl_getenv(const char *variable); /* * NAME curl_version() * * DESCRIPTION * * Returns a static ascii string of the libcurl version. */ CURL_EXTERN char *curl_version(void); /* * NAME curl_easy_escape() * * DESCRIPTION * * Escapes URL strings (converts all letters consider illegal in URLs to their * %XX versions). This function returns a new allocated string or NULL if an * error occurred. */ CURL_EXTERN char *curl_easy_escape(CURL *handle, const char *string, int length); /* the previous version: */ CURL_EXTERN char *curl_escape(const char *string, int length); /* * NAME curl_easy_unescape() * * DESCRIPTION * * Unescapes URL encoding in strings (converts all %XX codes to their 8bit * versions). This function returns a new allocated string or NULL if an error * occurred. * Conversion Note: On non-ASCII platforms the ASCII %XX codes are * converted into the host encoding. */ CURL_EXTERN char *curl_easy_unescape(CURL *handle, const char *string, int length, int *outlength); /* the previous version */ CURL_EXTERN char *curl_unescape(const char *string, int length); /* * NAME curl_free() * * DESCRIPTION * * Provided for de-allocation in the same translation unit that did the * allocation. Added in libcurl 7.10 */ CURL_EXTERN void curl_free(void *p); /* * NAME curl_global_init() * * DESCRIPTION * * curl_global_init() should be invoked exactly once for each application that * uses libcurl and before any call of other libcurl functions. * * This function is not thread-safe! */ CURL_EXTERN CURLcode curl_global_init(long flags); /* * NAME curl_global_init_mem() * * DESCRIPTION * * curl_global_init() or curl_global_init_mem() should be invoked exactly once * for each application that uses libcurl. This function can be used to * initialize libcurl and set user defined memory management callback * functions. Users can implement memory management routines to check for * memory leaks, check for mis-use of the curl library etc. User registered * callback routines will be invoked by this library instead of the system * memory management routines like malloc, free etc. */ CURL_EXTERN CURLcode curl_global_init_mem(long flags, curl_malloc_callback m, curl_free_callback f, curl_realloc_callback r, curl_strdup_callback s, curl_calloc_callback c); /* * NAME curl_global_cleanup() * * DESCRIPTION * * curl_global_cleanup() should be invoked exactly once for each application * that uses libcurl */ CURL_EXTERN void curl_global_cleanup(void); /* linked-list structure for the CURLOPT_QUOTE option (and other) */ struct curl_slist { char *data; struct curl_slist *next; }; /* * NAME curl_global_sslset() * * DESCRIPTION * * When built with multiple SSL backends, curl_global_sslset() allows to * choose one. This function can only be called once, and it must be called * *before* curl_global_init(). * * The backend can be identified by the id (e.g. CURLSSLBACKEND_OPENSSL). The * backend can also be specified via the name parameter (passing -1 as id). * If both id and name are specified, the name will be ignored. If neither id * nor name are specified, the function will fail with * CURLSSLSET_UNKNOWN_BACKEND and set the "avail" pointer to the * NULL-terminated list of available backends. * * Upon success, the function returns CURLSSLSET_OK. * * If the specified SSL backend is not available, the function returns * CURLSSLSET_UNKNOWN_BACKEND and sets the "avail" pointer to a NULL-terminated * list of available SSL backends. * * The SSL backend can be set only once. If it has already been set, a * subsequent attempt to change it will result in a CURLSSLSET_TOO_LATE. */ struct curl_ssl_backend { curl_sslbackend id; const char *name; }; typedef struct curl_ssl_backend curl_ssl_backend; typedef enum { CURLSSLSET_OK = 0, CURLSSLSET_UNKNOWN_BACKEND, CURLSSLSET_TOO_LATE, CURLSSLSET_NO_BACKENDS /* libcurl was built without any SSL support */ } CURLsslset; CURL_EXTERN CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, const curl_ssl_backend ***avail); /* * NAME curl_slist_append() * * DESCRIPTION * * Appends a string to a linked list. If no list exists, it will be created * first. Returns the new list, after appending. */ CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *, const char *); /* * NAME curl_slist_free_all() * * DESCRIPTION * * free a previously built curl_slist. */ CURL_EXTERN void curl_slist_free_all(struct curl_slist *); /* * NAME curl_getdate() * * DESCRIPTION * * Returns the time, in seconds since 1 Jan 1970 of the time string given in * the first argument. The time argument in the second parameter is unused * and should be set to NULL. */ CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); /* info about the certificate chain, only for OpenSSL, GnuTLS, Schannel, NSS and GSKit builds. Asked for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ struct curl_certinfo { int num_of_certs; /* number of certificates with information */ struct curl_slist **certinfo; /* for each index in this array, there's a linked list with textual information in the format "name: value" */ }; /* Information about the SSL library used and the respective internal SSL handle, which can be used to obtain further information regarding the connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */ struct curl_tlssessioninfo { curl_sslbackend backend; void *internals; }; #define CURLINFO_STRING 0x100000 #define CURLINFO_LONG 0x200000 #define CURLINFO_DOUBLE 0x300000 #define CURLINFO_SLIST 0x400000 #define CURLINFO_PTR 0x400000 /* same as SLIST */ #define CURLINFO_SOCKET 0x500000 #define CURLINFO_OFF_T 0x600000 #define CURLINFO_MASK 0x0fffff #define CURLINFO_TYPEMASK 0xf00000 typedef enum { CURLINFO_NONE, /* first, never use this */ CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1, CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2, CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3, CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4, CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5, CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6, CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7, CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7, CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8, CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8, CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9, CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9, CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10, CURLINFO_SPEED_UPLOAD_T = CURLINFO_OFF_T + 10, CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11, CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12, CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13, CURLINFO_FILETIME = CURLINFO_LONG + 14, CURLINFO_FILETIME_T = CURLINFO_OFF_T + 14, CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15, CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16, CURLINFO_CONTENT_LENGTH_UPLOAD_T = CURLINFO_OFF_T + 16, CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17, CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18, CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19, CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20, CURLINFO_PRIVATE = CURLINFO_STRING + 21, CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22, CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23, CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24, CURLINFO_OS_ERRNO = CURLINFO_LONG + 25, CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26, CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27, CURLINFO_COOKIELIST = CURLINFO_SLIST + 28, CURLINFO_LASTSOCKET = CURLINFO_LONG + 29, CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30, CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31, CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32, CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33, CURLINFO_CERTINFO = CURLINFO_PTR + 34, CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35, CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36, CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37, CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38, CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39, CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40, CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, CURLINFO_TLS_SESSION = CURLINFO_PTR + 43, CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44, CURLINFO_TLS_SSL_PTR = CURLINFO_PTR + 45, CURLINFO_HTTP_VERSION = CURLINFO_LONG + 46, CURLINFO_PROXY_SSL_VERIFYRESULT = CURLINFO_LONG + 47, CURLINFO_PROTOCOL = CURLINFO_LONG + 48, CURLINFO_SCHEME = CURLINFO_STRING + 49, CURLINFO_TOTAL_TIME_T = CURLINFO_OFF_T + 50, CURLINFO_NAMELOOKUP_TIME_T = CURLINFO_OFF_T + 51, CURLINFO_CONNECT_TIME_T = CURLINFO_OFF_T + 52, CURLINFO_PRETRANSFER_TIME_T = CURLINFO_OFF_T + 53, CURLINFO_STARTTRANSFER_TIME_T = CURLINFO_OFF_T + 54, CURLINFO_REDIRECT_TIME_T = CURLINFO_OFF_T + 55, CURLINFO_APPCONNECT_TIME_T = CURLINFO_OFF_T + 56, CURLINFO_RETRY_AFTER = CURLINFO_OFF_T + 57, CURLINFO_EFFECTIVE_METHOD = CURLINFO_STRING + 58, CURLINFO_PROXY_ERROR = CURLINFO_LONG + 59, CURLINFO_REFERER = CURLINFO_STRING + 60, CURLINFO_LASTONE = 60 } CURLINFO; /* CURLINFO_RESPONSE_CODE is the new name for the option previously known as CURLINFO_HTTP_CODE */ #define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE typedef enum { CURLCLOSEPOLICY_NONE, /* first, never use this */ CURLCLOSEPOLICY_OLDEST, CURLCLOSEPOLICY_LEAST_RECENTLY_USED, CURLCLOSEPOLICY_LEAST_TRAFFIC, CURLCLOSEPOLICY_SLOWEST, CURLCLOSEPOLICY_CALLBACK, CURLCLOSEPOLICY_LAST /* last, never use this */ } curl_closepolicy; #define CURL_GLOBAL_SSL (1<<0) /* no purpose since since 7.57.0 */ #define CURL_GLOBAL_WIN32 (1<<1) #define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) #define CURL_GLOBAL_NOTHING 0 #define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL #define CURL_GLOBAL_ACK_EINTR (1<<2) /***************************************************************************** * Setup defines, protos etc for the sharing stuff. */ /* Different data locks for a single share */ typedef enum { CURL_LOCK_DATA_NONE = 0, /* CURL_LOCK_DATA_SHARE is used internally to say that * the locking is just made to change the internal state of the share * itself. */ CURL_LOCK_DATA_SHARE, CURL_LOCK_DATA_COOKIE, CURL_LOCK_DATA_DNS, CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_DATA_CONNECT, CURL_LOCK_DATA_PSL, CURL_LOCK_DATA_LAST } curl_lock_data; /* Different lock access types */ typedef enum { CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ CURL_LOCK_ACCESS_LAST /* never use */ } curl_lock_access; typedef void (*curl_lock_function)(CURL *handle, curl_lock_data data, curl_lock_access locktype, void *userptr); typedef void (*curl_unlock_function)(CURL *handle, curl_lock_data data, void *userptr); typedef enum { CURLSHE_OK, /* all is fine */ CURLSHE_BAD_OPTION, /* 1 */ CURLSHE_IN_USE, /* 2 */ CURLSHE_INVALID, /* 3 */ CURLSHE_NOMEM, /* 4 out of memory */ CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */ CURLSHE_LAST /* never use */ } CURLSHcode; typedef enum { CURLSHOPT_NONE, /* don't use */ CURLSHOPT_SHARE, /* specify a data type to share */ CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */ CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock callback functions */ CURLSHOPT_LAST /* never use */ } CURLSHoption; CURL_EXTERN CURLSH *curl_share_init(void); CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...); CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *); /**************************************************************************** * Structures for querying information about the curl library at runtime. */ typedef enum { CURLVERSION_FIRST, CURLVERSION_SECOND, CURLVERSION_THIRD, CURLVERSION_FOURTH, CURLVERSION_FIFTH, CURLVERSION_SIXTH, CURLVERSION_SEVENTH, CURLVERSION_EIGHTH, CURLVERSION_NINTH, CURLVERSION_TENTH, CURLVERSION_LAST /* never actually use this */ } CURLversion; /* The 'CURLVERSION_NOW' is the symbolic name meant to be used by basically all programs ever that want to get version information. It is meant to be a built-in version number for what kind of struct the caller expects. If the struct ever changes, we redefine the NOW to another enum from above. */ #define CURLVERSION_NOW CURLVERSION_TENTH struct curl_version_info_data { CURLversion age; /* age of the returned struct */ const char *version; /* LIBCURL_VERSION */ unsigned int version_num; /* LIBCURL_VERSION_NUM */ const char *host; /* OS/host/cpu/machine when configured */ int features; /* bitmask, see defines below */ const char *ssl_version; /* human readable string */ long ssl_version_num; /* not used anymore, always 0 */ const char *libz_version; /* human readable string */ /* protocols is terminated by an entry with a NULL protoname */ const char * const *protocols; /* The fields below this were added in CURLVERSION_SECOND */ const char *ares; int ares_num; /* This field was added in CURLVERSION_THIRD */ const char *libidn; /* These field were added in CURLVERSION_FOURTH */ /* Same as '_libiconv_version' if built with HAVE_ICONV */ int iconv_ver_num; const char *libssh_version; /* human readable string */ /* These fields were added in CURLVERSION_FIFTH */ unsigned int brotli_ver_num; /* Numeric Brotli version (MAJOR << 24) | (MINOR << 12) | PATCH */ const char *brotli_version; /* human readable string. */ /* These fields were added in CURLVERSION_SIXTH */ unsigned int nghttp2_ver_num; /* Numeric nghttp2 version (MAJOR << 16) | (MINOR << 8) | PATCH */ const char *nghttp2_version; /* human readable string. */ const char *quic_version; /* human readable quic (+ HTTP/3) library + version or NULL */ /* These fields were added in CURLVERSION_SEVENTH */ const char *cainfo; /* the built-in default CURLOPT_CAINFO, might be NULL */ const char *capath; /* the built-in default CURLOPT_CAPATH, might be NULL */ /* These fields were added in CURLVERSION_EIGHTH */ unsigned int zstd_ver_num; /* Numeric Zstd version (MAJOR << 24) | (MINOR << 12) | PATCH */ const char *zstd_version; /* human readable string. */ /* These fields were added in CURLVERSION_NINTH */ const char *hyper_version; /* human readable string. */ /* These fields were added in CURLVERSION_TENTH */ const char *gsasl_version; /* human readable string. */ }; typedef struct curl_version_info_data curl_version_info_data; #define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */ #define CURL_VERSION_KERBEROS4 (1<<1) /* Kerberos V4 auth is supported (deprecated) */ #define CURL_VERSION_SSL (1<<2) /* SSL options are present */ #define CURL_VERSION_LIBZ (1<<3) /* libz features are present */ #define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */ #define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth is supported (deprecated) */ #define CURL_VERSION_DEBUG (1<<6) /* Built with debug capabilities */ #define CURL_VERSION_ASYNCHDNS (1<<7) /* Asynchronous DNS resolves */ #define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth is supported */ #define CURL_VERSION_LARGEFILE (1<<9) /* Supports files larger than 2GB */ #define CURL_VERSION_IDN (1<<10) /* Internationized Domain Names are supported */ #define CURL_VERSION_SSPI (1<<11) /* Built against Windows SSPI */ #define CURL_VERSION_CONV (1<<12) /* Character conversions supported */ #define CURL_VERSION_CURLDEBUG (1<<13) /* Debug memory tracking supported */ #define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */ #define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegation to winbind helper is supported */ #define CURL_VERSION_HTTP2 (1<<16) /* HTTP2 support built-in */ #define CURL_VERSION_GSSAPI (1<<17) /* Built against a GSS-API library */ #define CURL_VERSION_KERBEROS5 (1<<18) /* Kerberos V5 auth is supported */ #define CURL_VERSION_UNIX_SOCKETS (1<<19) /* Unix domain sockets support */ #define CURL_VERSION_PSL (1<<20) /* Mozilla's Public Suffix List, used for cookie domain verification */ #define CURL_VERSION_HTTPS_PROXY (1<<21) /* HTTPS-proxy support built-in */ #define CURL_VERSION_MULTI_SSL (1<<22) /* Multiple SSL backends available */ #define CURL_VERSION_BROTLI (1<<23) /* Brotli features are present. */ #define CURL_VERSION_ALTSVC (1<<24) /* Alt-Svc handling built-in */ #define CURL_VERSION_HTTP3 (1<<25) /* HTTP3 support built-in */ #define CURL_VERSION_ZSTD (1<<26) /* zstd features are present */ #define CURL_VERSION_UNICODE (1<<27) /* Unicode support on Windows */ #define CURL_VERSION_HSTS (1<<28) /* HSTS is supported */ #define CURL_VERSION_GSASL (1<<29) /* libgsasl is supported */ /* * NAME curl_version_info() * * DESCRIPTION * * This function returns a pointer to a static copy of the version info * struct. See above. */ CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion); /* * NAME curl_easy_strerror() * * DESCRIPTION * * The curl_easy_strerror function may be used to turn a CURLcode value * into the equivalent human readable error string. This is useful * for printing meaningful error messages. */ CURL_EXTERN const char *curl_easy_strerror(CURLcode); /* * NAME curl_share_strerror() * * DESCRIPTION * * The curl_share_strerror function may be used to turn a CURLSHcode value * into the equivalent human readable error string. This is useful * for printing meaningful error messages. */ CURL_EXTERN const char *curl_share_strerror(CURLSHcode); /* * NAME curl_easy_pause() * * DESCRIPTION * * The curl_easy_pause function pauses or unpauses transfers. Select the new * state by setting the bitmask, use the convenience defines below. * */ CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask); #define CURLPAUSE_RECV (1<<0) #define CURLPAUSE_RECV_CONT (0) #define CURLPAUSE_SEND (1<<2) #define CURLPAUSE_SEND_CONT (0) #define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND) #define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT) #ifdef __cplusplus } #endif /* unfortunately, the easy.h and multi.h include files need options and info stuff before they can be included! */ #include "easy.h" /* nothing in curl is fun without the easy stuff */ #include "multi.h" #include "urlapi.h" #include "options.h" /* the typechecker doesn't work in C++ (yet) */ #if defined(__GNUC__) && defined(__GNUC_MINOR__) && \ ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \ !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) #include "typecheck-gcc.h" #else #if defined(__STDC__) && (__STDC__ >= 1) /* This preprocessor magic that replaces a call with the exact same call is only done to make sure application authors pass exactly three arguments to these functions. */ #define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param) #define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg) #define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) #define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) #endif /* __STDC__ >= 1 */ #endif /* gcc >= 4.3 && !__cplusplus */ #endif /* CURLINC_CURL_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/typecheck-gcc.h
#ifndef CURLINC_TYPECHECK_GCC_H #define CURLINC_TYPECHECK_GCC_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* wraps curl_easy_setopt() with typechecking */ /* To add a new kind of warning, add an * if(curlcheck_sometype_option(_curl_opt)) * if(!curlcheck_sometype(value)) * _curl_easy_setopt_err_sometype(); * block and define curlcheck_sometype_option, curlcheck_sometype and * _curl_easy_setopt_err_sometype below * * NOTE: We use two nested 'if' statements here instead of the && operator, in * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x * when compiling with -Wlogical-op. * * To add an option that uses the same type as an existing option, you'll just * need to extend the appropriate _curl_*_option macro */ #define curl_easy_setopt(handle, option, value) \ __extension__({ \ __typeof__(option) _curl_opt = option; \ if(__builtin_constant_p(_curl_opt)) { \ if(curlcheck_long_option(_curl_opt)) \ if(!curlcheck_long(value)) \ _curl_easy_setopt_err_long(); \ if(curlcheck_off_t_option(_curl_opt)) \ if(!curlcheck_off_t(value)) \ _curl_easy_setopt_err_curl_off_t(); \ if(curlcheck_string_option(_curl_opt)) \ if(!curlcheck_string(value)) \ _curl_easy_setopt_err_string(); \ if(curlcheck_write_cb_option(_curl_opt)) \ if(!curlcheck_write_cb(value)) \ _curl_easy_setopt_err_write_callback(); \ if((_curl_opt) == CURLOPT_RESOLVER_START_FUNCTION) \ if(!curlcheck_resolver_start_callback(value)) \ _curl_easy_setopt_err_resolver_start_callback(); \ if((_curl_opt) == CURLOPT_READFUNCTION) \ if(!curlcheck_read_cb(value)) \ _curl_easy_setopt_err_read_cb(); \ if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \ if(!curlcheck_ioctl_cb(value)) \ _curl_easy_setopt_err_ioctl_cb(); \ if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \ if(!curlcheck_sockopt_cb(value)) \ _curl_easy_setopt_err_sockopt_cb(); \ if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \ if(!curlcheck_opensocket_cb(value)) \ _curl_easy_setopt_err_opensocket_cb(); \ if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \ if(!curlcheck_progress_cb(value)) \ _curl_easy_setopt_err_progress_cb(); \ if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \ if(!curlcheck_debug_cb(value)) \ _curl_easy_setopt_err_debug_cb(); \ if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \ if(!curlcheck_ssl_ctx_cb(value)) \ _curl_easy_setopt_err_ssl_ctx_cb(); \ if(curlcheck_conv_cb_option(_curl_opt)) \ if(!curlcheck_conv_cb(value)) \ _curl_easy_setopt_err_conv_cb(); \ if((_curl_opt) == CURLOPT_SEEKFUNCTION) \ if(!curlcheck_seek_cb(value)) \ _curl_easy_setopt_err_seek_cb(); \ if(curlcheck_cb_data_option(_curl_opt)) \ if(!curlcheck_cb_data(value)) \ _curl_easy_setopt_err_cb_data(); \ if((_curl_opt) == CURLOPT_ERRORBUFFER) \ if(!curlcheck_error_buffer(value)) \ _curl_easy_setopt_err_error_buffer(); \ if((_curl_opt) == CURLOPT_STDERR) \ if(!curlcheck_FILE(value)) \ _curl_easy_setopt_err_FILE(); \ if(curlcheck_postfields_option(_curl_opt)) \ if(!curlcheck_postfields(value)) \ _curl_easy_setopt_err_postfields(); \ if((_curl_opt) == CURLOPT_HTTPPOST) \ if(!curlcheck_arr((value), struct curl_httppost)) \ _curl_easy_setopt_err_curl_httpost(); \ if((_curl_opt) == CURLOPT_MIMEPOST) \ if(!curlcheck_ptr((value), curl_mime)) \ _curl_easy_setopt_err_curl_mimepost(); \ if(curlcheck_slist_option(_curl_opt)) \ if(!curlcheck_arr((value), struct curl_slist)) \ _curl_easy_setopt_err_curl_slist(); \ if((_curl_opt) == CURLOPT_SHARE) \ if(!curlcheck_ptr((value), CURLSH)) \ _curl_easy_setopt_err_CURLSH(); \ } \ curl_easy_setopt(handle, _curl_opt, value); \ }) /* wraps curl_easy_getinfo() with typechecking */ #define curl_easy_getinfo(handle, info, arg) \ __extension__({ \ __typeof__(info) _curl_info = info; \ if(__builtin_constant_p(_curl_info)) { \ if(curlcheck_string_info(_curl_info)) \ if(!curlcheck_arr((arg), char *)) \ _curl_easy_getinfo_err_string(); \ if(curlcheck_long_info(_curl_info)) \ if(!curlcheck_arr((arg), long)) \ _curl_easy_getinfo_err_long(); \ if(curlcheck_double_info(_curl_info)) \ if(!curlcheck_arr((arg), double)) \ _curl_easy_getinfo_err_double(); \ if(curlcheck_slist_info(_curl_info)) \ if(!curlcheck_arr((arg), struct curl_slist *)) \ _curl_easy_getinfo_err_curl_slist(); \ if(curlcheck_tlssessioninfo_info(_curl_info)) \ if(!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \ _curl_easy_getinfo_err_curl_tlssesssioninfo(); \ if(curlcheck_certinfo_info(_curl_info)) \ if(!curlcheck_arr((arg), struct curl_certinfo *)) \ _curl_easy_getinfo_err_curl_certinfo(); \ if(curlcheck_socket_info(_curl_info)) \ if(!curlcheck_arr((arg), curl_socket_t)) \ _curl_easy_getinfo_err_curl_socket(); \ if(curlcheck_off_t_info(_curl_info)) \ if(!curlcheck_arr((arg), curl_off_t)) \ _curl_easy_getinfo_err_curl_off_t(); \ } \ curl_easy_getinfo(handle, _curl_info, arg); \ }) /* * For now, just make sure that the functions are called with three arguments */ #define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) #define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) /* the actual warnings, triggered by calling the _curl_easy_setopt_err* * functions */ /* To define a new warning, use _CURL_WARNING(identifier, "message") */ #define CURLWARNING(id, message) \ static void __attribute__((__warning__(message))) \ __attribute__((__unused__)) __attribute__((__noinline__)) \ id(void) { __asm__(""); } CURLWARNING(_curl_easy_setopt_err_long, "curl_easy_setopt expects a long argument for this option") CURLWARNING(_curl_easy_setopt_err_curl_off_t, "curl_easy_setopt expects a curl_off_t argument for this option") CURLWARNING(_curl_easy_setopt_err_string, "curl_easy_setopt expects a " "string ('char *' or char[]) argument for this option" ) CURLWARNING(_curl_easy_setopt_err_write_callback, "curl_easy_setopt expects a curl_write_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_resolver_start_callback, "curl_easy_setopt expects a " "curl_resolver_start_callback argument for this option" ) CURLWARNING(_curl_easy_setopt_err_read_cb, "curl_easy_setopt expects a curl_read_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_ioctl_cb, "curl_easy_setopt expects a curl_ioctl_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_sockopt_cb, "curl_easy_setopt expects a curl_sockopt_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_opensocket_cb, "curl_easy_setopt expects a " "curl_opensocket_callback argument for this option" ) CURLWARNING(_curl_easy_setopt_err_progress_cb, "curl_easy_setopt expects a curl_progress_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_debug_cb, "curl_easy_setopt expects a curl_debug_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_ssl_ctx_cb, "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_conv_cb, "curl_easy_setopt expects a curl_conv_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_seek_cb, "curl_easy_setopt expects a curl_seek_callback argument for this option") CURLWARNING(_curl_easy_setopt_err_cb_data, "curl_easy_setopt expects a " "private data pointer as argument for this option") CURLWARNING(_curl_easy_setopt_err_error_buffer, "curl_easy_setopt expects a " "char buffer of CURL_ERROR_SIZE as argument for this option") CURLWARNING(_curl_easy_setopt_err_FILE, "curl_easy_setopt expects a 'FILE *' argument for this option") CURLWARNING(_curl_easy_setopt_err_postfields, "curl_easy_setopt expects a 'void *' or 'char *' argument for this option") CURLWARNING(_curl_easy_setopt_err_curl_httpost, "curl_easy_setopt expects a 'struct curl_httppost *' " "argument for this option") CURLWARNING(_curl_easy_setopt_err_curl_mimepost, "curl_easy_setopt expects a 'curl_mime *' " "argument for this option") CURLWARNING(_curl_easy_setopt_err_curl_slist, "curl_easy_setopt expects a 'struct curl_slist *' argument for this option") CURLWARNING(_curl_easy_setopt_err_CURLSH, "curl_easy_setopt expects a CURLSH* argument for this option") CURLWARNING(_curl_easy_getinfo_err_string, "curl_easy_getinfo expects a pointer to 'char *' for this info") CURLWARNING(_curl_easy_getinfo_err_long, "curl_easy_getinfo expects a pointer to long for this info") CURLWARNING(_curl_easy_getinfo_err_double, "curl_easy_getinfo expects a pointer to double for this info") CURLWARNING(_curl_easy_getinfo_err_curl_slist, "curl_easy_getinfo expects a pointer to 'struct curl_slist *' for this info") CURLWARNING(_curl_easy_getinfo_err_curl_tlssesssioninfo, "curl_easy_getinfo expects a pointer to " "'struct curl_tlssessioninfo *' for this info") CURLWARNING(_curl_easy_getinfo_err_curl_certinfo, "curl_easy_getinfo expects a pointer to " "'struct curl_certinfo *' for this info") CURLWARNING(_curl_easy_getinfo_err_curl_socket, "curl_easy_getinfo expects a pointer to curl_socket_t for this info") CURLWARNING(_curl_easy_getinfo_err_curl_off_t, "curl_easy_getinfo expects a pointer to curl_off_t for this info") /* groups of curl_easy_setops options that take the same type of argument */ /* To add a new option to one of the groups, just add * (option) == CURLOPT_SOMETHING * to the or-expression. If the option takes a long or curl_off_t, you don't * have to do anything */ /* evaluates to true if option takes a long argument */ #define curlcheck_long_option(option) \ (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT) #define curlcheck_off_t_option(option) \ (((option) > CURLOPTTYPE_OFF_T) && ((option) < CURLOPTTYPE_BLOB)) /* evaluates to true if option takes a char* argument */ #define curlcheck_string_option(option) \ ((option) == CURLOPT_ABSTRACT_UNIX_SOCKET || \ (option) == CURLOPT_ACCEPT_ENCODING || \ (option) == CURLOPT_ALTSVC || \ (option) == CURLOPT_CAINFO || \ (option) == CURLOPT_CAPATH || \ (option) == CURLOPT_COOKIE || \ (option) == CURLOPT_COOKIEFILE || \ (option) == CURLOPT_COOKIEJAR || \ (option) == CURLOPT_COOKIELIST || \ (option) == CURLOPT_CRLFILE || \ (option) == CURLOPT_CUSTOMREQUEST || \ (option) == CURLOPT_DEFAULT_PROTOCOL || \ (option) == CURLOPT_DNS_INTERFACE || \ (option) == CURLOPT_DNS_LOCAL_IP4 || \ (option) == CURLOPT_DNS_LOCAL_IP6 || \ (option) == CURLOPT_DNS_SERVERS || \ (option) == CURLOPT_DOH_URL || \ (option) == CURLOPT_EGDSOCKET || \ (option) == CURLOPT_FTPPORT || \ (option) == CURLOPT_FTP_ACCOUNT || \ (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ (option) == CURLOPT_HSTS || \ (option) == CURLOPT_INTERFACE || \ (option) == CURLOPT_ISSUERCERT || \ (option) == CURLOPT_KEYPASSWD || \ (option) == CURLOPT_KRBLEVEL || \ (option) == CURLOPT_LOGIN_OPTIONS || \ (option) == CURLOPT_MAIL_AUTH || \ (option) == CURLOPT_MAIL_FROM || \ (option) == CURLOPT_NETRC_FILE || \ (option) == CURLOPT_NOPROXY || \ (option) == CURLOPT_PASSWORD || \ (option) == CURLOPT_PINNEDPUBLICKEY || \ (option) == CURLOPT_PRE_PROXY || \ (option) == CURLOPT_PROXY || \ (option) == CURLOPT_PROXYPASSWORD || \ (option) == CURLOPT_PROXYUSERNAME || \ (option) == CURLOPT_PROXYUSERPWD || \ (option) == CURLOPT_PROXY_CAINFO || \ (option) == CURLOPT_PROXY_CAPATH || \ (option) == CURLOPT_PROXY_CRLFILE || \ (option) == CURLOPT_PROXY_ISSUERCERT || \ (option) == CURLOPT_PROXY_KEYPASSWD || \ (option) == CURLOPT_PROXY_PINNEDPUBLICKEY || \ (option) == CURLOPT_PROXY_SERVICE_NAME || \ (option) == CURLOPT_PROXY_SSLCERT || \ (option) == CURLOPT_PROXY_SSLCERTTYPE || \ (option) == CURLOPT_PROXY_SSLKEY || \ (option) == CURLOPT_PROXY_SSLKEYTYPE || \ (option) == CURLOPT_PROXY_SSL_CIPHER_LIST || \ (option) == CURLOPT_PROXY_TLS13_CIPHERS || \ (option) == CURLOPT_PROXY_TLSAUTH_PASSWORD || \ (option) == CURLOPT_PROXY_TLSAUTH_TYPE || \ (option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \ (option) == CURLOPT_RANDOM_FILE || \ (option) == CURLOPT_RANGE || \ (option) == CURLOPT_REFERER || \ (option) == CURLOPT_REQUEST_TARGET || \ (option) == CURLOPT_RTSP_SESSION_ID || \ (option) == CURLOPT_RTSP_STREAM_URI || \ (option) == CURLOPT_RTSP_TRANSPORT || \ (option) == CURLOPT_SASL_AUTHZID || \ (option) == CURLOPT_SERVICE_NAME || \ (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 || \ (option) == CURLOPT_SSH_KNOWNHOSTS || \ (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ (option) == CURLOPT_SSLCERT || \ (option) == CURLOPT_SSLCERTTYPE || \ (option) == CURLOPT_SSLENGINE || \ (option) == CURLOPT_SSLKEY || \ (option) == CURLOPT_SSLKEYTYPE || \ (option) == CURLOPT_SSL_CIPHER_LIST || \ (option) == CURLOPT_TLS13_CIPHERS || \ (option) == CURLOPT_TLSAUTH_PASSWORD || \ (option) == CURLOPT_TLSAUTH_TYPE || \ (option) == CURLOPT_TLSAUTH_USERNAME || \ (option) == CURLOPT_UNIX_SOCKET_PATH || \ (option) == CURLOPT_URL || \ (option) == CURLOPT_USERAGENT || \ (option) == CURLOPT_USERNAME || \ (option) == CURLOPT_AWS_SIGV4 || \ (option) == CURLOPT_USERPWD || \ (option) == CURLOPT_XOAUTH2_BEARER || \ (option) == CURLOPT_SSL_EC_CURVES || \ 0) /* evaluates to true if option takes a curl_write_callback argument */ #define curlcheck_write_cb_option(option) \ ((option) == CURLOPT_HEADERFUNCTION || \ (option) == CURLOPT_WRITEFUNCTION) /* evaluates to true if option takes a curl_conv_callback argument */ #define curlcheck_conv_cb_option(option) \ ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \ (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \ (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION) /* evaluates to true if option takes a data argument to pass to a callback */ #define curlcheck_cb_data_option(option) \ ((option) == CURLOPT_CHUNK_DATA || \ (option) == CURLOPT_CLOSESOCKETDATA || \ (option) == CURLOPT_DEBUGDATA || \ (option) == CURLOPT_FNMATCH_DATA || \ (option) == CURLOPT_HEADERDATA || \ (option) == CURLOPT_HSTSREADDATA || \ (option) == CURLOPT_HSTSWRITEDATA || \ (option) == CURLOPT_INTERLEAVEDATA || \ (option) == CURLOPT_IOCTLDATA || \ (option) == CURLOPT_OPENSOCKETDATA || \ (option) == CURLOPT_PREREQDATA || \ (option) == CURLOPT_PROGRESSDATA || \ (option) == CURLOPT_READDATA || \ (option) == CURLOPT_SEEKDATA || \ (option) == CURLOPT_SOCKOPTDATA || \ (option) == CURLOPT_SSH_KEYDATA || \ (option) == CURLOPT_SSL_CTX_DATA || \ (option) == CURLOPT_WRITEDATA || \ (option) == CURLOPT_RESOLVER_START_DATA || \ (option) == CURLOPT_TRAILERDATA || \ 0) /* evaluates to true if option takes a POST data argument (void* or char*) */ #define curlcheck_postfields_option(option) \ ((option) == CURLOPT_POSTFIELDS || \ (option) == CURLOPT_COPYPOSTFIELDS || \ 0) /* evaluates to true if option takes a struct curl_slist * argument */ #define curlcheck_slist_option(option) \ ((option) == CURLOPT_HTTP200ALIASES || \ (option) == CURLOPT_HTTPHEADER || \ (option) == CURLOPT_MAIL_RCPT || \ (option) == CURLOPT_POSTQUOTE || \ (option) == CURLOPT_PREQUOTE || \ (option) == CURLOPT_PROXYHEADER || \ (option) == CURLOPT_QUOTE || \ (option) == CURLOPT_RESOLVE || \ (option) == CURLOPT_TELNETOPTIONS || \ (option) == CURLOPT_CONNECT_TO || \ 0) /* groups of curl_easy_getinfo infos that take the same type of argument */ /* evaluates to true if info expects a pointer to char * argument */ #define curlcheck_string_info(info) \ (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG && \ (info) != CURLINFO_PRIVATE) /* evaluates to true if info expects a pointer to long argument */ #define curlcheck_long_info(info) \ (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE) /* evaluates to true if info expects a pointer to double argument */ #define curlcheck_double_info(info) \ (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST) /* true if info expects a pointer to struct curl_slist * argument */ #define curlcheck_slist_info(info) \ (((info) == CURLINFO_SSL_ENGINES) || ((info) == CURLINFO_COOKIELIST)) /* true if info expects a pointer to struct curl_tlssessioninfo * argument */ #define curlcheck_tlssessioninfo_info(info) \ (((info) == CURLINFO_TLS_SSL_PTR) || ((info) == CURLINFO_TLS_SESSION)) /* true if info expects a pointer to struct curl_certinfo * argument */ #define curlcheck_certinfo_info(info) ((info) == CURLINFO_CERTINFO) /* true if info expects a pointer to struct curl_socket_t argument */ #define curlcheck_socket_info(info) \ (CURLINFO_SOCKET < (info) && (info) < CURLINFO_OFF_T) /* true if info expects a pointer to curl_off_t argument */ #define curlcheck_off_t_info(info) \ (CURLINFO_OFF_T < (info)) /* typecheck helpers -- check whether given expression has requested type*/ /* For pointers, you can use the curlcheck_ptr/curlcheck_arr macros, * otherwise define a new macro. Search for __builtin_types_compatible_p * in the GCC manual. * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is * the actual expression passed to the curl_easy_setopt macro. This * means that you can only apply the sizeof and __typeof__ operators, no * == or whatsoever. */ /* XXX: should evaluate to true if expr is a pointer */ #define curlcheck_any_ptr(expr) \ (sizeof(expr) == sizeof(void *)) /* evaluates to true if expr is NULL */ /* XXX: must not evaluate expr, so this check is not accurate */ #define curlcheck_NULL(expr) \ (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL))) /* evaluates to true if expr is type*, const type* or NULL */ #define curlcheck_ptr(expr, type) \ (curlcheck_NULL(expr) || \ __builtin_types_compatible_p(__typeof__(expr), type *) || \ __builtin_types_compatible_p(__typeof__(expr), const type *)) /* evaluates to true if expr is one of type[], type*, NULL or const type* */ #define curlcheck_arr(expr, type) \ (curlcheck_ptr((expr), type) || \ __builtin_types_compatible_p(__typeof__(expr), type [])) /* evaluates to true if expr is a string */ #define curlcheck_string(expr) \ (curlcheck_arr((expr), char) || \ curlcheck_arr((expr), signed char) || \ curlcheck_arr((expr), unsigned char)) /* evaluates to true if expr is a long (no matter the signedness) * XXX: for now, int is also accepted (and therefore short and char, which * are promoted to int when passed to a variadic function) */ #define curlcheck_long(expr) \ (__builtin_types_compatible_p(__typeof__(expr), long) || \ __builtin_types_compatible_p(__typeof__(expr), signed long) || \ __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \ __builtin_types_compatible_p(__typeof__(expr), int) || \ __builtin_types_compatible_p(__typeof__(expr), signed int) || \ __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \ __builtin_types_compatible_p(__typeof__(expr), short) || \ __builtin_types_compatible_p(__typeof__(expr), signed short) || \ __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \ __builtin_types_compatible_p(__typeof__(expr), char) || \ __builtin_types_compatible_p(__typeof__(expr), signed char) || \ __builtin_types_compatible_p(__typeof__(expr), unsigned char)) /* evaluates to true if expr is of type curl_off_t */ #define curlcheck_off_t(expr) \ (__builtin_types_compatible_p(__typeof__(expr), curl_off_t)) /* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */ /* XXX: also check size of an char[] array? */ #define curlcheck_error_buffer(expr) \ (curlcheck_NULL(expr) || \ __builtin_types_compatible_p(__typeof__(expr), char *) || \ __builtin_types_compatible_p(__typeof__(expr), char[])) /* evaluates to true if expr is of type (const) void* or (const) FILE* */ #if 0 #define curlcheck_cb_data(expr) \ (curlcheck_ptr((expr), void) || \ curlcheck_ptr((expr), FILE)) #else /* be less strict */ #define curlcheck_cb_data(expr) \ curlcheck_any_ptr(expr) #endif /* evaluates to true if expr is of type FILE* */ #define curlcheck_FILE(expr) \ (curlcheck_NULL(expr) || \ (__builtin_types_compatible_p(__typeof__(expr), FILE *))) /* evaluates to true if expr can be passed as POST data (void* or char*) */ #define curlcheck_postfields(expr) \ (curlcheck_ptr((expr), void) || \ curlcheck_arr((expr), char) || \ curlcheck_arr((expr), unsigned char)) /* helper: __builtin_types_compatible_p distinguishes between functions and * function pointers, hide it */ #define curlcheck_cb_compatible(func, type) \ (__builtin_types_compatible_p(__typeof__(func), type) || \ __builtin_types_compatible_p(__typeof__(func) *, type)) /* evaluates to true if expr is of type curl_resolver_start_callback */ #define curlcheck_resolver_start_callback(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_resolver_start_callback)) /* evaluates to true if expr is of type curl_read_callback or "similar" */ #define curlcheck_read_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), __typeof__(fread) *) || \ curlcheck_cb_compatible((expr), curl_read_callback) || \ curlcheck_cb_compatible((expr), _curl_read_callback1) || \ curlcheck_cb_compatible((expr), _curl_read_callback2) || \ curlcheck_cb_compatible((expr), _curl_read_callback3) || \ curlcheck_cb_compatible((expr), _curl_read_callback4) || \ curlcheck_cb_compatible((expr), _curl_read_callback5) || \ curlcheck_cb_compatible((expr), _curl_read_callback6)) typedef size_t (*_curl_read_callback1)(char *, size_t, size_t, void *); typedef size_t (*_curl_read_callback2)(char *, size_t, size_t, const void *); typedef size_t (*_curl_read_callback3)(char *, size_t, size_t, FILE *); typedef size_t (*_curl_read_callback4)(void *, size_t, size_t, void *); typedef size_t (*_curl_read_callback5)(void *, size_t, size_t, const void *); typedef size_t (*_curl_read_callback6)(void *, size_t, size_t, FILE *); /* evaluates to true if expr is of type curl_write_callback or "similar" */ #define curlcheck_write_cb(expr) \ (curlcheck_read_cb(expr) || \ curlcheck_cb_compatible((expr), __typeof__(fwrite) *) || \ curlcheck_cb_compatible((expr), curl_write_callback) || \ curlcheck_cb_compatible((expr), _curl_write_callback1) || \ curlcheck_cb_compatible((expr), _curl_write_callback2) || \ curlcheck_cb_compatible((expr), _curl_write_callback3) || \ curlcheck_cb_compatible((expr), _curl_write_callback4) || \ curlcheck_cb_compatible((expr), _curl_write_callback5) || \ curlcheck_cb_compatible((expr), _curl_write_callback6)) typedef size_t (*_curl_write_callback1)(const char *, size_t, size_t, void *); typedef size_t (*_curl_write_callback2)(const char *, size_t, size_t, const void *); typedef size_t (*_curl_write_callback3)(const char *, size_t, size_t, FILE *); typedef size_t (*_curl_write_callback4)(const void *, size_t, size_t, void *); typedef size_t (*_curl_write_callback5)(const void *, size_t, size_t, const void *); typedef size_t (*_curl_write_callback6)(const void *, size_t, size_t, FILE *); /* evaluates to true if expr is of type curl_ioctl_callback or "similar" */ #define curlcheck_ioctl_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_ioctl_callback) || \ curlcheck_cb_compatible((expr), _curl_ioctl_callback1) || \ curlcheck_cb_compatible((expr), _curl_ioctl_callback2) || \ curlcheck_cb_compatible((expr), _curl_ioctl_callback3) || \ curlcheck_cb_compatible((expr), _curl_ioctl_callback4)) typedef curlioerr (*_curl_ioctl_callback1)(CURL *, int, void *); typedef curlioerr (*_curl_ioctl_callback2)(CURL *, int, const void *); typedef curlioerr (*_curl_ioctl_callback3)(CURL *, curliocmd, void *); typedef curlioerr (*_curl_ioctl_callback4)(CURL *, curliocmd, const void *); /* evaluates to true if expr is of type curl_sockopt_callback or "similar" */ #define curlcheck_sockopt_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_sockopt_callback) || \ curlcheck_cb_compatible((expr), _curl_sockopt_callback1) || \ curlcheck_cb_compatible((expr), _curl_sockopt_callback2)) typedef int (*_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype); typedef int (*_curl_sockopt_callback2)(const void *, curl_socket_t, curlsocktype); /* evaluates to true if expr is of type curl_opensocket_callback or "similar" */ #define curlcheck_opensocket_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_opensocket_callback) || \ curlcheck_cb_compatible((expr), _curl_opensocket_callback1) || \ curlcheck_cb_compatible((expr), _curl_opensocket_callback2) || \ curlcheck_cb_compatible((expr), _curl_opensocket_callback3) || \ curlcheck_cb_compatible((expr), _curl_opensocket_callback4)) typedef curl_socket_t (*_curl_opensocket_callback1) (void *, curlsocktype, struct curl_sockaddr *); typedef curl_socket_t (*_curl_opensocket_callback2) (void *, curlsocktype, const struct curl_sockaddr *); typedef curl_socket_t (*_curl_opensocket_callback3) (const void *, curlsocktype, struct curl_sockaddr *); typedef curl_socket_t (*_curl_opensocket_callback4) (const void *, curlsocktype, const struct curl_sockaddr *); /* evaluates to true if expr is of type curl_progress_callback or "similar" */ #define curlcheck_progress_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_progress_callback) || \ curlcheck_cb_compatible((expr), _curl_progress_callback1) || \ curlcheck_cb_compatible((expr), _curl_progress_callback2)) typedef int (*_curl_progress_callback1)(void *, double, double, double, double); typedef int (*_curl_progress_callback2)(const void *, double, double, double, double); /* evaluates to true if expr is of type curl_debug_callback or "similar" */ #define curlcheck_debug_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_debug_callback) || \ curlcheck_cb_compatible((expr), _curl_debug_callback1) || \ curlcheck_cb_compatible((expr), _curl_debug_callback2) || \ curlcheck_cb_compatible((expr), _curl_debug_callback3) || \ curlcheck_cb_compatible((expr), _curl_debug_callback4) || \ curlcheck_cb_compatible((expr), _curl_debug_callback5) || \ curlcheck_cb_compatible((expr), _curl_debug_callback6) || \ curlcheck_cb_compatible((expr), _curl_debug_callback7) || \ curlcheck_cb_compatible((expr), _curl_debug_callback8)) typedef int (*_curl_debug_callback1) (CURL *, curl_infotype, char *, size_t, void *); typedef int (*_curl_debug_callback2) (CURL *, curl_infotype, char *, size_t, const void *); typedef int (*_curl_debug_callback3) (CURL *, curl_infotype, const char *, size_t, void *); typedef int (*_curl_debug_callback4) (CURL *, curl_infotype, const char *, size_t, const void *); typedef int (*_curl_debug_callback5) (CURL *, curl_infotype, unsigned char *, size_t, void *); typedef int (*_curl_debug_callback6) (CURL *, curl_infotype, unsigned char *, size_t, const void *); typedef int (*_curl_debug_callback7) (CURL *, curl_infotype, const unsigned char *, size_t, void *); typedef int (*_curl_debug_callback8) (CURL *, curl_infotype, const unsigned char *, size_t, const void *); /* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */ /* this is getting even messier... */ #define curlcheck_ssl_ctx_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_ssl_ctx_callback) || \ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback1) || \ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback2) || \ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback3) || \ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback4) || \ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback5) || \ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback6) || \ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback7) || \ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback8)) typedef CURLcode (*_curl_ssl_ctx_callback1)(CURL *, void *, void *); typedef CURLcode (*_curl_ssl_ctx_callback2)(CURL *, void *, const void *); typedef CURLcode (*_curl_ssl_ctx_callback3)(CURL *, const void *, void *); typedef CURLcode (*_curl_ssl_ctx_callback4)(CURL *, const void *, const void *); #ifdef HEADER_SSL_H /* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX * this will of course break if we're included before OpenSSL headers... */ typedef CURLcode (*_curl_ssl_ctx_callback5)(CURL *, SSL_CTX *, void *); typedef CURLcode (*_curl_ssl_ctx_callback6)(CURL *, SSL_CTX *, const void *); typedef CURLcode (*_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX *, void *); typedef CURLcode (*_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX *, const void *); #else typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5; typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6; typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7; typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8; #endif /* evaluates to true if expr is of type curl_conv_callback or "similar" */ #define curlcheck_conv_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_conv_callback) || \ curlcheck_cb_compatible((expr), _curl_conv_callback1) || \ curlcheck_cb_compatible((expr), _curl_conv_callback2) || \ curlcheck_cb_compatible((expr), _curl_conv_callback3) || \ curlcheck_cb_compatible((expr), _curl_conv_callback4)) typedef CURLcode (*_curl_conv_callback1)(char *, size_t length); typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length); typedef CURLcode (*_curl_conv_callback3)(void *, size_t length); typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length); /* evaluates to true if expr is of type curl_seek_callback or "similar" */ #define curlcheck_seek_cb(expr) \ (curlcheck_NULL(expr) || \ curlcheck_cb_compatible((expr), curl_seek_callback) || \ curlcheck_cb_compatible((expr), _curl_seek_callback1) || \ curlcheck_cb_compatible((expr), _curl_seek_callback2)) typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int); typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int); #endif /* CURLINC_TYPECHECK_GCC_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/multi.h
#ifndef CURLINC_MULTI_H #define CURLINC_MULTI_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* This is an "external" header file. Don't give away any internals here! GOALS o Enable a "pull" interface. The application that uses libcurl decides where and when to ask libcurl to get/send data. o Enable multiple simultaneous transfers in the same thread without making it complicated for the application. o Enable the application to select() on its own file descriptors and curl's file descriptors simultaneous easily. */ /* * This header file should not really need to include "curl.h" since curl.h * itself includes this file and we expect user applications to do #include * <curl/curl.h> without the need for especially including multi.h. * * For some reason we added this include here at one point, and rather than to * break existing (wrongly written) libcurl applications, we leave it as-is * but with this warning attached. */ #include "curl.h" #ifdef __cplusplus extern "C" { #endif #if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) typedef struct Curl_multi CURLM; #else typedef void CURLM; #endif typedef enum { CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or curl_multi_socket*() soon */ CURLM_OK, CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */ CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was attempted to get added - again */ CURLM_RECURSIVE_API_CALL, /* an api function was called from inside a callback */ CURLM_WAKEUP_FAILURE, /* wakeup is unavailable or failed */ CURLM_BAD_FUNCTION_ARGUMENT, /* function called with a bad parameter */ CURLM_LAST } CURLMcode; /* just to make code nicer when using curl_multi_socket() you can now check for CURLM_CALL_MULTI_SOCKET too in the same style it works for curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */ #define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM /* bitmask bits for CURLMOPT_PIPELINING */ #define CURLPIPE_NOTHING 0L #define CURLPIPE_HTTP1 1L #define CURLPIPE_MULTIPLEX 2L typedef enum { CURLMSG_NONE, /* first, not used */ CURLMSG_DONE, /* This easy handle has completed. 'result' contains the CURLcode of the transfer */ CURLMSG_LAST /* last, not used */ } CURLMSG; struct CURLMsg { CURLMSG msg; /* what this message means */ CURL *easy_handle; /* the handle it concerns */ union { void *whatever; /* message-specific data */ CURLcode result; /* return code for transfer */ } data; }; typedef struct CURLMsg CURLMsg; /* Based on poll(2) structure and values. * We don't use pollfd and POLL* constants explicitly * to cover platforms without poll(). */ #define CURL_WAIT_POLLIN 0x0001 #define CURL_WAIT_POLLPRI 0x0002 #define CURL_WAIT_POLLOUT 0x0004 struct curl_waitfd { curl_socket_t fd; short events; short revents; /* not supported yet */ }; /* * Name: curl_multi_init() * * Desc: inititalize multi-style curl usage * * Returns: a new CURLM handle to use in all 'curl_multi' functions. */ CURL_EXTERN CURLM *curl_multi_init(void); /* * Name: curl_multi_add_handle() * * Desc: add a standard curl handle to the multi stack * * Returns: CURLMcode type, general multi error code. */ CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle, CURL *curl_handle); /* * Name: curl_multi_remove_handle() * * Desc: removes a curl handle from the multi stack again * * Returns: CURLMcode type, general multi error code. */ CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle, CURL *curl_handle); /* * Name: curl_multi_fdset() * * Desc: Ask curl for its fd_set sets. The app can use these to select() or * poll() on. We want curl_multi_perform() called as soon as one of * them are ready. * * Returns: CURLMcode type, general multi error code. */ CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *exc_fd_set, int *max_fd); /* * Name: curl_multi_wait() * * Desc: Poll on all fds within a CURLM set as well as any * additional fds passed to the function. * * Returns: CURLMcode type, general multi error code. */ CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret); /* * Name: curl_multi_poll() * * Desc: Poll on all fds within a CURLM set as well as any * additional fds passed to the function. * * Returns: CURLMcode type, general multi error code. */ CURL_EXTERN CURLMcode curl_multi_poll(CURLM *multi_handle, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret); /* * Name: curl_multi_wakeup() * * Desc: wakes up a sleeping curl_multi_poll call. * * Returns: CURLMcode type, general multi error code. */ CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *multi_handle); /* * Name: curl_multi_perform() * * Desc: When the app thinks there's data available for curl it calls this * function to read/write whatever there is right now. This returns * as soon as the reads and writes are done. This function does not * require that there actually is data available for reading or that * data can be written, it can be called just in case. It returns * the number of handles that still transfer data in the second * argument's integer-pointer. * * Returns: CURLMcode type, general multi error code. *NOTE* that this only * returns errors etc regarding the whole multi stack. There might * still have occurred problems on individual transfers even when * this returns OK. */ CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle, int *running_handles); /* * Name: curl_multi_cleanup() * * Desc: Cleans up and removes a whole multi stack. It does not free or * touch any individual easy handles in any way. We need to define * in what state those handles will be if this function is called * in the middle of a transfer. * * Returns: CURLMcode type, general multi error code. */ CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); /* * Name: curl_multi_info_read() * * Desc: Ask the multi handle if there's any messages/informationals from * the individual transfers. Messages include informationals such as * error code from the transfer or just the fact that a transfer is * completed. More details on these should be written down as well. * * Repeated calls to this function will return a new struct each * time, until a special "end of msgs" struct is returned as a signal * that there is no more to get at this point. * * The data the returned pointer points to will not survive calling * curl_multi_cleanup(). * * The 'CURLMsg' struct is meant to be very simple and only contain * very basic information. If more involved information is wanted, * we will provide the particular "transfer handle" in that struct * and that should/could/would be used in subsequent * curl_easy_getinfo() calls (or similar). The point being that we * must never expose complex structs to applications, as then we'll * undoubtably get backwards compatibility problems in the future. * * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out * of structs. It also writes the number of messages left in the * queue (after this read) in the integer the second argument points * to. */ CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle, int *msgs_in_queue); /* * Name: curl_multi_strerror() * * Desc: The curl_multi_strerror function may be used to turn a CURLMcode * value into the equivalent human readable error string. This is * useful for printing meaningful error messages. * * Returns: A pointer to a null-terminated error message. */ CURL_EXTERN const char *curl_multi_strerror(CURLMcode); /* * Name: curl_multi_socket() and * curl_multi_socket_all() * * Desc: An alternative version of curl_multi_perform() that allows the * application to pass in one of the file descriptors that have been * detected to have "action" on them and let libcurl perform. * See man page for details. */ #define CURL_POLL_NONE 0 #define CURL_POLL_IN 1 #define CURL_POLL_OUT 2 #define CURL_POLL_INOUT 3 #define CURL_POLL_REMOVE 4 #define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD #define CURL_CSELECT_IN 0x01 #define CURL_CSELECT_OUT 0x02 #define CURL_CSELECT_ERR 0x04 typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */ curl_socket_t s, /* socket */ int what, /* see above */ void *userp, /* private callback pointer */ void *socketp); /* private socket pointer */ /* * Name: curl_multi_timer_callback * * Desc: Called by libcurl whenever the library detects a change in the * maximum number of milliseconds the app is allowed to wait before * curl_multi_socket() or curl_multi_perform() must be called * (to allow libcurl's timed events to take place). * * Returns: The callback should return zero. */ typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */ long timeout_ms, /* see above */ void *userp); /* private callback pointer */ CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s, int *running_handles); CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle, curl_socket_t s, int ev_bitmask, int *running_handles); CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle, int *running_handles); #ifndef CURL_ALLOW_OLD_MULTI_SOCKET /* This macro below was added in 7.16.3 to push users who recompile to use the new curl_multi_socket_action() instead of the old curl_multi_socket() */ #define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z) #endif /* * Name: curl_multi_timeout() * * Desc: Returns the maximum number of milliseconds the app is allowed to * wait before curl_multi_socket() or curl_multi_perform() must be * called (to allow libcurl's timed events to take place). * * Returns: CURLM error code. */ CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle, long *milliseconds); typedef enum { /* This is the socket callback function pointer */ CURLOPT(CURLMOPT_SOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 1), /* This is the argument passed to the socket callback */ CURLOPT(CURLMOPT_SOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 2), /* set to 1 to enable pipelining for this multi handle */ CURLOPT(CURLMOPT_PIPELINING, CURLOPTTYPE_LONG, 3), /* This is the timer callback function pointer */ CURLOPT(CURLMOPT_TIMERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 4), /* This is the argument passed to the timer callback */ CURLOPT(CURLMOPT_TIMERDATA, CURLOPTTYPE_OBJECTPOINT, 5), /* maximum number of entries in the connection cache */ CURLOPT(CURLMOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 6), /* maximum number of (pipelining) connections to one host */ CURLOPT(CURLMOPT_MAX_HOST_CONNECTIONS, CURLOPTTYPE_LONG, 7), /* maximum number of requests in a pipeline */ CURLOPT(CURLMOPT_MAX_PIPELINE_LENGTH, CURLOPTTYPE_LONG, 8), /* a connection with a content-length longer than this will not be considered for pipelining */ CURLOPT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 9), /* a connection with a chunk length longer than this will not be considered for pipelining */ CURLOPT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 10), /* a list of site names(+port) that are blocked from pipelining */ CURLOPT(CURLMOPT_PIPELINING_SITE_BL, CURLOPTTYPE_OBJECTPOINT, 11), /* a list of server types that are blocked from pipelining */ CURLOPT(CURLMOPT_PIPELINING_SERVER_BL, CURLOPTTYPE_OBJECTPOINT, 12), /* maximum number of open connections in total */ CURLOPT(CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPTTYPE_LONG, 13), /* This is the server push callback function pointer */ CURLOPT(CURLMOPT_PUSHFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 14), /* This is the argument passed to the server push callback */ CURLOPT(CURLMOPT_PUSHDATA, CURLOPTTYPE_OBJECTPOINT, 15), /* maximum number of concurrent streams to support on a connection */ CURLOPT(CURLMOPT_MAX_CONCURRENT_STREAMS, CURLOPTTYPE_LONG, 16), CURLMOPT_LASTENTRY /* the last unused */ } CURLMoption; /* * Name: curl_multi_setopt() * * Desc: Sets options for the multi handle. * * Returns: CURLM error code. */ CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle, CURLMoption option, ...); /* * Name: curl_multi_assign() * * Desc: This function sets an association in the multi handle between the * given socket and a private pointer of the application. This is * (only) useful for curl_multi_socket uses. * * Returns: CURLM error code. */ CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle, curl_socket_t sockfd, void *sockp); /* * Name: curl_push_callback * * Desc: This callback gets called when a new stream is being pushed by the * server. It approves or denies the new stream. It can also decide * to completely fail the connection. * * Returns: CURL_PUSH_OK, CURL_PUSH_DENY or CURL_PUSH_ERROROUT */ #define CURL_PUSH_OK 0 #define CURL_PUSH_DENY 1 #define CURL_PUSH_ERROROUT 2 /* added in 7.72.0 */ struct curl_pushheaders; /* forward declaration only */ CURL_EXTERN char *curl_pushheader_bynum(struct curl_pushheaders *h, size_t num); CURL_EXTERN char *curl_pushheader_byname(struct curl_pushheaders *h, const char *name); typedef int (*curl_push_callback)(CURL *parent, CURL *easy, size_t num_headers, struct curl_pushheaders *headers, void *userp); #ifdef __cplusplus } /* end of extern "C" */ #endif #endif
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/options.h
#ifndef CURLINC_OPTIONS_H #define CURLINC_OPTIONS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2018 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifdef __cplusplus extern "C" { #endif typedef enum { CURLOT_LONG, /* long (a range of values) */ CURLOT_VALUES, /* (a defined set or bitmask) */ CURLOT_OFF_T, /* curl_off_t (a range of values) */ CURLOT_OBJECT, /* pointer (void *) */ CURLOT_STRING, /* (char * to zero terminated buffer) */ CURLOT_SLIST, /* (struct curl_slist *) */ CURLOT_CBPTR, /* (void * passed as-is to a callback) */ CURLOT_BLOB, /* blob (struct curl_blob *) */ CURLOT_FUNCTION /* function pointer */ } curl_easytype; /* Flag bits */ /* "alias" means it is provided for old programs to remain functional, we prefer another name */ #define CURLOT_FLAG_ALIAS (1<<0) /* The CURLOPTTYPE_* id ranges can still be used to figure out what type/size to use for curl_easy_setopt() for the given id */ struct curl_easyoption { const char *name; CURLoption id; curl_easytype type; unsigned int flags; }; CURL_EXTERN const struct curl_easyoption * curl_easy_option_by_name(const char *name); CURL_EXTERN const struct curl_easyoption * curl_easy_option_by_id (CURLoption id); CURL_EXTERN const struct curl_easyoption * curl_easy_option_next(const struct curl_easyoption *prev); #ifdef __cplusplus } /* end of extern "C" */ #endif #endif /* CURLINC_OPTIONS_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/curlver.h
#ifndef CURLINC_CURLVER_H #define CURLINC_CURLVER_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* This header file contains nothing but libcurl version info, generated by a script at release-time. This was made its own header file in 7.11.2 */ /* This is the global package copyright */ #define LIBCURL_COPYRIGHT "1996 - 2021 Daniel Stenberg, <[email protected]>." /* This is the version number of the libcurl package from which this header file origins: */ #define LIBCURL_VERSION "7.80.0-DEV" /* The numeric version number is also available "in parts" by using these defines: */ #define LIBCURL_VERSION_MAJOR 7 #define LIBCURL_VERSION_MINOR 80 #define LIBCURL_VERSION_PATCH 0 /* This is the numeric version of the libcurl version number, meant for easier parsing and comparisons by programs. The LIBCURL_VERSION_NUM define will always follow this syntax: 0xXXYYZZ Where XX, YY and ZZ are the main version, release and patch numbers in hexadecimal (using 8 bits each). All three numbers are always represented using two digits. 1.2 would appear as "0x010200" while version 9.11.7 appears as "0x090b07". This 6-digit (24 bits) hexadecimal number does not show pre-release number, and it is always a greater number in a more recent release. It makes comparisons with greater than and less than work. Note: This define is the full hex number and _does not_ use the CURL_VERSION_BITS() macro since curl's own configure script greps for it and needs it to contain the full number. */ #define LIBCURL_VERSION_NUM 0x075000 /* * This is the date and time when the full source package was created. The * timestamp is not stored in git, as the timestamp is properly set in the * tarballs by the maketgz script. * * The format of the date follows this template: * * "2007-11-23" */ #define LIBCURL_TIMESTAMP "[unreleased]" #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* CURLINC_CURLVER_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/urlapi.h
#ifndef CURLINC_URLAPI_H #define CURLINC_URLAPI_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2018 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl.h" #ifdef __cplusplus extern "C" { #endif /* the error codes for the URL API */ typedef enum { CURLUE_OK, CURLUE_BAD_HANDLE, /* 1 */ CURLUE_BAD_PARTPOINTER, /* 2 */ CURLUE_MALFORMED_INPUT, /* 3 */ CURLUE_BAD_PORT_NUMBER, /* 4 */ CURLUE_UNSUPPORTED_SCHEME, /* 5 */ CURLUE_URLDECODE, /* 6 */ CURLUE_OUT_OF_MEMORY, /* 7 */ CURLUE_USER_NOT_ALLOWED, /* 8 */ CURLUE_UNKNOWN_PART, /* 9 */ CURLUE_NO_SCHEME, /* 10 */ CURLUE_NO_USER, /* 11 */ CURLUE_NO_PASSWORD, /* 12 */ CURLUE_NO_OPTIONS, /* 13 */ CURLUE_NO_HOST, /* 14 */ CURLUE_NO_PORT, /* 15 */ CURLUE_NO_QUERY, /* 16 */ CURLUE_NO_FRAGMENT, /* 17 */ CURLUE_LAST } CURLUcode; typedef enum { CURLUPART_URL, CURLUPART_SCHEME, CURLUPART_USER, CURLUPART_PASSWORD, CURLUPART_OPTIONS, CURLUPART_HOST, CURLUPART_PORT, CURLUPART_PATH, CURLUPART_QUERY, CURLUPART_FRAGMENT, CURLUPART_ZONEID /* added in 7.65.0 */ } CURLUPart; #define CURLU_DEFAULT_PORT (1<<0) /* return default port number */ #define CURLU_NO_DEFAULT_PORT (1<<1) /* act as if no port number was set, if the port number matches the default for the scheme */ #define CURLU_DEFAULT_SCHEME (1<<2) /* return default scheme if missing */ #define CURLU_NON_SUPPORT_SCHEME (1<<3) /* allow non-supported scheme */ #define CURLU_PATH_AS_IS (1<<4) /* leave dot sequences */ #define CURLU_DISALLOW_USER (1<<5) /* no user+password allowed */ #define CURLU_URLDECODE (1<<6) /* URL decode on get */ #define CURLU_URLENCODE (1<<7) /* URL encode on set */ #define CURLU_APPENDQUERY (1<<8) /* append a form style part */ #define CURLU_GUESS_SCHEME (1<<9) /* legacy curl-style guessing */ #define CURLU_NO_AUTHORITY (1<<10) /* Allow empty authority when the scheme is unknown. */ #define CURLU_ALLOW_SPACE (1<<11) /* Allow spaces in the URL */ typedef struct Curl_URL CURLU; /* * curl_url() creates a new CURLU handle and returns a pointer to it. * Must be freed with curl_url_cleanup(). */ CURL_EXTERN CURLU *curl_url(void); /* * curl_url_cleanup() frees the CURLU handle and related resources used for * the URL parsing. It will not free strings previously returned with the URL * API. */ CURL_EXTERN void curl_url_cleanup(CURLU *handle); /* * curl_url_dup() duplicates a CURLU handle and returns a new copy. The new * handle must also be freed with curl_url_cleanup(). */ CURL_EXTERN CURLU *curl_url_dup(CURLU *in); /* * curl_url_get() extracts a specific part of the URL from a CURLU * handle. Returns error code. The returned pointer MUST be freed with * curl_free() afterwards. */ CURL_EXTERN CURLUcode curl_url_get(CURLU *handle, CURLUPart what, char **part, unsigned int flags); /* * curl_url_set() sets a specific part of the URL in a CURLU handle. Returns * error code. The passed in string will be copied. Passing a NULL instead of * a part string, clears that part. */ CURL_EXTERN CURLUcode curl_url_set(CURLU *handle, CURLUPart what, const char *part, unsigned int flags); /* * curl_url_strerror() turns a CURLUcode value into the equivalent human * readable error string. This is useful for printing meaningful error * messages. */ CURL_EXTERN const char *curl_url_strerror(CURLUcode); #ifdef __cplusplus } /* end of extern "C" */ #endif #endif /* CURLINC_URLAPI_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/mprintf.h
#ifndef CURLINC_MPRINTF_H #define CURLINC_MPRINTF_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <stdarg.h> #include <stdio.h> /* needed for FILE */ #include "curl.h" /* for CURL_EXTERN */ #ifdef __cplusplus extern "C" { #endif CURL_EXTERN int curl_mprintf(const char *format, ...); CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...); CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...); CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...); CURL_EXTERN int curl_mvprintf(const char *format, va_list args); CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args); CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args); CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, const char *format, va_list args); CURL_EXTERN char *curl_maprintf(const char *format, ...); CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); #ifdef __cplusplus } #endif #endif /* CURLINC_MPRINTF_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/system.h
#ifndef CURLINC_SYSTEM_H #define CURLINC_SYSTEM_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Try to keep one section per platform, compiler and architecture, otherwise, * if an existing section is reused for a different one and later on the * original is adjusted, probably the piggybacking one can be adversely * changed. * * In order to differentiate between platforms/compilers/architectures use * only compiler built in predefined preprocessor symbols. * * curl_off_t * ---------- * * For any given platform/compiler curl_off_t must be typedef'ed to a 64-bit * wide signed integral data type. The width of this data type must remain * constant and independent of any possible large file support settings. * * As an exception to the above, curl_off_t shall be typedef'ed to a 32-bit * wide signed integral data type if there is no 64-bit type. * * As a general rule, curl_off_t shall not be mapped to off_t. This rule shall * only be violated if off_t is the only 64-bit data type available and the * size of off_t is independent of large file support settings. Keep your * build on the safe side avoiding an off_t gating. If you have a 64-bit * off_t then take for sure that another 64-bit data type exists, dig deeper * and you will find it. * */ #if defined(__DJGPP__) || defined(__GO32__) # if defined(__DJGPP__) && (__DJGPP__ > 1) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # else # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__SALFORDC__) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__BORLANDC__) # if (__BORLANDC__ < 0x520) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # else # define CURL_TYPEOF_CURL_OFF_T __int64 # define CURL_FORMAT_CURL_OFF_T "I64d" # define CURL_FORMAT_CURL_OFF_TU "I64u" # define CURL_SUFFIX_CURL_OFF_T i64 # define CURL_SUFFIX_CURL_OFF_TU ui64 # endif # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__TURBOC__) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__WATCOMC__) # if defined(__386__) # define CURL_TYPEOF_CURL_OFF_T __int64 # define CURL_FORMAT_CURL_OFF_T "I64d" # define CURL_FORMAT_CURL_OFF_TU "I64u" # define CURL_SUFFIX_CURL_OFF_T i64 # define CURL_SUFFIX_CURL_OFF_TU ui64 # else # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__POCC__) # if (__POCC__ < 280) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # elif defined(_MSC_VER) # define CURL_TYPEOF_CURL_OFF_T __int64 # define CURL_FORMAT_CURL_OFF_T "I64d" # define CURL_FORMAT_CURL_OFF_TU "I64u" # define CURL_SUFFIX_CURL_OFF_T i64 # define CURL_SUFFIX_CURL_OFF_TU ui64 # else # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__LCC__) # if defined(__e2k__) /* MCST eLbrus C Compiler */ # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 # else /* Local (or Little) C Compiler */ # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # define CURL_TYPEOF_CURL_SOCKLEN_T int # endif #elif defined(__SYMBIAN32__) # if defined(__EABI__) /* Treat all ARM compilers equally */ # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # elif defined(__CW32__) # pragma longlong on # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # elif defined(__VC32__) # define CURL_TYPEOF_CURL_OFF_T __int64 # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int #elif defined(__MWERKS__) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(_WIN32_WCE) # define CURL_TYPEOF_CURL_OFF_T __int64 # define CURL_FORMAT_CURL_OFF_T "I64d" # define CURL_FORMAT_CURL_OFF_TU "I64u" # define CURL_SUFFIX_CURL_OFF_T i64 # define CURL_SUFFIX_CURL_OFF_TU ui64 # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__MINGW32__) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "I64d" # define CURL_FORMAT_CURL_OFF_TU "I64u" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_WS2TCPIP_H 1 #elif defined(__VMS) # if defined(__VAX) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # else # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int #elif defined(__OS400__) # if defined(__ILEC400__) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 # endif #elif defined(__MVS__) # if defined(__IBMC__) || defined(__IBMCPP__) # if defined(_ILP32) # elif defined(_LP64) # endif # if defined(_LONG_LONG) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # elif defined(_LP64) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # else # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 # endif #elif defined(__370__) # if defined(__IBMC__) || defined(__IBMCPP__) # if defined(_ILP32) # elif defined(_LP64) # endif # if defined(_LONG_LONG) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # elif defined(_LP64) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # else # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 # endif #elif defined(TPF) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # define CURL_TYPEOF_CURL_SOCKLEN_T int #elif defined(__TINYC__) /* also known as tcc */ # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Oracle Solaris Studio */ # if !defined(__LP64) && (defined(__ILP32) || \ defined(__i386) || \ defined(__sparcv8) || \ defined(__sparcv8plus)) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # elif defined(__LP64) || \ defined(__amd64) || defined(__sparcv9) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 #elif defined(__xlc__) /* IBM xlc compiler */ # if !defined(_LP64) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # else # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 /* ===================================== */ /* KEEP MSVC THE PENULTIMATE ENTRY */ /* ===================================== */ #elif defined(_MSC_VER) # if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) # define CURL_TYPEOF_CURL_OFF_T __int64 # define CURL_FORMAT_CURL_OFF_T "I64d" # define CURL_FORMAT_CURL_OFF_TU "I64u" # define CURL_SUFFIX_CURL_OFF_T i64 # define CURL_SUFFIX_CURL_OFF_TU ui64 # else # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T int /* ===================================== */ /* KEEP GENERIC GCC THE LAST ENTRY */ /* ===================================== */ #elif defined(__GNUC__) && !defined(_SCO_DS) # if !defined(__LP64__) && \ (defined(__ILP32__) || defined(__i386__) || defined(__hppa__) || \ defined(__ppc__) || defined(__powerpc__) || defined(__arm__) || \ defined(__sparc__) || defined(__mips__) || defined(__sh__) || \ defined(__XTENSA__) || \ (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4) || \ (defined(__LONG_MAX__) && __LONG_MAX__ == 2147483647L)) # define CURL_TYPEOF_CURL_OFF_T long long # define CURL_FORMAT_CURL_OFF_T "lld" # define CURL_FORMAT_CURL_OFF_TU "llu" # define CURL_SUFFIX_CURL_OFF_T LL # define CURL_SUFFIX_CURL_OFF_TU ULL # elif defined(__LP64__) || \ defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) || \ defined(__e2k__) || \ (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8) || \ (defined(__LONG_MAX__) && __LONG_MAX__ == 9223372036854775807L) # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # endif # define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t # define CURL_PULL_SYS_TYPES_H 1 # define CURL_PULL_SYS_SOCKET_H 1 #else /* generic "safe guess" on old 32 bit style */ # define CURL_TYPEOF_CURL_OFF_T long # define CURL_FORMAT_CURL_OFF_T "ld" # define CURL_FORMAT_CURL_OFF_TU "lu" # define CURL_SUFFIX_CURL_OFF_T L # define CURL_SUFFIX_CURL_OFF_TU UL # define CURL_TYPEOF_CURL_SOCKLEN_T int #endif #ifdef _AIX /* AIX needs <sys/poll.h> */ #define CURL_PULL_SYS_POLL_H #endif /* CURL_PULL_WS2TCPIP_H is defined above when inclusion of header file */ /* ws2tcpip.h is required here to properly make type definitions below. */ #ifdef CURL_PULL_WS2TCPIP_H # include <winsock2.h> # include <windows.h> # include <ws2tcpip.h> #endif /* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */ /* sys/types.h is required here to properly make type definitions below. */ #ifdef CURL_PULL_SYS_TYPES_H # include <sys/types.h> #endif /* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */ /* sys/socket.h is required here to properly make type definitions below. */ #ifdef CURL_PULL_SYS_SOCKET_H # include <sys/socket.h> #endif /* CURL_PULL_SYS_POLL_H is defined above when inclusion of header file */ /* sys/poll.h is required here to properly make type definitions below. */ #ifdef CURL_PULL_SYS_POLL_H # include <sys/poll.h> #endif /* Data type definition of curl_socklen_t. */ #ifdef CURL_TYPEOF_CURL_SOCKLEN_T typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; #endif /* Data type definition of curl_off_t. */ #ifdef CURL_TYPEOF_CURL_OFF_T typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; #endif /* * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow * these to be visible and exported by the external libcurl interface API, * while also making them visible to the library internals, simply including * curl_setup.h, without actually needing to include curl.h internally. * If some day this section would grow big enough, all this should be moved * to its own header file. */ /* * Figure out if we can use the ## preprocessor operator, which is supported * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__ * or __cplusplus so we need to carefully check for them too. */ #if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \ defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \ defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \ defined(__ILEC400__) /* This compiler is believed to have an ISO compatible preprocessor */ #define CURL_ISOCPP #else /* This compiler is believed NOT to have an ISO compatible preprocessor */ #undef CURL_ISOCPP #endif /* * Macros for minimum-width signed and unsigned curl_off_t integer constants. */ #if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551) # define CURLINC_OFF_T_C_HLPR2(x) x # define CURLINC_OFF_T_C_HLPR1(x) CURLINC_OFF_T_C_HLPR2(x) # define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \ CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T) # define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \ CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU) #else # ifdef CURL_ISOCPP # define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix # else # define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix # endif # define CURLINC_OFF_T_C_HLPR1(Val,Suffix) CURLINC_OFF_T_C_HLPR2(Val,Suffix) # define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T) # define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU) #endif #endif /* CURLINC_SYSTEM_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/stdcheaders.h
#ifndef CURLINC_STDCHEADERS_H #define CURLINC_STDCHEADERS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include <sys/types.h> size_t fread(void *, size_t, size_t, FILE *); size_t fwrite(const void *, size_t, size_t, FILE *); int strcasecmp(const char *, const char *); int strncasecmp(const char *, const char *, size_t); #endif /* CURLINC_STDCHEADERS_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl/include
repos/gpt4all.zig/src/zig-libcurl/curl/include/curl/easy.h
#ifndef CURLINC_EASY_H #define CURLINC_EASY_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifdef __cplusplus extern "C" { #endif /* Flag bits in the curl_blob struct: */ #define CURL_BLOB_COPY 1 /* tell libcurl to copy the data */ #define CURL_BLOB_NOCOPY 0 /* tell libcurl to NOT copy the data */ struct curl_blob { void *data; size_t len; unsigned int flags; /* bit 0 is defined, the rest are reserved and should be left zeroes */ }; CURL_EXTERN CURL *curl_easy_init(void); CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...); CURL_EXTERN CURLcode curl_easy_perform(CURL *curl); CURL_EXTERN void curl_easy_cleanup(CURL *curl); /* * NAME curl_easy_getinfo() * * DESCRIPTION * * Request internal information from the curl session with this function. The * third argument MUST be a pointer to a long, a pointer to a char * or a * pointer to a double (as the documentation describes elsewhere). The data * pointed to will be filled in accordingly and can be relied upon only if the * function returns CURLE_OK. This function is intended to get used *AFTER* a * performed transfer, all results from this function are undefined until the * transfer is completed. */ CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); /* * NAME curl_easy_duphandle() * * DESCRIPTION * * Creates a new curl session handle with the same options set for the handle * passed in. Duplicating a handle could only be a matter of cloning data and * options, internal state info and things like persistent connections cannot * be transferred. It is useful in multithreaded applications when you can run * curl_easy_duphandle() for each new thread to avoid a series of identical * curl_easy_setopt() invokes in every thread. */ CURL_EXTERN CURL *curl_easy_duphandle(CURL *curl); /* * NAME curl_easy_reset() * * DESCRIPTION * * Re-initializes a CURL handle to the default values. This puts back the * handle to the same state as it was in when it was just created. * * It does keep: live connections, the Session ID cache, the DNS cache and the * cookies. */ CURL_EXTERN void curl_easy_reset(CURL *curl); /* * NAME curl_easy_recv() * * DESCRIPTION * * Receives data from the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. */ CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, size_t *n); /* * NAME curl_easy_send() * * DESCRIPTION * * Sends data over the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. */ CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer, size_t buflen, size_t *n); /* * NAME curl_easy_upkeep() * * DESCRIPTION * * Performs connection upkeep for the given session handle. */ CURL_EXTERN CURLcode curl_easy_upkeep(CURL *curl); #ifdef __cplusplus } #endif #endif
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/copyright.pl
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### # # Invoke script in the root of the git checkout. Scans all files in git unless # given a specific single file. # # Usage: copyright.pl [file] # # regexes of files to not scan my @skiplist=( '^tests\/data\/test(\d+)$', # test case data '^docs\/cmdline-opts\/[a-z]+(.*)\.d$', # curl.1 pieces '(\/|^)[A-Z0-9_.-]+$', # all uppercase file name, possibly with dot and dash '(\/|^)[A-Z0-9_-]+\.md$', # all uppercase file name with .md extension '.gitignore', # wherever they are '.gitattributes', # wherever they are '^tests/certs/.*', # generated certs '^tests/stunnel.pem', # generated cert '^tests/valgrind.supp', # valgrind suppressions '^projects/Windows/.*.dsw$', # generated MSVC file '^projects/Windows/.*.sln$', # generated MSVC file '^projects/Windows/.*.tmpl$', # generated MSVC file '^projects/Windows/.*.vcxproj.filters$', # generated MSVC file '^m4/ax_compile_check_sizeof.m4$', # imported, leave be '^.mailmap', # git control file '\/readme', '^.github/', # github instruction files '^.dcignore', # deepcode.ai instruction file '^.lift/', # muse-CI control files "buildconf", # its nothing to copyright # docs/ files we're okay with without copyright 'INSTALL.cmake', 'TheArtOfHttpScripting', 'page-footer', 'curl_multi_socket_all.3', 'curl_strnequal.3', 'symbols-in-versions', 'options-in-versions', # macos-framework files '^lib\/libcurl.plist', '^lib\/libcurl.vers.in', # vms files '^packages\/vms\/build_vms.com', '^packages\/vms\/curl_release_note_start.txt', '^packages\/vms\/curlmsg.sdl', '^packages\/vms\/macro32_exactcase.patch', # XML junk '^projects\/wolfssl_override.props', # macos framework generated files '^src\/macos\/curl.mcp.xml.sit.hqx', '^src\/macos\/src\/curl_GUSIConfig.cpp', # checksrc control files '\.checksrc$', # an empty control file "^zuul.d/playbooks/.zuul.ignore", ); sub scanfile { my ($f) = @_; my $line=1; my $found = 0; open(F, "<$f") || print ERROR "can't open $f\n"; while (<F>) { chomp; my $l = $_; # check for a copyright statement and save the years if($l =~ /.* +copyright .* *\d\d\d\d/i) { while($l =~ /([\d]{4})/g) { push @copyright, { year => $1, line => $line, col => index($l, $1), code => $l }; $found++; } } # allow within the first 100 lines if(++$line > 100) { last; } } close(F); return $found; } sub checkfile { my ($file) = @_; my $fine = 0; @copyright=(); my $found = scanfile($file); if(!$found) { print "$file:1: missing copyright range\n"; return 2; } my $commityear = undef; @copyright = sort {$$b{year} cmp $$a{year}} @copyright; # if the file is modified, assume commit year this year if(`git status -s -- $file` =~ /^ [MARCU]/) { $commityear = (localtime(time))[5] + 1900; } else { # min-parents=1 to ignore wrong initial commit in truncated repos my $grl = `git rev-list --max-count=1 --min-parents=1 --timestamp HEAD -- $file`; if($grl) { chomp $grl; $commityear = (localtime((split(/ /, $grl))[0]))[5] + 1900; } } if(defined($commityear) && scalar(@copyright) && $copyright[0]{year} != $commityear) { printf "$file:%d: copyright year out of date, should be $commityear, " . "is $copyright[0]{year}\n", $copyright[0]{line}; } else { $fine = 1; } return $fine; } my @all; if($ARGV[0]) { push @all, $ARGV[0]; } else { @all = `git ls-files`; } for my $f (@all) { chomp $f; my $skipped = 0; for my $skip (@skiplist) { #print "$f matches $skip ?\n"; if($f =~ /$skip/) { $skiplisted++; $skipped = 1; #print "$f: SKIPPED ($skip)\n"; last; } } if(!$skipped) { my $r = checkfile($f); $missing++ if($r == 2); $wrong++ if(!$r); } } print STDERR "$missing files have no copyright\n" if($missing); print STDERR "$wrong files have wrong copyright year\n" if ($wrong); print STDERR "$skiplisted files are skipped\n" if ($skiplisted); exit 1 if($missing || $wrong);
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/coverage.sh
#!/bin/sh #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### ./buildconf mkdir -p cvr cd cvr ../configure --disable-shared --enable-debug --enable-maintainer-mode --enable-code-coverage make -sj # the regular test run make TFLAGS=-n test-nonflaky # make all allocs/file operations fail #make TFLAGS=-n test-torture # do everything event-based make TFLAGS=-n test-event lcov -d . -c -o cov.lcov genhtml cov.lcov --output-directory coverage --title "curl code coverage" tar -cjf curl-coverage.tar.bz2 coverage
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/contributors.sh
#!/bin/sh #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 2013-2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### # # This script shows all mentioned contributors from the given <hash>/<tag> # until HEAD and adds the contributors already mentioned in the existing # RELEASE-NOTES. # start=$1 if test "$start" = "-h"; then echo "Usage: $0 <since this tag/hash> [--releasenotes]" exit fi if test -z "$start"; then start=`git tag --sort=taggerdate | grep "^curl-" | tail -1`; echo "Since $start:" fi # We also include curl-www if possible. Override by setting CURLWWW if [ -z "$CURLWWW" ] ; then CURLWWW=../curl-www fi # filter out Author:, Commit: and *by: lines # cut off the email parts # split list of names at comma # split list of names at " and " # cut off spaces first and last on the line # filter alternatives through THANKS-filter # only count names with a space (ie more than one word) # sort all unique names # awk them into RELEASE-NOTES format ( ( git log --pretty=full --use-mailmap $start..HEAD if [ -d "$CURLWWW" ] then git -C ../curl-www log --pretty=full --use-mailmap $start..HEAD fi ) | \ egrep -ai '(^Author|^Commit|by):' | \ cut -d: -f2- | \ cut '-d(' -f1 | \ cut '-d<' -f1 | \ tr , '\012' | \ sed 's/ at github/ on github/' | \ sed 's/ and /\n/' | \ sed -e 's/^ //' -e 's/ $//g' -e 's/@users.noreply.github.com$/ on github/' grep -a "^ [^ \(]" RELEASE-NOTES| \ sed 's/, */\n/g'| \ sed 's/^ *//' )| \ sed -f ./docs/THANKS-filter | \ grep -a ' ' | \ sort -fu | \ awk '{ num++; n = sprintf("%s%s%s,", n, length(n)?" ":"", $0); #print n; if(length(n) > 77) { printf(" %s\n", p); n=sprintf("%s,", $0); } p=n; } END { printf(" %s\n", p); printf(" (%d contributors)\n", num); } '
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/installcheck.sh
#!/bin/bash #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### PREFIX=$1 # Run this script in the root of the git clone. Point out the install prefix # where 'make install' has already installed curl. if test -z "$1"; then echo "scripts/installcheck.sh [PREFIX]" exit fi diff -u <(find docs/libcurl/ -name "*.3" -printf "%f\n" | grep -v template| sort) <(find $PREFIX/share/man/ -name "*.3" -printf "%f\n" | sort) if test "$?" -ne "0"; then echo "ERROR: installed libcurl docs mismatch" exit 2 fi diff -u <(find include/ -name "*.h" -printf "%f\n" | sort) <(find $PREFIX/include/ -name "*.h" -printf "%f\n" | sort) if test "$?" -ne "0"; then echo "ERROR: installed include files mismatch" exit 1 fi echo "installcheck: installed libcurl docs and include files look good"
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/updatemanpages.pl
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### # Update man pages. use strict; use warnings; use Tie::File; # Data from the command line. my $curlver = $ARGV[0]; my $curldate = $ARGV[1]; # Directories and extensions. my @dirlist = ("docs/", "docs/libcurl/", "docs/libcurl/opts/", "tests/"); my @extlist = (".1", ".3"); my @excludelist = ("mk-ca-bundle.1", "template.3"); # Subroutines sub printargs{ # Print arguments and exit. print "usage: updatemanpages.pl <version> <date>\n"; exit; } sub getthline{ # Process file looking for .TH section. my $filename = shift; my $file_handle; my $file_line; # Open the file. open($file_handle, $filename); # Look for the .TH section, process it into an array, # modify it and write to file. tie(my @file_data, 'Tie::File', $filename); foreach my $file_data_line(@file_data) { if($file_data_line =~ /^.TH/) { $file_line = $file_data_line; last; } } # Close the file. close($file_handle); return $file_line; } sub extractth{ # Extract .TH section as an array. my $input = shift; # Split the line into an array. my @tharray; my $inputsize = length($input); my $inputcurrent = ""; my $quotemode = 0; for(my $inputseek = 0; $inputseek < $inputsize; $inputseek++) { if(substr($input, $inputseek, 1) eq " " && $quotemode eq 0) { push(@tharray, $inputcurrent); $inputcurrent = ""; next; } $inputcurrent = $inputcurrent . substr($input, $inputseek, 1); if(substr($input, $inputseek, 1) eq "\"") { if($quotemode eq 0) { $quotemode = 1; } else { $quotemode = 0; } } } if($inputcurrent ne "") { push(@tharray, $inputcurrent); } return @tharray; } sub getdate{ # Get the date from the .TH section. my $filename = shift; my $thline; my @tharray; my $date = ""; $thline = getthline($filename); # Return nothing if there is no .TH section found. if(!$thline || $thline eq "") { return ""; } @tharray = extractth($thline); # Remove the quotes at the start and end. $date = substr($tharray[3], 1, -1); return $date; } sub processth{ # Process .TH section. my $input = shift; my $date = shift; # Split the line into an array. my @tharray = extractth($input); # Alter the date. my $itemdate = "\""; $itemdate .= $date; $itemdate .= "\""; $tharray[3] = $itemdate; # Alter the item version. my $itemver = $tharray[4]; my $itemname = ""; for(my $itemnameseek = 1; $itemnameseek < length($itemver); $itemnameseek++) { if(substr($itemver, $itemnameseek, 1) eq " " || substr($itemver, $itemnameseek, 1) eq "\"") { last; } $itemname .= substr($itemver, $itemnameseek, 1); } $itemver = "\""; $itemver .= $itemname; $itemver .= " "; $itemver .= $curlver; $itemver .= "\""; $tharray[4] = $itemver; my $thoutput = ""; foreach my $thvalue (@tharray) { $thoutput .= $thvalue; $thoutput .= " "; } $thoutput =~ s/\s+$//; $thoutput .= "\n"; # Return updated string. return $thoutput; } sub processfile{ # Process file looking for .TH section. my $filename = shift; my $date = shift; my $file_handle; my $file_dist_handle; my $filename_dist; # Open a handle for the original file and a second file handle # for the dist file. $filename_dist = $filename . ".dist"; open($file_handle, $filename); open($file_dist_handle, ">" . $filename_dist); # Look for the .TH section, process it into an array, # modify it and write to file. tie(my @file_data, 'Tie::File', $filename); foreach my $file_data_line (@file_data) { if($file_data_line =~ /^.TH/) { my $file_dist_line = processth($file_data_line, $date); print $file_dist_handle $file_dist_line . "\n"; } else { print $file_dist_handle $file_data_line . "\n"; } } # Close the file. close($file_handle); close($file_dist_handle); } # Check that $curlver is set, otherwise print arguments and exit. if(!$curlver) { printargs(); } # check to see that the git command works, it requires git 2.6 something my $gitcheck = `git log -1 --date="format:%B %d, %Y" $dirlist[0] 2>/dev/null`; if(length($gitcheck) < 1) { print "git version too old or $dirlist[0] is a bad argument\n"; exit; } # Look in each directory. my $dir_handle; foreach my $dirname (@dirlist) { foreach my $extname (@extlist) { # Go through the directory looking for files ending with # the current extension. opendir($dir_handle, $dirname); my @filelist = grep(/.$extname$/i, readdir($dir_handle)); foreach my $file (@filelist) { # Skip if file is in exclude list. if(grep(/^$file$/, @excludelist)) { next; } # Load the file and get the date. my $filedate; # Check if dist version exists and load date from that # file if it does. if(-e ($dirname . $file . ".dist")) { $filedate = getdate(($dirname . $file . ".dist")); } else { $filedate = getdate(($dirname . $file)); } # Skip if value is empty. if(!$filedate || $filedate eq "") { next; } # Check the man page in the git repository. my $repodata = `LC_TIME=C git log -1 --date="format:%B %d, %Y" \\ --since="$filedate" $dirname$file | grep ^Date:`; # If there is output then update the man page # with the new date/version. # Process the file if there is output. if($repodata) { my $thisdate; if(!$curldate) { if($repodata =~ /^Date: +(.*)/) { $thisdate = $1; } else { print STDERR "Warning: " . ($dirname . $file) . ": found no " . "date\n"; } } else { $thisdate = $curldate; } processfile(($dirname . $file), $thisdate); print $dirname . $file . " page updated to $thisdate\n"; } } closedir($dir_handle); } } __END__ =pod =head1 updatemanpages.pl Updates the man pages with the version number and optional date. If the date isn't provided, the last modified date from git is used. =head2 USAGE updatemanpages.pl version [date] =head3 version Specifies version (required) =head3 date Specifies date (optional) =head2 SETTINGS =head3 @dirlist Specifies the list of directories to look for files in. =head3 @extlist Specifies the list of files with extensions to process. =head3 @excludelist Specifies the list of files to not process. =head2 NOTES This script is used during maketgz. =cut
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/completion.pl
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### use strict; use warnings; use Getopt::Long(); use Pod::Usage(); my $curl = 'curl'; my $shell = 'zsh'; my $help = 0; Getopt::Long::GetOptions( 'curl=s' => \$curl, 'shell=s' => \$shell, 'help' => \$help, ) or Pod::Usage::pod2usage(); Pod::Usage::pod2usage() if $help; my $regex = '\s+(?:(-[^\s]+),\s)?(--[^\s]+)\s*(\<.+?\>)?\s+(.*)'; my @opts = parse_main_opts('--help all', $regex); if ($shell eq 'fish') { print "# curl fish completion\n\n"; print qq{$_ \n} foreach (@opts); } elsif ($shell eq 'zsh') { my $opts_str; $opts_str .= qq{ $_ \\\n} foreach (@opts); chomp $opts_str; my $tmpl = <<"EOS"; #compdef curl # curl zsh completion local curcontext="\$curcontext" state state_descr line typeset -A opt_args local rc=1 _arguments -C -S \\ $opts_str '*:URL:_urls' && rc=0 return rc EOS print $tmpl; } else { die("Unsupported shell: $shell"); } sub parse_main_opts { my ($cmd, $regex) = @_; my @list; my @lines = call_curl($cmd); foreach my $line (@lines) { my ($short, $long, $arg, $desc) = ($line =~ /^$regex/) or next; my $option = ''; $arg =~ s/\:/\\\:/g if defined $arg; $desc =~ s/'/'\\''/g if defined $desc; $desc =~ s/\[/\\\[/g if defined $desc; $desc =~ s/\]/\\\]/g if defined $desc; $desc =~ s/\:/\\\:/g if defined $desc; if ($shell eq 'fish') { $option .= "complete --command curl"; $option .= " --short-option '" . strip_dash(trim($short)) . "'" if defined $short; $option .= " --long-option '" . strip_dash(trim($long)) . "'" if defined $long; $option .= " --description '" . strip_dash(trim($desc)) . "'" if defined $desc; } elsif ($shell eq 'zsh') { $option .= '{' . trim($short) . ',' if defined $short; $option .= trim($long) if defined $long; $option .= '}' if defined $short; $option .= '\'[' . trim($desc) . ']\'' if defined $desc; $option .= ":'$arg'" if defined $arg; $option .= ':_files' if defined $arg and ($arg eq '<file>' || $arg eq '<filename>' || $arg eq '<dir>'); } push @list, $option; } # Sort longest first, because zsh won't complete an option listed # after one that's a prefix of it. @list = sort { $a =~ /([^=]*)/; my $ma = $1; $b =~ /([^=]*)/; my $mb = $1; length($mb) <=> length($ma) } @list if $shell eq 'zsh'; return @list; } sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s }; sub strip_dash { my $s = shift; $s =~ s/^-+//g; return $s }; sub call_curl { my ($cmd) = @_; my $output = `"$curl" $cmd`; if ($? == -1) { die "Could not run curl: $!"; } elsif ((my $exit_code = $? >> 8) != 0) { die "curl returned $exit_code with output:\n$output"; } return split /\n/, $output; } __END__ =head1 NAME completion.pl - Generates tab-completion files for various shells =head1 SYNOPSIS completion.pl [options...] --curl path to curl executable --shell zsh/fish --help prints this help =cut
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/contrithanks.sh
#!/bin/sh #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 2013 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### # # This script shows all mentioned contributors from <hash> until HEAD and # puts them at the end of the THANKS document on stdout # start=$1 if test "$start" = "-h"; then echo "Usage: $0 <since this tag/hash>" exit fi if test -z "$start"; then start=`git tag --sort=taggerdate | grep "^curl-" | tail -1`; fi # We also include curl-www if possible. Override by setting CURLWWW if [ -z "$CURLWWW" ] ; then CURLWWW=../curl-www fi cat ./docs/THANKS ( ( git log --use-mailmap $start..HEAD if [ -d "$CURLWWW" ] then git -C ../curl-www log --use-mailmap $start..HEAD fi ) | \ egrep -ai '(^Author|^Commit|by):' | \ cut -d: -f2- | \ cut '-d(' -f1 | \ cut '-d<' -f1 | \ tr , '\012' | \ sed 's/ at github/ on github/' | \ sed 's/ and /\n/' | \ sed -e 's/^ //' -e 's/ $//g' -e 's/@users.noreply.github.com$/ on github/' # grep out the list of names from RELEASE-NOTES # split on ", " # remove leading whitespace grep -a "^ [^ (]" RELEASE-NOTES| \ sed 's/, */\n/g'| \ sed 's/^ *//' )| \ sed -f ./docs/THANKS-filter | \ grep -a ' ' | \ sort -fu | \ grep -aixvf ./docs/THANKS
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/log2changes.pl
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### # git log --pretty=fuller --no-color --date=short --decorate=full my @mname = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ); sub nicedate { my ($date)=$_; if($date =~ /(\d\d\d\d)-(\d\d)-(\d\d)/) { return sprintf("%d %s %4d", $3, $mname[$2-1], $1); } return $date; } print ' _ _ ____ _ ___| | | | _ \| | / __| | | | |_) | | | (__| |_| | _ <| |___ \___|\___/|_| \_\_____| Changelog '; my $line; my $tag; while(<STDIN>) { my $l = $_; if($l =~/^commit ([[:xdigit:]]*) ?(.*)/) { $co = $1; my $ref = $2; if ($ref =~ /refs\/tags\/curl-([0-9_]*)/) { $tag = $1; $tag =~ tr/_/./; } } elsif($l =~ /^Author: *(.*) +</) { $a = $1; } elsif($l =~ /^Commit: *(.*) +</) { $c = $1; } elsif($l =~ /^CommitDate: (.*)/) { $date = nicedate($1); } elsif($l =~ /^( )(.*)/) { my $extra; if ($tag) { # Version entries have a special format print "\nVersion " . $tag." ($date)\n"; $oldc = ""; $tag = ""; } if($a ne $c) { $extra=sprintf("\n- [%s brought this change]\n\n ", $a); } else { $extra="\n- "; } if($co ne $oldco) { if($c ne $oldc) { print "\n$c ($date)$extra"; } else { print "$extra"; } $line =0; } $oldco = $co; $oldc = $c; $olddate = $date; if($line++) { print " "; } print $2."\n"; } }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/singleuse.pl
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 2019 - 2021, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### # # This script is aimed to help scan for and detect globally declared functions # that are not used from other source files. # # Use it like this: # # $ ./scripts/singleuse.pl lib/.libs/libcurl.a # # Be aware that it might cause false positives due to various build options. # my $file = $ARGV[0]; my %wl = ( 'Curl_none_cert_status_request' => 'multiple TLS backends', 'Curl_none_check_cxn' => 'multiple TLS backends', 'Curl_none_cleanup' => 'multiple TLS backends', 'Curl_none_close_all' => 'multiple TLS backends', 'Curl_none_data_pending' => 'multiple TLS backends', 'Curl_none_engines_list' => 'multiple TLS backends', 'Curl_none_init' => 'multiple TLS backends', 'Curl_none_md5sum' => 'multiple TLS backends', 'Curl_none_random' => 'multiple TLS backends', 'Curl_none_session_free' => 'multiple TLS backends', 'Curl_none_set_engine' => 'multiple TLS backends', 'Curl_none_set_engine_default' => 'multiple TLS backends', 'Curl_none_shutdown' => 'multiple TLS backends', 'Curl_multi_dump' => 'debug build only', 'Curl_parse_port' => 'UNITTEST', 'Curl_shuffle_addr' => 'UNITTEST', 'de_cleanup' => 'UNITTEST', 'doh_decode' => 'UNITTEST', 'doh_encode' => 'UNITTEST', 'Curl_auth_digest_get_pair' => 'by digest_sspi', 'curlx_uztoso' => 'cmdline tool use', 'curlx_uztoul' => 'by krb5_sspi', 'curlx_uitous' => 'by schannel', 'Curl_islower' => 'by curl_fnmatch', 'getaddressinfo' => 'UNITTEST', ); my %api = ( 'curl_easy_cleanup' => 'API', 'curl_easy_duphandle' => 'API', 'curl_easy_escape' => 'API', 'curl_easy_getinfo' => 'API', 'curl_easy_init' => 'API', 'curl_easy_pause' => 'API', 'curl_easy_perform' => 'API', 'curl_easy_recv' => 'API', 'curl_easy_reset' => 'API', 'curl_easy_send' => 'API', 'curl_easy_setopt' => 'API', 'curl_easy_strerror' => 'API', 'curl_easy_unescape' => 'API', 'curl_easy_upkeep' => 'API', 'curl_easy_option_by_id' => 'API', 'curl_easy_option_by_name' => 'API', 'curl_easy_option_next' => 'API', 'curl_escape' => 'API', 'curl_formadd' => 'API', 'curl_formfree' => 'API', 'curl_formget' => 'API', 'curl_free' => 'API', 'curl_getdate' => 'API', 'curl_getenv' => 'API', 'curl_global_cleanup' => 'API', 'curl_global_init' => 'API', 'curl_global_init_mem' => 'API', 'curl_global_sslset' => 'API', 'curl_maprintf' => 'API', 'curl_mfprintf' => 'API', 'curl_mime_addpart' => 'API', 'curl_mime_data' => 'API', 'curl_mime_data_cb' => 'API', 'curl_mime_encoder' => 'API', 'curl_mime_filedata' => 'API', 'curl_mime_filename' => 'API', 'curl_mime_free' => 'API', 'curl_mime_headers' => 'API', 'curl_mime_init' => 'API', 'curl_mime_name' => 'API', 'curl_mime_subparts' => 'API', 'curl_mime_type' => 'API', 'curl_mprintf' => 'API', 'curl_msnprintf' => 'API', 'curl_msprintf' => 'API', 'curl_multi_add_handle' => 'API', 'curl_multi_assign' => 'API', 'curl_multi_cleanup' => 'API', 'curl_multi_fdset' => 'API', 'curl_multi_info_read' => 'API', 'curl_multi_init' => 'API', 'curl_multi_perform' => 'API', 'curl_multi_remove_handle' => 'API', 'curl_multi_setopt' => 'API', 'curl_multi_socket' => 'API', 'curl_multi_socket_action' => 'API', 'curl_multi_socket_all' => 'API', 'curl_multi_poll' => 'API', 'curl_multi_strerror' => 'API', 'curl_multi_timeout' => 'API', 'curl_multi_wait' => 'API', 'curl_multi_wakeup' => 'API', 'curl_mvaprintf' => 'API', 'curl_mvfprintf' => 'API', 'curl_mvprintf' => 'API', 'curl_mvsnprintf' => 'API', 'curl_mvsprintf' => 'API', 'curl_pushheader_byname' => 'API', 'curl_pushheader_bynum' => 'API', 'curl_share_cleanup' => 'API', 'curl_share_init' => 'API', 'curl_share_setopt' => 'API', 'curl_share_strerror' => 'API', 'curl_slist_append' => 'API', 'curl_slist_free_all' => 'API', 'curl_strequal' => 'API', 'curl_strnequal' => 'API', 'curl_unescape' => 'API', 'curl_url' => 'API', 'curl_url_cleanup' => 'API', 'curl_url_dup' => 'API', 'curl_url_get' => 'API', 'curl_url_set' => 'API', 'curl_url_strerror' => 'API', 'curl_version' => 'API', 'curl_version_info' => 'API', # the following functions are provided globally in debug builds 'curl_easy_perform_ev' => 'debug-build', ); open(N, "nm $file|") || die; my %exist; my %uses; my $file; while (<N>) { my $l = $_; chomp $l; if($l =~ /^([0-9a-z_-]+)\.o:/) { $file = $1; } if($l =~ /^([0-9a-f]+) T (.*)/) { my ($name)=($2); #print "Define $name in $file\n"; $file =~ s/^libcurl_la-//; $exist{$name} = $file; } elsif($l =~ /^ U (.*)/) { my ($name)=($1); #print "Uses $name in $file\n"; $uses{$name} .= "$file, "; } } close(N); my $err; for(sort keys %exist) { #printf "%s is defined in %s, used by: %s\n", $_, $exist{$_}, $uses{$_}; if(!$uses{$_}) { # this is a symbol with no "global" user if($_ =~ /^curl_dbg_/) { # we ignore the memdebug symbols } elsif($_ =~ /^curl_/) { if(!$api{$_}) { # not present in the API, or for debug-builds print STDERR "Bad curl-prefix: $_\n"; $err++; } } elsif($wl{$_}) { #print "$_ is WL\n"; } else { printf "%s is defined in %s, but not used outside\n", $_, $exist{$_}; $err++; } } elsif($_ =~ /^curl_/) { # global prefix, make sure it is "blessed" if(!$api{$_}) { # not present in the API, or for debug-builds if($_ !~ /^curl_dbg_/) { # ignore the memdebug symbols print STDERR "Bad curl-prefix $_\n"; $err++; } } } } exit $err;
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/release-notes.pl
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 2020 - 2021, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### ############################################### # # ==== How to use this script ==== # # 1. Get recent commits added to RELEASE-NOTES: # # $ ./scripts/release-notes.pl # # 2. Edit RELEASE-NOTES and remove all entries that don't belong. Unused # references below will be cleaned up in the next step. Make sure to move # "changes" up to the changes section. All entries will by default be listed # under bug-fixes as this script can't know where to put them. # # 3. Run the cleanup script and let it sort the entries and remove unused # references from lines you removed in step (2): # # $ ./scripts/release-notes.pl cleanup # # 4. Reload RELEASE-NOTES and verify that things look okay. The cleanup # procedure can and should be re-run when lines are removed or rephrased. # # 5. Run ./scripts/contributors.sh and update the contributor list of names # The list can also be extended or edited manually. # # 6. Run ./scripts/delta and update the contributor count at the top, and # double-check/update the other counters. # # 7. Commit the file using "RELEASE-NOTES: synced" as commit message. # ################################################ my $cleanup = ($ARGV[0] eq "cleanup"); my @gitlog=`git log @^{/RELEASE-NOTES:.synced}..` if(!$cleanup); my @releasenotes=`cat RELEASE-NOTES`; my @o; # the entire new RELEASE-NOTES my @refused; # [num] = [2 bits of use info] my @refs; # [number] = [URL] for my $l (@releasenotes) { if($l =~ /^ o .*\[(\d+)\]/) { # referenced, set bit 0 $refused[$1]=1; } elsif($l =~ /^ \[(\d+)\] = (.*)/) { # listed in a reference, set bit 1 $refused[$1] |= 2; $refs[$1] = $2; } } # Return a new fresh reference number sub getref { for my $r (1 .. $#refs) { if(!$refused[$r] & 1) { return $r; } } # add at the end return $#refs + 1; } # '#num' # 'num' # 'https://github.com/curl/curl/issues/6939' # 'https://github.com/curl/curl-www/issues/69' sub extract { my ($ref)=@_; if($ref =~ /^(\#|)(\d+)/) { # return the plain number return $2; } elsif($ref =~ /^https:\/\/github.com\/curl\/curl\/.*\/(\d+)/) { # return the plain number return $2; } else { # return the URL return $ref; } } my $short; my $first; for my $l (@gitlog) { chomp $l; if($l =~ /^commit/) { if($first) { onecommit($short); } # starts a new commit undef @fixes; undef @closes; undef @bug; $short = ""; $first = 0; } elsif(($l =~ /^ (.*)/) && !$first) { # first line $short = $1; $first = 1; push @line, $short; } elsif(($l =~ /^ (.*)/) && $first) { # not the first my $line = $1; if($line =~ /^Fixes(:|) *(.*)/i) { push @fixes, extract($2); } elsif($line =~ /^Clo(s|)es(:|) *(.*)/i) { push @closes, extract($3); } elsif($line =~ /^Bug: (.*)/i) { push @bug, extract($1); } } } if($first) { onecommit($short); } # call at the end of a parsed commit sub onecommit { my ($short)=@_; my $ref; if($bug[0]) { $ref = $bug[0]; } elsif($fixes[0]) { $ref = $fixes[0]; } elsif($closes[0]) { $ref = $closes[0]; } if($ref =~ /^#?(\d+)/) { $ref = "https://curl.se/bug/?i=$1" } if($ref) { my $r = getref(); $refs[$r] = $ref; $moreinfo{$short}=$r; $refused[$r] |= 1; } } #### Output the new RELEASE-NOTES my @bullets; for my $l (@releasenotes) { if(($l =~ /^This release includes the following bugfixes:/) && !$cleanup) { push @o, $l; push @o, "\n"; for my $f (@line) { push @o, sprintf " o %s%s\n", $f, $moreinfo{$f}? sprintf(" [%d]", $moreinfo{$f}): ""; $refused[$moreinfo{$f}]=3; } push @o, " --- new entries are listed above this ---"; next; } elsif($cleanup) { if($l =~ /^ --- new entries are listed/) { # ignore this if still around next; } elsif($l =~ /^ o .*/) { push @bullets, $l; next; } elsif($bullets[0]) { # output them case insensitively for my $b (sort { "\L$a" cmp "\L$b" } @bullets) { push @o, $b; } undef @bullets; } } if($l =~ /^ \[(\d+)\] = /) { # stop now last; } else { push @o, $l; } } my @srefs; my $ln; for my $n (1 .. $#refs) { my $r = $refs[$n]; if($r && ($refused[$n] & 1)) { push @o, sprintf " [%d] = %s\n", $n, $r; } } open(O, ">RELEASE-NOTES"); for my $l (@o) { print O $l; } close(O); exit; # Debug: show unused references for my $r (1 .. $#refs) { if($refused[$r] != 3) { printf "%s is %d!\n", $r, $refused[$r]; } }
0
repos/gpt4all.zig/src/zig-libcurl/curl/scripts
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/zuul/iconv-env.sh
#*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### export CPPFLAGS="-DCURL_DOES_CONVERSIONS -DHAVE_ICONV -DCURL_ICONV_CODESET_OF_HOST='\"ISO8859-1\"'"
0
repos/gpt4all.zig/src/zig-libcurl/curl/scripts
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/zuul/script.sh
#!/bin/bash #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### set -eo pipefail ./buildconf if [ "$T" = "coverage" ]; then ./configure --enable-debug --disable-shared --disable-threaded-resolver --enable-code-coverage --enable-werror --with-libssh2 make make TFLAGS=-n test-nonflaky make "TFLAGS=-n -e" test-nonflaky tests="1 200 300 500 700 800 900 1000 1100 1200 1302 1400 1502 3000" make "TFLAGS=-n -t $tests" test-nonflaky coveralls --gcov /usr/bin/gcov-8 --gcov-options '\-lp' -i src -e lib -e tests -e docs -b $PWD/src coveralls --gcov /usr/bin/gcov-8 --gcov-options '\-lp' -e src -i lib -e tests -e docs -b $PWD/lib fi if [ "$T" = "torture" ]; then ./configure --enable-debug --disable-shared --disable-threaded-resolver --enable-code-coverage --enable-werror --with-libssh2 --with-openssl make tests="!TLS-SRP !FTP" make "TFLAGS=-n --shallow=20 -t $tests" test-nonflaky fi if [ "$T" = "events" ]; then ./configure --enable-debug --disable-shared --disable-threaded-resolver --enable-code-coverage --enable-werror --with-libssh2 --with-openssl make tests="!TLS-SRP" make "TFLAGS=-n -e $tests" test-nonflaky fi if [ "$T" = "debug" ]; then ./configure --enable-debug --enable-werror $C make make examples if [ -z $NOTESTS ]; then make test-nonflaky fi fi if [ "$T" = "debug-wolfssl" ]; then ./configure --enable-debug --enable-werror $C make make "TFLAGS=-n !313" test-nonflaky fi if [ "$T" = "debug-mesalink" ]; then ./configure --enable-debug --enable-werror $C make make "TFLAGS=-n !313 !410 !3001" test-nonflaky fi if [ "$T" = "debug-rustls" ]; then ./configure --enable-debug --enable-werror $C make make "TFLAGS=HTTPS !313" test-nonflaky fi if [ "$T" = "debug-bearssl" ]; then ./configure --enable-debug --enable-werror $C make make "TFLAGS=-n !313" test-nonflaky fi if [ "$T" = "novalgrind" ]; then ./configure --enable-werror $C make make examples make TFLAGS=-n test-nonflaky fi if [ "$T" = "normal" ]; then if [ $TRAVIS_OS_NAME = linux ]; then # Remove system curl to make sure we don't rely on it. # Only done on Linux since we're not permitted to on mac. sudo rm -f /usr/bin/curl fi ./configure --enable-warnings --enable-werror $C make make examples if [ -z $NOTESTS ]; then make test-nonflaky fi if [ -n "$CHECKSRC" ]; then make checksrc fi fi if [ "$T" = "tidy" ]; then ./configure --enable-warnings --enable-werror $C make make tidy fi if [ "$T" = "iconv" ]; then source scripts/zuul/iconv-env.sh ./configure --enable-debug --enable-werror $C make make examples make test-nonflaky fi if [ "$T" = "cmake" ]; then cmake -H. -Bbuild -DCURL_WERROR=ON $C cmake --build build env TFLAGS="!1139 $TFLAGS" cmake --build build --target test-nonflaky fi if [ "$T" = "distcheck" ]; then # find BOM markers and exit if we do ! git grep `printf '\xef\xbb\xbf'` ./configure --without-ssl make ./maketgz 99.98.97 # verify in-tree build - and install it tar xf curl-99.98.97.tar.gz cd curl-99.98.97 ./configure --prefix=$HOME/temp --without-ssl make make TFLAGS=1 test make install # basic check of the installed files cd .. bash scripts/installcheck.sh $HOME/temp rm -rf curl-99.98.97 # verify out-of-tree build tar xf curl-99.98.97.tar.gz touch curl-99.98.97/docs/{cmdline-opts,libcurl}/Makefile.inc mkdir build cd build ../curl-99.98.97/configure --without-ssl make make TFLAGS='-p 1 1139' test # verify cmake build cd .. rm -rf curl-99.98.97 tar xf curl-99.98.97.tar.gz cd curl-99.98.97 mkdir build cd build cmake .. make cd ../.. fi if [ "$T" = "fuzzer" ]; then # Download the fuzzer to a temporary folder ./tests/fuzz/download_fuzzer.sh /tmp/curl_fuzzer export CURLSRC=$PWD # Run the mainline fuzzer test pushd /tmp/curl_fuzzer ./mainline.sh ${CURLSRC} popd fi if [ "$T" = "scan-build" ]; then scan-build ./configure --enable-debug --enable-werror $C scan-build --status-bugs make scan-build --status-bugs make examples fi
0
repos/gpt4all.zig/src/zig-libcurl/curl/scripts
repos/gpt4all.zig/src/zig-libcurl/curl/scripts/zuul/before_script.sh
#!/bin/bash #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### set -eo pipefail ./buildconf if [ "$NGTCP2" = yes ]; then if [ "$TRAVIS_OS_NAME" = linux -a "$GNUTLS" ]; then cd $HOME git clone --depth 1 https://gitlab.com/gnutls/nettle.git cd nettle ./.bootstrap ./configure LDFLAGS="-Wl,-rpath,$HOME/ngbuild/lib" --disable-documentation --prefix=$HOME/ngbuild make make install cd $HOME git clone --depth 1 https://gitlab.com/gnutls/gnutls.git pgtls cd pgtls ./bootstrap ./configure PKG_CONFIG_PATH=$HOME/ngbuild/lib/pkgconfig LDFLAGS="-Wl,-rpath,$HOME/ngbuild/lib" --with-included-libtasn1 --with-included-unistring --disable-guile --disable-doc --prefix=$HOME/ngbuild make make install else cd $HOME git clone --depth 1 -b OpenSSL_1_1_1j+quic https://github.com/quictls/openssl possl cd possl ./config enable-tls1_3 --prefix=$HOME/ngbuild make make install_sw fi cd $HOME git clone --depth 1 https://github.com/ngtcp2/nghttp3 cd nghttp3 autoreconf -i ./configure --prefix=$HOME/ngbuild --enable-lib-only make make install cd $HOME git clone --depth 1 https://github.com/ngtcp2/ngtcp2 cd ngtcp2 autoreconf -i if test -n "$GNUTLS"; then WITHGNUTLS="--with-gnutls" fi ./configure PKG_CONFIG_PATH=$HOME/ngbuild/lib/pkgconfig LDFLAGS="-Wl,-rpath,$HOME/ngbuild/lib" --prefix=$HOME/ngbuild --enable-lib-only $WITHGNUTLS make make install fi if [ "$TRAVIS_OS_NAME" = linux -a "$BORINGSSL" ]; then cd $HOME git clone --depth=1 https://boringssl.googlesource.com/boringssl cd boringssl CXX="g++" CC="gcc" cmake -H. -Bbuild -GNinja -DCMAKE_BUILD_TYPE=release -DBUILD_SHARED_LIBS=1 cmake --build build mkdir lib cp ./build/crypto/libcrypto.so ./lib/ cp ./build/ssl/libssl.so ./lib/ echo "BoringSSL lib dir: "`pwd`"/lib" cmake --build build --target clean rm -f build/CMakeCache.txt CXX="g++" CC="gcc" cmake -H. -Bbuild -GNinja -DCMAKE_POSITION_INDEPENDENT_CODE=on cmake --build build export LIBS=-lpthread fi if [ "$TRAVIS_OS_NAME" = linux -a "$OPENSSL3" ]; then cd $HOME git clone --depth=1 https://github.com/openssl/openssl cd openssl ./config enable-tls1_3 --prefix=$HOME/openssl3 make make install_sw fi if [ "$TRAVIS_OS_NAME" = linux -a "$MBEDTLS3" ]; then cd $HOME git clone --depth=1 -b v3.0.0 https://github.com/ARMmbed/mbedtls cd mbedtls make make DESTDIR=$HOME/mbedtls3 install fi if [ "$TRAVIS_OS_NAME" = linux -a "$LIBRESSL" ]; then cd $HOME git clone --depth=1 -b v3.1.4 https://github.com/libressl-portable/portable.git libressl-git cd libressl-git ./autogen.sh ./configure --prefix=$HOME/libressl make make install fi if [ "$TRAVIS_OS_NAME" = linux -a "$QUICHE" ]; then cd $HOME git clone --depth=1 --recursive https://github.com/cloudflare/quiche.git curl https://sh.rustup.rs -sSf | sh -s -- -y source $HOME/.cargo/env cd $HOME/quiche #### Work-around https://github.com/curl/curl/issues/7927 ####### #### See https://github.com/alexcrichton/cmake-rs/issues/131 #### sed -i -e 's/cmake = "0.1"/cmake = "=0.1.45"/' Cargo.toml cargo build -v --release --features ffi,pkg-config-meta,qlog mkdir -v deps/boringssl/src/lib ln -vnf $(find target/release -name libcrypto.a -o -name libssl.a) deps/boringssl/src/lib/ fi if [ "$TRAVIS_OS_NAME" = linux -a "$RUSTLS_VERSION" ]; then cd $HOME git clone --depth=1 --recursive https://github.com/rustls/rustls-ffi.git -b "$RUSTLS_VERSION" curl https://sh.rustup.rs -sSf | sh -s -- -y source $HOME/.cargo/env cargo install cbindgen cd $HOME/rustls-ffi make make DESTDIR=$HOME/crust install fi if [ $TRAVIS_OS_NAME = linux -a "$WOLFSSL" ]; then if [ ! -e $HOME/wolfssl-4.7.0-stable/Makefile ]; then cd $HOME curl -LO https://github.com/wolfSSL/wolfssl/archive/v4.7.0-stable.tar.gz tar -xzf v4.7.0-stable.tar.gz cd wolfssl-4.7.0-stable ./autogen.sh ./configure --enable-tls13 --enable-all touch wolfssl/wolfcrypt/fips.h make fi cd $HOME/wolfssl-4.7.0-stable sudo make install fi # Install common libraries. if [ $TRAVIS_OS_NAME = linux ]; then if [ "$MESALINK" = "yes" ]; then if [ ! -e $HOME/mesalink-1.0.0/Makefile ]; then cd $HOME curl https://sh.rustup.rs -sSf | sh -s -- -y source $HOME/.cargo/env curl -LO https://github.com/mesalock-linux/mesalink/archive/v1.0.0.tar.gz tar -xzf v1.0.0.tar.gz cd mesalink-1.0.0 ./autogen.sh ./configure --enable-tls13 make fi cd $HOME/mesalink-1.0.0 sudo make install fi if [ "$BEARSSL" = "yes" ]; then if [ ! -e $HOME/bearssl-0.6/Makefile ]; then cd $HOME curl -LO https://bearssl.org/bearssl-0.6.tar.gz tar -xzf bearssl-0.6.tar.gz cd bearssl-0.6 make fi cd $HOME/bearssl-0.6 sudo cp inc/*.h /usr/local/include sudo cp build/libbearssl.* /usr/local/lib fi fi
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_memrchr.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "curl_memrchr.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" #ifndef HAVE_MEMRCHR /* * Curl_memrchr() * * Our memrchr() function clone for systems which lack this function. The * memrchr() function is like the memchr() function, except that it searches * backwards from the end of the n bytes pointed to by s instead of forward * from the beginning. */ void * Curl_memrchr(const void *s, int c, size_t n) { if(n > 0) { const unsigned char *p = s; const unsigned char *q = s; p += n - 1; while(p >= q) { if(*p == (unsigned char)c) return (void *)p; p--; } } return NULL; } #endif /* HAVE_MEMRCHR */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/share.h
#ifndef HEADER_CURL_SHARE_H #define HEADER_CURL_SHARE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "cookie.h" #include "psl.h" #include "urldata.h" #include "conncache.h" /* SalfordC says "A structure member may not be volatile". Hence: */ #ifdef __SALFORDC__ #define CURL_VOLATILE #else #define CURL_VOLATILE volatile #endif #define CURL_GOOD_SHARE 0x7e117a1e #define GOOD_SHARE_HANDLE(x) ((x) && (x)->magic == CURL_GOOD_SHARE) /* this struct is libcurl-private, don't export details */ struct Curl_share { unsigned int magic; /* CURL_GOOD_SHARE */ unsigned int specifier; CURL_VOLATILE unsigned int dirty; curl_lock_function lockfunc; curl_unlock_function unlockfunc; void *clientdata; struct conncache conn_cache; struct Curl_hash hostcache; #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) struct CookieInfo *cookies; #endif #ifdef USE_LIBPSL struct PslCache psl; #endif struct Curl_ssl_session *sslsession; size_t max_ssl_sessions; long sessionage; }; CURLSHcode Curl_share_lock(struct Curl_easy *, curl_lock_data, curl_lock_access); CURLSHcode Curl_share_unlock(struct Curl_easy *, curl_lock_data); #endif /* HEADER_CURL_SHARE_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/select.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <limits.h> #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #elif defined(HAVE_UNISTD_H) #include <unistd.h> #endif #if !defined(HAVE_SELECT) && !defined(HAVE_POLL_FINE) #error "We can't compile without select() or poll() support." #endif #if defined(__BEOS__) && !defined(__HAIKU__) /* BeOS has FD_SET defined in socket.h */ #include <socket.h> #endif #ifdef MSDOS #include <dos.h> /* delay() */ #endif #ifdef __VXWORKS__ #include <strings.h> /* bzero() in FD_SET */ #endif #include <curl/curl.h> #include "urldata.h" #include "connect.h" #include "select.h" #include "timeval.h" #include "warnless.h" /* * Internal function used for waiting a specific amount of ms * in Curl_socket_check() and Curl_poll() when no file descriptor * is provided to wait on, just being used to delay execution. * WinSock select() and poll() timeout mechanisms need a valid * socket descriptor in a not null file descriptor set to work. * Waiting indefinitely with this function is not allowed, a * zero or negative timeout value will return immediately. * Timeout resolution, accuracy, as well as maximum supported * value is system dependent, neither factor is a critical issue * for the intended use of this function in the library. * * Return values: * -1 = system call error, invalid timeout value, or interrupted * 0 = specified timeout has elapsed */ int Curl_wait_ms(timediff_t timeout_ms) { int r = 0; if(!timeout_ms) return 0; if(timeout_ms < 0) { SET_SOCKERRNO(EINVAL); return -1; } #if defined(MSDOS) delay(timeout_ms); #elif defined(WIN32) /* prevent overflow, timeout_ms is typecast to ULONG/DWORD. */ #if TIMEDIFF_T_MAX >= ULONG_MAX if(timeout_ms >= ULONG_MAX) timeout_ms = ULONG_MAX-1; /* don't use ULONG_MAX, because that is equal to INFINITE */ #endif Sleep((ULONG)timeout_ms); #else #if defined(HAVE_POLL_FINE) /* prevent overflow, timeout_ms is typecast to int. */ #if TIMEDIFF_T_MAX > INT_MAX if(timeout_ms > INT_MAX) timeout_ms = INT_MAX; #endif r = poll(NULL, 0, (int)timeout_ms); #else { struct timeval pending_tv; timediff_t tv_sec = timeout_ms / 1000; timediff_t tv_usec = (timeout_ms % 1000) * 1000; /* max=999999 */ #ifdef HAVE_SUSECONDS_T #if TIMEDIFF_T_MAX > TIME_T_MAX /* tv_sec overflow check in case time_t is signed */ if(tv_sec > TIME_T_MAX) tv_sec = TIME_T_MAX; #endif pending_tv.tv_sec = (time_t)tv_sec; pending_tv.tv_usec = (suseconds_t)tv_usec; #else #if TIMEDIFF_T_MAX > INT_MAX /* tv_sec overflow check in case time_t is signed */ if(tv_sec > INT_MAX) tv_sec = INT_MAX; #endif pending_tv.tv_sec = (int)tv_sec; pending_tv.tv_usec = (int)tv_usec; #endif r = select(0, NULL, NULL, NULL, &pending_tv); } #endif /* HAVE_POLL_FINE */ #endif /* USE_WINSOCK */ if(r) r = -1; return r; } #ifndef HAVE_POLL_FINE /* * This is a wrapper around select() to aid in Windows compatibility. * A negative timeout value makes this function wait indefinitely, * unless no valid file descriptor is given, when this happens the * negative timeout is ignored and the function times out immediately. * * Return values: * -1 = system call error or fd >= FD_SETSIZE * 0 = timeout * N = number of signalled file descriptors */ static int our_select(curl_socket_t maxfd, /* highest socket number */ fd_set *fds_read, /* sockets ready for reading */ fd_set *fds_write, /* sockets ready for writing */ fd_set *fds_err, /* sockets with errors */ timediff_t timeout_ms) /* milliseconds to wait */ { struct timeval pending_tv; struct timeval *ptimeout; #ifdef USE_WINSOCK /* WinSock select() can't handle zero events. See the comment below. */ if((!fds_read || fds_read->fd_count == 0) && (!fds_write || fds_write->fd_count == 0) && (!fds_err || fds_err->fd_count == 0)) { /* no sockets, just wait */ return Curl_wait_ms(timeout_ms); } #endif ptimeout = &pending_tv; if(timeout_ms < 0) { ptimeout = NULL; } else if(timeout_ms > 0) { timediff_t tv_sec = timeout_ms / 1000; timediff_t tv_usec = (timeout_ms % 1000) * 1000; /* max=999999 */ #ifdef HAVE_SUSECONDS_T #if TIMEDIFF_T_MAX > TIME_T_MAX /* tv_sec overflow check in case time_t is signed */ if(tv_sec > TIME_T_MAX) tv_sec = TIME_T_MAX; #endif pending_tv.tv_sec = (time_t)tv_sec; pending_tv.tv_usec = (suseconds_t)tv_usec; #elif defined(WIN32) /* maybe also others in the future */ #if TIMEDIFF_T_MAX > LONG_MAX /* tv_sec overflow check on Windows there we know it is long */ if(tv_sec > LONG_MAX) tv_sec = LONG_MAX; #endif pending_tv.tv_sec = (long)tv_sec; pending_tv.tv_usec = (long)tv_usec; #else #if TIMEDIFF_T_MAX > INT_MAX /* tv_sec overflow check in case time_t is signed */ if(tv_sec > INT_MAX) tv_sec = INT_MAX; #endif pending_tv.tv_sec = (int)tv_sec; pending_tv.tv_usec = (int)tv_usec; #endif } else { pending_tv.tv_sec = 0; pending_tv.tv_usec = 0; } #ifdef USE_WINSOCK /* WinSock select() must not be called with an fd_set that contains zero fd flags, or it will return WSAEINVAL. But, it also can't be called with no fd_sets at all! From the documentation: Any two of the parameters, readfds, writefds, or exceptfds, can be given as null. At least one must be non-null, and any non-null descriptor set must contain at least one handle to a socket. It is unclear why WinSock doesn't just handle this for us instead of calling this an error. Luckily, with WinSock, we can _also_ ask how many bits are set on an fd_set. So, let's just check it beforehand. */ return select((int)maxfd + 1, fds_read && fds_read->fd_count ? fds_read : NULL, fds_write && fds_write->fd_count ? fds_write : NULL, fds_err && fds_err->fd_count ? fds_err : NULL, ptimeout); #else return select((int)maxfd + 1, fds_read, fds_write, fds_err, ptimeout); #endif } #endif /* * Wait for read or write events on a set of file descriptors. It uses poll() * when a fine poll() is available, in order to avoid limits with FD_SETSIZE, * otherwise select() is used. An error is returned if select() is being used * and a file descriptor is too large for FD_SETSIZE. * * A negative timeout value makes this function wait indefinitely, * unless no valid file descriptor is given, when this happens the * negative timeout is ignored and the function times out immediately. * * Return values: * -1 = system call error or fd >= FD_SETSIZE * 0 = timeout * [bitmask] = action as described below * * CURL_CSELECT_IN - first socket is readable * CURL_CSELECT_IN2 - second socket is readable * CURL_CSELECT_OUT - write socket is writable * CURL_CSELECT_ERR - an error condition occurred */ int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */ curl_socket_t readfd1, curl_socket_t writefd, /* socket to write to */ timediff_t timeout_ms) /* milliseconds to wait */ { struct pollfd pfd[3]; int num; int r; if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) && (writefd == CURL_SOCKET_BAD)) { /* no sockets, just wait */ return Curl_wait_ms(timeout_ms); } /* Avoid initial timestamp, avoid Curl_now() call, when elapsed time in this function does not need to be measured. This happens when function is called with a zero timeout or a negative timeout value indicating a blocking call should be performed. */ num = 0; if(readfd0 != CURL_SOCKET_BAD) { pfd[num].fd = readfd0; pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; pfd[num].revents = 0; num++; } if(readfd1 != CURL_SOCKET_BAD) { pfd[num].fd = readfd1; pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI; pfd[num].revents = 0; num++; } if(writefd != CURL_SOCKET_BAD) { pfd[num].fd = writefd; pfd[num].events = POLLWRNORM|POLLOUT|POLLPRI; pfd[num].revents = 0; num++; } r = Curl_poll(pfd, num, timeout_ms); if(r <= 0) return r; r = 0; num = 0; if(readfd0 != CURL_SOCKET_BAD) { if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP)) r |= CURL_CSELECT_IN; if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL)) r |= CURL_CSELECT_ERR; num++; } if(readfd1 != CURL_SOCKET_BAD) { if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP)) r |= CURL_CSELECT_IN2; if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL)) r |= CURL_CSELECT_ERR; num++; } if(writefd != CURL_SOCKET_BAD) { if(pfd[num].revents & (POLLWRNORM|POLLOUT)) r |= CURL_CSELECT_OUT; if(pfd[num].revents & (POLLERR|POLLHUP|POLLPRI|POLLNVAL)) r |= CURL_CSELECT_ERR; } return r; } /* * This is a wrapper around poll(). If poll() does not exist, then * select() is used instead. An error is returned if select() is * being used and a file descriptor is too large for FD_SETSIZE. * A negative timeout value makes this function wait indefinitely, * unless no valid file descriptor is given, when this happens the * negative timeout is ignored and the function times out immediately. * * Return values: * -1 = system call error or fd >= FD_SETSIZE * 0 = timeout * N = number of structures with non zero revent fields */ int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms) { #ifdef HAVE_POLL_FINE int pending_ms; #else fd_set fds_read; fd_set fds_write; fd_set fds_err; curl_socket_t maxfd; #endif bool fds_none = TRUE; unsigned int i; int r; if(ufds) { for(i = 0; i < nfds; i++) { if(ufds[i].fd != CURL_SOCKET_BAD) { fds_none = FALSE; break; } } } if(fds_none) { /* no sockets, just wait */ return Curl_wait_ms(timeout_ms); } /* Avoid initial timestamp, avoid Curl_now() call, when elapsed time in this function does not need to be measured. This happens when function is called with a zero timeout or a negative timeout value indicating a blocking call should be performed. */ #ifdef HAVE_POLL_FINE /* prevent overflow, timeout_ms is typecast to int. */ #if TIMEDIFF_T_MAX > INT_MAX if(timeout_ms > INT_MAX) timeout_ms = INT_MAX; #endif if(timeout_ms > 0) pending_ms = (int)timeout_ms; else if(timeout_ms < 0) pending_ms = -1; else pending_ms = 0; r = poll(ufds, nfds, pending_ms); if(r <= 0) return r; for(i = 0; i < nfds; i++) { if(ufds[i].fd == CURL_SOCKET_BAD) continue; if(ufds[i].revents & POLLHUP) ufds[i].revents |= POLLIN; if(ufds[i].revents & POLLERR) ufds[i].revents |= POLLIN|POLLOUT; } #else /* HAVE_POLL_FINE */ FD_ZERO(&fds_read); FD_ZERO(&fds_write); FD_ZERO(&fds_err); maxfd = (curl_socket_t)-1; for(i = 0; i < nfds; i++) { ufds[i].revents = 0; if(ufds[i].fd == CURL_SOCKET_BAD) continue; VERIFY_SOCK(ufds[i].fd); if(ufds[i].events & (POLLIN|POLLOUT|POLLPRI| POLLRDNORM|POLLWRNORM|POLLRDBAND)) { if(ufds[i].fd > maxfd) maxfd = ufds[i].fd; if(ufds[i].events & (POLLRDNORM|POLLIN)) FD_SET(ufds[i].fd, &fds_read); if(ufds[i].events & (POLLWRNORM|POLLOUT)) FD_SET(ufds[i].fd, &fds_write); if(ufds[i].events & (POLLRDBAND|POLLPRI)) FD_SET(ufds[i].fd, &fds_err); } } /* Note also that WinSock ignores the first argument, so we don't worry about the fact that maxfd is computed incorrectly with WinSock (since curl_socket_t is unsigned in such cases and thus -1 is the largest value). */ r = our_select(maxfd, &fds_read, &fds_write, &fds_err, timeout_ms); if(r <= 0) return r; r = 0; for(i = 0; i < nfds; i++) { ufds[i].revents = 0; if(ufds[i].fd == CURL_SOCKET_BAD) continue; if(FD_ISSET(ufds[i].fd, &fds_read)) { if(ufds[i].events & POLLRDNORM) ufds[i].revents |= POLLRDNORM; if(ufds[i].events & POLLIN) ufds[i].revents |= POLLIN; } if(FD_ISSET(ufds[i].fd, &fds_write)) { if(ufds[i].events & POLLWRNORM) ufds[i].revents |= POLLWRNORM; if(ufds[i].events & POLLOUT) ufds[i].revents |= POLLOUT; } if(FD_ISSET(ufds[i].fd, &fds_err)) { if(ufds[i].events & POLLRDBAND) ufds[i].revents |= POLLRDBAND; if(ufds[i].events & POLLPRI) ufds[i].revents |= POLLPRI; } if(ufds[i].revents) r++; } #endif /* HAVE_POLL_FINE */ return r; } #ifdef TPF /* * This is a replacement for select() on the TPF platform. * It is used whenever libcurl calls select(). * The call below to tpf_process_signals() is required because * TPF's select calls are not signal interruptible. * * Return values are the same as select's. */ int tpf_select_libcurl(int maxfds, fd_set *reads, fd_set *writes, fd_set *excepts, struct timeval *tv) { int rc; rc = tpf_select_bsd(maxfds, reads, writes, excepts, tv); tpf_process_signals(); return rc; } #endif /* TPF */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/pop3.h
#ifndef HEADER_CURL_POP3_H #define HEADER_CURL_POP3_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2009 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "pingpong.h" #include "curl_sasl.h" /**************************************************************************** * POP3 unique setup ***************************************************************************/ typedef enum { POP3_STOP, /* do nothing state, stops the state machine */ POP3_SERVERGREET, /* waiting for the initial greeting immediately after a connect */ POP3_CAPA, POP3_STARTTLS, POP3_UPGRADETLS, /* asynchronously upgrade the connection to SSL/TLS (multi mode only) */ POP3_AUTH, POP3_APOP, POP3_USER, POP3_PASS, POP3_COMMAND, POP3_QUIT, POP3_LAST /* never used */ } pop3state; /* This POP3 struct is used in the Curl_easy. All POP3 data that is connection-oriented must be in pop3_conn to properly deal with the fact that perhaps the Curl_easy is changed between the times the connection is used. */ struct POP3 { curl_pp_transfer transfer; char *id; /* Message ID */ char *custom; /* Custom Request */ }; /* pop3_conn is used for struct connection-oriented data in the connectdata struct */ struct pop3_conn { struct pingpong pp; pop3state state; /* Always use pop3.c:state() to change state! */ bool ssldone; /* Is connect() over SSL done? */ bool tls_supported; /* StartTLS capability supported by server */ size_t eob; /* Number of bytes of the EOB (End Of Body) that have been received so far */ size_t strip; /* Number of bytes from the start to ignore as non-body */ struct SASL sasl; /* SASL-related storage */ unsigned int authtypes; /* Accepted authentication types */ unsigned int preftype; /* Preferred authentication type */ char *apoptimestamp; /* APOP timestamp from the server greeting */ }; extern const struct Curl_handler Curl_handler_pop3; extern const struct Curl_handler Curl_handler_pop3s; /* Authentication type flags */ #define POP3_TYPE_CLEARTEXT (1 << 0) #define POP3_TYPE_APOP (1 << 1) #define POP3_TYPE_SASL (1 << 2) /* Authentication type values */ #define POP3_TYPE_NONE 0 #define POP3_TYPE_ANY ~0U /* This is the 5-bytes End-Of-Body marker for POP3 */ #define POP3_EOB "\x0d\x0a\x2e\x0d\x0a" #define POP3_EOB_LEN 5 /* This function scans the body after the end-of-body and writes everything * until the end is found */ CURLcode Curl_pop3_write(struct Curl_easy *data, char *str, size_t nread); #endif /* HEADER_CURL_POP3_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/sockaddr.h
#ifndef HEADER_CURL_SOCKADDR_H #define HEADER_CURL_SOCKADDR_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" struct Curl_sockaddr_storage { union { struct sockaddr sa; struct sockaddr_in sa_in; #ifdef ENABLE_IPV6 struct sockaddr_in6 sa_in6; #endif #ifdef HAVE_STRUCT_SOCKADDR_STORAGE struct sockaddr_storage sa_stor; #else char cbuf[256]; /* this should be big enough to fit a lot */ #endif } buffer; }; #endif /* HEADER_CURL_SOCKADDR_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/tftp.h
#ifndef HEADER_CURL_TFTP_H #define HEADER_CURL_TFTP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_TFTP extern const struct Curl_handler Curl_handler_tftp; #endif #endif /* HEADER_CURL_TFTP_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/config-win32ce.h
#ifndef HEADER_CURL_CONFIG_WIN32CE_H #define HEADER_CURL_CONFIG_WIN32CE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* ================================================================ */ /* lib/config-win32ce.h - Hand crafted config file for windows ce */ /* ================================================================ */ /* ---------------------------------------------------------------- */ /* HEADER FILES */ /* ---------------------------------------------------------------- */ /* Define if you have the <arpa/inet.h> header file. */ /* #define HAVE_ARPA_INET_H 1 */ /* Define if you have the <assert.h> header file. */ /* #define HAVE_ASSERT_H 1 */ /* Define if you have the <errno.h> header file. */ /* #define HAVE_ERRNO_H 1 */ /* Define if you have the <fcntl.h> header file. */ #define HAVE_FCNTL_H 1 /* Define if you have the <getopt.h> header file. */ /* #define HAVE_GETOPT_H 1 */ /* Define if you have the <io.h> header file. */ #define HAVE_IO_H 1 /* Define if you need the malloc.h header file even with stdlib.h */ #define NEED_MALLOC_H 1 /* Define if you have the <netdb.h> header file. */ /* #define HAVE_NETDB_H 1 */ /* Define if you have the <netinet/in.h> header file. */ /* #define HAVE_NETINET_IN_H 1 */ /* Define if you have the <signal.h> header file. */ #define HAVE_SIGNAL_H 1 /* Define if you have the <ssl.h> header file. */ /* #define HAVE_SSL_H 1 */ /* Define if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define if you have the <process.h> header file. */ /* #define HAVE_PROCESS_H 1 */ /* Define if you have the <sys/param.h> header file. */ /* #define HAVE_SYS_PARAM_H 1 */ /* Define if you have the <sys/select.h> header file. */ /* #define HAVE_SYS_SELECT_H 1 */ /* Define if you have the <sys/socket.h> header file. */ /* #define HAVE_SYS_SOCKET_H 1 */ /* Define if you have the <sys/sockio.h> header file. */ /* #define HAVE_SYS_SOCKIO_H 1 */ /* Define if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define if you have the <sys/time.h> header file */ /* #define HAVE_SYS_TIME_H 1 */ /* Define if you have the <sys/types.h> header file. */ /* #define HAVE_SYS_TYPES_H 1 */ /* Define if you have the <sys/utime.h> header file */ #define HAVE_SYS_UTIME_H 1 /* Define if you have the <termio.h> header file. */ /* #define HAVE_TERMIO_H 1 */ /* Define if you have the <termios.h> header file. */ /* #define HAVE_TERMIOS_H 1 */ /* Define if you have the <time.h> header file. */ #define HAVE_TIME_H 1 /* Define if you have the <unistd.h> header file. */ #if defined(__MINGW32__) || defined(__WATCOMC__) || defined(__LCC__) #define HAVE_UNISTD_H 1 #endif /* Define if you have the <windows.h> header file. */ #define HAVE_WINDOWS_H 1 /* Define if you have the <winsock2.h> header file. */ #define HAVE_WINSOCK2_H 1 /* Define if you have the <ws2tcpip.h> header file. */ #define HAVE_WS2TCPIP_H 1 /* ---------------------------------------------------------------- */ /* OTHER HEADER INFO */ /* ---------------------------------------------------------------- */ /* Define if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define if you can safely include both <sys/time.h> and <time.h>. */ /* #define TIME_WITH_SYS_TIME 1 */ /* ---------------------------------------------------------------- */ /* FUNCTIONS */ /* ---------------------------------------------------------------- */ /* Define if you have the closesocket function. */ #define HAVE_CLOSESOCKET 1 /* Define if you don't have vprintf but do have _doprnt. */ /* #define HAVE_DOPRNT 1 */ /* Define if you have the gethostname function. */ #define HAVE_GETHOSTNAME 1 /* Define if you have the getpass function. */ /* #define HAVE_GETPASS 1 */ /* Define if you have the getservbyname function. */ #define HAVE_GETSERVBYNAME 1 /* Define if you have the gettimeofday function. */ /* #define HAVE_GETTIMEOFDAY 1 */ /* Define if you have the inet_addr function. */ #define HAVE_INET_ADDR 1 /* Define if you have the ioctlsocket function. */ #define HAVE_IOCTLSOCKET 1 /* Define if you have a working ioctlsocket FIONBIO function. */ #define HAVE_IOCTLSOCKET_FIONBIO 1 /* Define if you have the RAND_screen function when using SSL */ #define HAVE_RAND_SCREEN 1 /* Define if you have the `RAND_status' function when using SSL. */ #define HAVE_RAND_STATUS 1 /* Define if you have the select function. */ #define HAVE_SELECT 1 /* Define if you have the setvbuf function. */ #define HAVE_SETVBUF 1 /* Define if you have the socket function. */ #define HAVE_SOCKET 1 /* Define if you have the strcasecmp function. */ /* #define HAVE_STRCASECMP 1 */ /* Define if you have the strdup function. */ /* #define HAVE_STRDUP 1 */ /* Define if you have the strftime function. */ /* #define HAVE_STRFTIME 1 */ /* Define if you have the stricmp function. */ /* #define HAVE_STRICMP 1 */ /* Define if you have the strnicmp function. */ /* #define HAVE_STRNICMP 1 */ /* Define if you have the strstr function. */ #define HAVE_STRSTR 1 /* Define if you have the strtoll function. */ #if defined(__MINGW32__) || defined(__WATCOMC__) #define HAVE_STRTOLL 1 #endif /* Define if you have the utime function */ #define HAVE_UTIME 1 /* Define if you have the recv function. */ #define HAVE_RECV 1 /* Define to the type of arg 1 for recv. */ #define RECV_TYPE_ARG1 SOCKET /* Define to the type of arg 2 for recv. */ #define RECV_TYPE_ARG2 char * /* Define to the type of arg 3 for recv. */ #define RECV_TYPE_ARG3 int /* Define to the type of arg 4 for recv. */ #define RECV_TYPE_ARG4 int /* Define to the function return type for recv. */ #define RECV_TYPE_RETV int /* Define if you have the recvfrom function. */ #define HAVE_RECVFROM 1 /* Define to the type of arg 1 for recvfrom. */ #define RECVFROM_TYPE_ARG1 SOCKET /* Define to the type pointed by arg 2 for recvfrom. */ #define RECVFROM_TYPE_ARG2 char /* Define to the type of arg 3 for recvfrom. */ #define RECVFROM_TYPE_ARG3 int /* Define to the type of arg 4 for recvfrom. */ #define RECVFROM_TYPE_ARG4 int /* Define to the type pointed by arg 5 for recvfrom. */ #define RECVFROM_TYPE_ARG5 struct sockaddr /* Define to the type pointed by arg 6 for recvfrom. */ #define RECVFROM_TYPE_ARG6 int /* Define to the function return type for recvfrom. */ #define RECVFROM_TYPE_RETV int /* Define if you have the send function. */ #define HAVE_SEND 1 /* Define to the type of arg 1 for send. */ #define SEND_TYPE_ARG1 SOCKET /* Define to the type qualifier of arg 2 for send. */ #define SEND_QUAL_ARG2 const /* Define to the type of arg 2 for send. */ #define SEND_TYPE_ARG2 char * /* Define to the type of arg 3 for send. */ #define SEND_TYPE_ARG3 int /* Define to the type of arg 4 for send. */ #define SEND_TYPE_ARG4 int /* Define to the function return type for send. */ #define SEND_TYPE_RETV int /* ---------------------------------------------------------------- */ /* TYPEDEF REPLACEMENTS */ /* ---------------------------------------------------------------- */ /* Define this if in_addr_t is not an available 'typedefed' type */ #define in_addr_t unsigned long /* Define ssize_t if it is not an available 'typedefed' type */ #if (defined(__WATCOMC__) && (__WATCOMC__ >= 1240)) || defined(__POCC__) #elif defined(_WIN64) #define ssize_t __int64 #else #define ssize_t int #endif /* ---------------------------------------------------------------- */ /* TYPE SIZES */ /* ---------------------------------------------------------------- */ /* The size of `int', as computed by sizeof. */ #define SIZEOF_INT 4 /* The size of `long double', as computed by sizeof. */ #define SIZEOF_LONG_DOUBLE 16 /* The size of `long long', as computed by sizeof. */ /* #define SIZEOF_LONG_LONG 8 */ /* The size of `short', as computed by sizeof. */ #define SIZEOF_SHORT 2 /* Define to the size of `long', as computed by sizeof. */ #define SIZEOF_LONG 4 /* The size of `size_t', as computed by sizeof. */ #if defined(_WIN64) # define SIZEOF_SIZE_T 8 #else # define SIZEOF_SIZE_T 4 #endif /* ---------------------------------------------------------------- */ /* STRUCT RELATED */ /* ---------------------------------------------------------------- */ /* Define this if you have struct sockaddr_storage */ /* #define HAVE_STRUCT_SOCKADDR_STORAGE 1 */ /* Define this if you have struct timeval */ #define HAVE_STRUCT_TIMEVAL 1 /* Define this if struct sockaddr_in6 has the sin6_scope_id member */ #define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 /* ---------------------------------------------------------------- */ /* COMPILER SPECIFIC */ /* ---------------------------------------------------------------- */ /* Undef keyword 'const' if it does not work. */ /* #undef const */ /* Define to avoid VS2005 complaining about portable C functions */ #if defined(_MSC_VER) && (_MSC_VER >= 1400) #define _CRT_SECURE_NO_DEPRECATE 1 #define _CRT_NONSTDC_NO_DEPRECATE 1 #endif /* VS2005 and later default size for time_t is 64-bit, unless */ /* _USE_32BIT_TIME_T has been defined to get a 32-bit time_t. */ #if defined(_MSC_VER) && (_MSC_VER >= 1400) # ifndef _USE_32BIT_TIME_T # define SIZEOF_TIME_T 8 # else # define SIZEOF_TIME_T 4 # endif #endif /* ---------------------------------------------------------------- */ /* LARGE FILE SUPPORT */ /* ---------------------------------------------------------------- */ #if defined(_MSC_VER) && !defined(_WIN32_WCE) # if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) # define USE_WIN32_LARGE_FILES # else # define USE_WIN32_SMALL_FILES # endif #endif #if !defined(USE_WIN32_LARGE_FILES) && !defined(USE_WIN32_SMALL_FILES) # define USE_WIN32_SMALL_FILES #endif /* ---------------------------------------------------------------- */ /* LDAP SUPPORT */ /* ---------------------------------------------------------------- */ #define USE_WIN32_LDAP 1 #undef HAVE_LDAP_URL_PARSE /* ---------------------------------------------------------------- */ /* ADDITIONAL DEFINITIONS */ /* ---------------------------------------------------------------- */ /* Define cpu-machine-OS */ #undef OS #define OS "i386-pc-win32ce" /* Name of package */ #define PACKAGE "curl" /* ---------------------------------------------------------------- */ /* WinCE */ /* ---------------------------------------------------------------- */ #ifndef UNICODE # define UNICODE #endif #ifndef _UNICODE # define _UNICODE #endif #define CURL_DISABLE_FILE 1 #define CURL_DISABLE_TELNET 1 #define CURL_DISABLE_LDAP 1 #define ENOSPC 1 #define ENOMEM 2 #define EAGAIN 3 extern int stat(const char *path, struct stat *buffer); #endif /* HEADER_CURL_CONFIG_WIN32CE_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/ldap.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_LDAP) && !defined(USE_OPENLDAP) /* * Notice that USE_OPENLDAP is only a source code selection switch. When * libcurl is built with USE_OPENLDAP defined the libcurl source code that * gets compiled is the code from openldap.c, otherwise the code that gets * compiled is the code from ldap.c. * * When USE_OPENLDAP is defined a recent version of the OpenLDAP library * might be required for compilation and runtime. In order to use ancient * OpenLDAP library versions, USE_OPENLDAP shall not be defined. */ #ifdef USE_WIN32_LDAP /* Use Windows LDAP implementation. */ # include <winldap.h> # ifndef LDAP_VENDOR_NAME # error Your Platform SDK is NOT sufficient for LDAP support! \ Update your Platform SDK, or disable LDAP support! # else # include <winber.h> # endif #else # define LDAP_DEPRECATED 1 /* Be sure ldap_init() is defined. */ # ifdef HAVE_LBER_H # include <lber.h> # endif # include <ldap.h> # if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H)) # include <ldap_ssl.h> # endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */ #endif #include "urldata.h" #include <curl/curl.h> #include "sendf.h" #include "escape.h" #include "progress.h" #include "transfer.h" #include "strcase.h" #include "strtok.h" #include "curl_ldap.h" #include "curl_multibyte.h" #include "curl_base64.h" #include "connect.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #ifndef HAVE_LDAP_URL_PARSE /* Use our own implementation. */ struct ldap_urldesc { char *lud_host; int lud_port; #if defined(USE_WIN32_LDAP) TCHAR *lud_dn; TCHAR **lud_attrs; #else char *lud_dn; char **lud_attrs; #endif int lud_scope; #if defined(USE_WIN32_LDAP) TCHAR *lud_filter; #else char *lud_filter; #endif char **lud_exts; size_t lud_attrs_dups; /* how many were dup'ed, this field is not in the "real" struct so can only be used in code without HAVE_LDAP_URL_PARSE defined */ }; #undef LDAPURLDesc #define LDAPURLDesc struct ldap_urldesc static int _ldap_url_parse(struct Curl_easy *data, const struct connectdata *conn, LDAPURLDesc **ludp); static void _ldap_free_urldesc(LDAPURLDesc *ludp); #undef ldap_free_urldesc #define ldap_free_urldesc _ldap_free_urldesc #endif #ifdef DEBUG_LDAP #define LDAP_TRACE(x) do { \ _ldap_trace("%u: ", __LINE__); \ _ldap_trace x; \ } while(0) static void _ldap_trace(const char *fmt, ...); #else #define LDAP_TRACE(x) Curl_nop_stmt #endif #if defined(USE_WIN32_LDAP) && defined(ldap_err2string) /* Use ansi error strings in UNICODE builds */ #undef ldap_err2string #define ldap_err2string ldap_err2stringA #endif static CURLcode ldap_do(struct Curl_easy *data, bool *done); /* * LDAP protocol handler. */ const struct Curl_handler Curl_handler_ldap = { "LDAP", /* scheme */ ZERO_NULL, /* setup_connection */ ldap_do, /* do_it */ ZERO_NULL, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ ZERO_NULL, /* attach connection */ PORT_LDAP, /* defport */ CURLPROTO_LDAP, /* protocol */ CURLPROTO_LDAP, /* family */ PROTOPT_NONE /* flags */ }; #ifdef HAVE_LDAP_SSL /* * LDAPS protocol handler. */ const struct Curl_handler Curl_handler_ldaps = { "LDAPS", /* scheme */ ZERO_NULL, /* setup_connection */ ldap_do, /* do_it */ ZERO_NULL, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ ZERO_NULL, /* attach connection */ PORT_LDAPS, /* defport */ CURLPROTO_LDAPS, /* protocol */ CURLPROTO_LDAP, /* family */ PROTOPT_SSL /* flags */ }; #endif #if defined(USE_WIN32_LDAP) #if defined(USE_WINDOWS_SSPI) static int ldap_win_bind_auth(LDAP *server, const char *user, const char *passwd, unsigned long authflags) { ULONG method = 0; SEC_WINNT_AUTH_IDENTITY cred; int rc = LDAP_AUTH_METHOD_NOT_SUPPORTED; memset(&cred, 0, sizeof(cred)); #if defined(USE_SPNEGO) if(authflags & CURLAUTH_NEGOTIATE) { method = LDAP_AUTH_NEGOTIATE; } else #endif #if defined(USE_NTLM) if(authflags & CURLAUTH_NTLM) { method = LDAP_AUTH_NTLM; } else #endif #if !defined(CURL_DISABLE_CRYPTO_AUTH) if(authflags & CURLAUTH_DIGEST) { method = LDAP_AUTH_DIGEST; } else #endif { /* required anyway if one of upper preprocessor definitions enabled */ } if(method && user && passwd) { rc = Curl_create_sspi_identity(user, passwd, &cred); if(!rc) { rc = ldap_bind_s(server, NULL, (TCHAR *)&cred, method); Curl_sspi_free_identity(&cred); } } else { /* proceed with current user credentials */ method = LDAP_AUTH_NEGOTIATE; rc = ldap_bind_s(server, NULL, NULL, method); } return rc; } #endif /* #if defined(USE_WINDOWS_SSPI) */ static int ldap_win_bind(struct Curl_easy *data, LDAP *server, const char *user, const char *passwd) { int rc = LDAP_INVALID_CREDENTIALS; PTCHAR inuser = NULL; PTCHAR inpass = NULL; if(user && passwd && (data->set.httpauth & CURLAUTH_BASIC)) { inuser = curlx_convert_UTF8_to_tchar((char *) user); inpass = curlx_convert_UTF8_to_tchar((char *) passwd); rc = ldap_simple_bind_s(server, inuser, inpass); curlx_unicodefree(inuser); curlx_unicodefree(inpass); } #if defined(USE_WINDOWS_SSPI) else { rc = ldap_win_bind_auth(server, user, passwd, data->set.httpauth); } #endif return rc; } #endif /* #if defined(USE_WIN32_LDAP) */ #if defined(USE_WIN32_LDAP) #define FREE_ON_WINLDAP(x) curlx_unicodefree(x) #else #define FREE_ON_WINLDAP(x) #endif static CURLcode ldap_do(struct Curl_easy *data, bool *done) { CURLcode result = CURLE_OK; int rc = 0; LDAP *server = NULL; LDAPURLDesc *ludp = NULL; LDAPMessage *ldapmsg = NULL; LDAPMessage *entryIterator; int num = 0; struct connectdata *conn = data->conn; int ldap_proto = LDAP_VERSION3; int ldap_ssl = 0; char *val_b64 = NULL; size_t val_b64_sz = 0; curl_off_t dlsize = 0; #ifdef LDAP_OPT_NETWORK_TIMEOUT struct timeval ldap_timeout = {10, 0}; /* 10 sec connection/search timeout */ #endif #if defined(USE_WIN32_LDAP) TCHAR *host = NULL; #else char *host = NULL; #endif char *user = NULL; char *passwd = NULL; *done = TRUE; /* unconditionally */ infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d", LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION); infof(data, "LDAP local: %s", data->state.url); #ifdef HAVE_LDAP_URL_PARSE rc = ldap_url_parse(data->state.url, &ludp); #else rc = _ldap_url_parse(data, conn, &ludp); #endif if(rc) { failf(data, "LDAP local: %s", ldap_err2string(rc)); result = CURLE_LDAP_INVALID_URL; goto quit; } /* Get the URL scheme (either ldap or ldaps) */ if(conn->given->flags & PROTOPT_SSL) ldap_ssl = 1; infof(data, "LDAP local: trying to establish %s connection", ldap_ssl ? "encrypted" : "cleartext"); #if defined(USE_WIN32_LDAP) host = curlx_convert_UTF8_to_tchar(conn->host.name); if(!host) { result = CURLE_OUT_OF_MEMORY; goto quit; } #else host = conn->host.name; #endif if(conn->bits.user_passwd) { user = conn->user; passwd = conn->passwd; } #ifdef LDAP_OPT_NETWORK_TIMEOUT ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout); #endif ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); if(ldap_ssl) { #ifdef HAVE_LDAP_SSL #ifdef USE_WIN32_LDAP /* Win32 LDAP SDK doesn't support insecure mode without CA! */ server = ldap_sslinit(host, (int)conn->port, 1); ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON); #else int ldap_option; char *ldap_ca = conn->ssl_config.CAfile; #if defined(CURL_HAS_NOVELL_LDAPSDK) rc = ldapssl_client_init(NULL, NULL); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } if(conn->ssl_config.verifypeer) { /* Novell SDK supports DER or BASE64 files. */ int cert_type = LDAPSSL_CERT_FILETYPE_B64; if((data->set.ssl.cert_type) && (strcasecompare(data->set.ssl.cert_type, "DER"))) cert_type = LDAPSSL_CERT_FILETYPE_DER; if(!ldap_ca) { failf(data, "LDAP local: ERROR %s CA cert not set!", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM")); result = CURLE_SSL_CERTPROBLEM; goto quit; } infof(data, "LDAP local: using %s CA cert '%s'", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), ldap_ca); rc = ldapssl_add_trusted_cert(ldap_ca, cert_type); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting %s CA cert: %s", (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"), ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } ldap_option = LDAPSSL_VERIFY_SERVER; } else ldap_option = LDAPSSL_VERIFY_NONE; rc = ldapssl_set_verify_mode(ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting cert verify mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } server = ldapssl_init(host, (int)conn->port, 1); if(!server) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.dispname, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } #elif defined(LDAP_OPT_X_TLS) if(conn->ssl_config.verifypeer) { /* OpenLDAP SDK supports BASE64 files. */ if((data->set.ssl.cert_type) && (!strcasecompare(data->set.ssl.cert_type, "PEM"))) { failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type!"); result = CURLE_SSL_CERTPROBLEM; goto quit; } if(!ldap_ca) { failf(data, "LDAP local: ERROR PEM CA cert not set!"); result = CURLE_SSL_CERTPROBLEM; goto quit; } infof(data, "LDAP local: using PEM CA cert: %s", ldap_ca); rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting PEM CA cert: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } ldap_option = LDAP_OPT_X_TLS_DEMAND; } else ldap_option = LDAP_OPT_X_TLS_NEVER; rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting cert verify mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } server = ldap_init(host, (int)conn->port); if(!server) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.dispname, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } ldap_option = LDAP_OPT_X_TLS_HARD; rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } /* rc = ldap_start_tls_s(server, NULL, NULL); if(rc != LDAP_SUCCESS) { failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s", ldap_err2string(rc)); result = CURLE_SSL_CERTPROBLEM; goto quit; } */ #else /* we should probably never come up to here since configure should check in first place if we can support LDAP SSL/TLS */ failf(data, "LDAP local: SSL/TLS not supported with this version " "of the OpenLDAP toolkit\n"); result = CURLE_SSL_CERTPROBLEM; goto quit; #endif #endif #endif /* CURL_LDAP_USE_SSL */ } else { server = ldap_init(host, (int)conn->port); if(!server) { failf(data, "LDAP local: Cannot connect to %s:%ld", conn->host.dispname, conn->port); result = CURLE_COULDNT_CONNECT; goto quit; } } #ifdef USE_WIN32_LDAP ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); rc = ldap_win_bind(data, server, user, passwd); #else rc = ldap_simple_bind_s(server, user, passwd); #endif if(!ldap_ssl && rc) { ldap_proto = LDAP_VERSION2; ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto); #ifdef USE_WIN32_LDAP rc = ldap_win_bind(data, server, user, passwd); #else rc = ldap_simple_bind_s(server, user, passwd); #endif } if(rc) { #ifdef USE_WIN32_LDAP failf(data, "LDAP local: bind via ldap_win_bind %s", ldap_err2string(rc)); #else failf(data, "LDAP local: bind via ldap_simple_bind_s %s", ldap_err2string(rc)); #endif result = CURLE_LDAP_CANNOT_BIND; goto quit; } rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope, ludp->lud_filter, ludp->lud_attrs, 0, &ldapmsg); if(rc && rc != LDAP_SIZELIMIT_EXCEEDED) { failf(data, "LDAP remote: %s", ldap_err2string(rc)); result = CURLE_LDAP_SEARCH_FAILED; goto quit; } for(num = 0, entryIterator = ldap_first_entry(server, ldapmsg); entryIterator; entryIterator = ldap_next_entry(server, entryIterator), num++) { BerElement *ber = NULL; #if defined(USE_WIN32_LDAP) TCHAR *attribute; #else char *attribute; #endif int i; /* Get the DN and write it to the client */ { char *name; size_t name_len; #if defined(USE_WIN32_LDAP) TCHAR *dn = ldap_get_dn(server, entryIterator); name = curlx_convert_tchar_to_UTF8(dn); if(!name) { ldap_memfree(dn); result = CURLE_OUT_OF_MEMORY; goto quit; } #else char *dn = name = ldap_get_dn(server, entryIterator); #endif name_len = strlen(name); result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"DN: ", 4); if(result) { FREE_ON_WINLDAP(name); ldap_memfree(dn); goto quit; } result = Curl_client_write(data, CLIENTWRITE_BODY, (char *) name, name_len); if(result) { FREE_ON_WINLDAP(name); ldap_memfree(dn); goto quit; } result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); if(result) { FREE_ON_WINLDAP(name); ldap_memfree(dn); goto quit; } dlsize += name_len + 5; FREE_ON_WINLDAP(name); ldap_memfree(dn); } /* Get the attributes and write them to the client */ for(attribute = ldap_first_attribute(server, entryIterator, &ber); attribute; attribute = ldap_next_attribute(server, entryIterator, ber)) { BerValue **vals; size_t attr_len; #if defined(USE_WIN32_LDAP) char *attr = curlx_convert_tchar_to_UTF8(attribute); if(!attr) { if(ber) ber_free(ber, 0); result = CURLE_OUT_OF_MEMORY; goto quit; } #else char *attr = attribute; #endif attr_len = strlen(attr); vals = ldap_get_values_len(server, entryIterator, attribute); if(vals != NULL) { for(i = 0; (vals[i] != NULL); i++) { result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\t", 1); if(result) { ldap_value_free_len(vals); FREE_ON_WINLDAP(attr); ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } result = Curl_client_write(data, CLIENTWRITE_BODY, (char *) attr, attr_len); if(result) { ldap_value_free_len(vals); FREE_ON_WINLDAP(attr); ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)": ", 2); if(result) { ldap_value_free_len(vals); FREE_ON_WINLDAP(attr); ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } dlsize += attr_len + 3; if((attr_len > 7) && (strcmp(";binary", (char *) attr + (attr_len - 7)) == 0)) { /* Binary attribute, encode to base64. */ result = Curl_base64_encode(data, vals[i]->bv_val, vals[i]->bv_len, &val_b64, &val_b64_sz); if(result) { ldap_value_free_len(vals); FREE_ON_WINLDAP(attr); ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } if(val_b64_sz > 0) { result = Curl_client_write(data, CLIENTWRITE_BODY, val_b64, val_b64_sz); free(val_b64); if(result) { ldap_value_free_len(vals); FREE_ON_WINLDAP(attr); ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } dlsize += val_b64_sz; } } else { result = Curl_client_write(data, CLIENTWRITE_BODY, vals[i]->bv_val, vals[i]->bv_len); if(result) { ldap_value_free_len(vals); FREE_ON_WINLDAP(attr); ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } dlsize += vals[i]->bv_len; } result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); if(result) { ldap_value_free_len(vals); FREE_ON_WINLDAP(attr); ldap_memfree(attribute); if(ber) ber_free(ber, 0); goto quit; } dlsize++; } /* Free memory used to store values */ ldap_value_free_len(vals); } /* Free the attribute as we are done with it */ FREE_ON_WINLDAP(attr); ldap_memfree(attribute); result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1); if(result) goto quit; dlsize++; Curl_pgrsSetDownloadCounter(data, dlsize); } if(ber) ber_free(ber, 0); } quit: if(ldapmsg) { ldap_msgfree(ldapmsg); LDAP_TRACE(("Received %d entries\n", num)); } if(rc == LDAP_SIZELIMIT_EXCEEDED) infof(data, "There are more than %d entries", num); if(ludp) ldap_free_urldesc(ludp); if(server) ldap_unbind_s(server); #if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK) if(ldap_ssl) ldapssl_client_deinit(); #endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */ FREE_ON_WINLDAP(host); /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); connclose(conn, "LDAP connection always disable re-use"); return result; } #ifdef DEBUG_LDAP static void _ldap_trace(const char *fmt, ...) { static int do_trace = -1; va_list args; if(do_trace == -1) { const char *env = getenv("CURL_TRACE"); do_trace = (env && strtol(env, NULL, 10) > 0); } if(!do_trace) return; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); } #endif #ifndef HAVE_LDAP_URL_PARSE /* * Return scope-value for a scope-string. */ static int str2scope(const char *p) { if(strcasecompare(p, "one")) return LDAP_SCOPE_ONELEVEL; if(strcasecompare(p, "onetree")) return LDAP_SCOPE_ONELEVEL; if(strcasecompare(p, "base")) return LDAP_SCOPE_BASE; if(strcasecompare(p, "sub")) return LDAP_SCOPE_SUBTREE; if(strcasecompare(p, "subtree")) return LDAP_SCOPE_SUBTREE; return (-1); } /* * Split 'str' into strings separated by commas. * Note: out[] points into 'str'. */ static bool split_str(char *str, char ***out, size_t *count) { char **res; char *lasts; char *s; size_t i; size_t items = 1; s = strchr(str, ','); while(s) { items++; s = strchr(++s, ','); } res = calloc(items, sizeof(char *)); if(!res) return FALSE; for(i = 0, s = strtok_r(str, ",", &lasts); s && i < items; s = strtok_r(NULL, ",", &lasts), i++) res[i] = s; *out = res; *count = items; return TRUE; } /* * Break apart the pieces of an LDAP URL. * Syntax: * ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext> * * <hostname> already known from 'conn->host.name'. * <port> already known from 'conn->remote_port'. * extract the rest from 'data->state.path+1'. All fields are optional. * e.g. * ldap://<hostname>:<port>/?<attributes>?<scope>?<filter> * yields ludp->lud_dn = "". * * Defined in RFC4516 section 2. */ static int _ldap_url_parse2(struct Curl_easy *data, const struct connectdata *conn, LDAPURLDesc *ludp) { int rc = LDAP_SUCCESS; char *p; char *path; char *q = NULL; char *query = NULL; size_t i; if(!data || !data->state.up.path || data->state.up.path[0] != '/' || !strncasecompare("LDAP", data->state.up.scheme, 4)) return LDAP_INVALID_SYNTAX; ludp->lud_scope = LDAP_SCOPE_BASE; ludp->lud_port = conn->remote_port; ludp->lud_host = conn->host.name; /* Duplicate the path */ p = path = strdup(data->state.up.path + 1); if(!path) return LDAP_NO_MEMORY; /* Duplicate the query if present */ if(data->state.up.query) { q = query = strdup(data->state.up.query); if(!query) { free(path); return LDAP_NO_MEMORY; } } /* Parse the DN (Distinguished Name) */ if(*p) { char *dn = p; char *unescaped; CURLcode result; LDAP_TRACE(("DN '%s'\n", dn)); /* Unescape the DN */ result = Curl_urldecode(data, dn, 0, &unescaped, NULL, REJECT_ZERO); if(result) { rc = LDAP_NO_MEMORY; goto quit; } #if defined(USE_WIN32_LDAP) /* Convert the unescaped string to a tchar */ ludp->lud_dn = curlx_convert_UTF8_to_tchar(unescaped); /* Free the unescaped string as we are done with it */ free(unescaped); if(!ludp->lud_dn) { rc = LDAP_NO_MEMORY; goto quit; } #else ludp->lud_dn = unescaped; #endif } p = q; if(!p) goto quit; /* Parse the attributes. skip "??" */ q = strchr(p, '?'); if(q) *q++ = '\0'; if(*p) { char **attributes; size_t count = 0; /* Split the string into an array of attributes */ if(!split_str(p, &attributes, &count)) { rc = LDAP_NO_MEMORY; goto quit; } /* Allocate our array (+1 for the NULL entry) */ #if defined(USE_WIN32_LDAP) ludp->lud_attrs = calloc(count + 1, sizeof(TCHAR *)); #else ludp->lud_attrs = calloc(count + 1, sizeof(char *)); #endif if(!ludp->lud_attrs) { free(attributes); rc = LDAP_NO_MEMORY; goto quit; } for(i = 0; i < count; i++) { char *unescaped; CURLcode result; LDAP_TRACE(("attr[%zu] '%s'\n", i, attributes[i])); /* Unescape the attribute */ result = Curl_urldecode(data, attributes[i], 0, &unescaped, NULL, REJECT_ZERO); if(result) { free(attributes); rc = LDAP_NO_MEMORY; goto quit; } #if defined(USE_WIN32_LDAP) /* Convert the unescaped string to a tchar */ ludp->lud_attrs[i] = curlx_convert_UTF8_to_tchar(unescaped); /* Free the unescaped string as we are done with it */ free(unescaped); if(!ludp->lud_attrs[i]) { free(attributes); rc = LDAP_NO_MEMORY; goto quit; } #else ludp->lud_attrs[i] = unescaped; #endif ludp->lud_attrs_dups++; } free(attributes); } p = q; if(!p) goto quit; /* Parse the scope. skip "??" */ q = strchr(p, '?'); if(q) *q++ = '\0'; if(*p) { ludp->lud_scope = str2scope(p); if(ludp->lud_scope == -1) { rc = LDAP_INVALID_SYNTAX; goto quit; } LDAP_TRACE(("scope %d\n", ludp->lud_scope)); } p = q; if(!p) goto quit; /* Parse the filter */ q = strchr(p, '?'); if(q) *q++ = '\0'; if(*p) { char *filter = p; char *unescaped; CURLcode result; LDAP_TRACE(("filter '%s'\n", filter)); /* Unescape the filter */ result = Curl_urldecode(data, filter, 0, &unescaped, NULL, REJECT_ZERO); if(result) { rc = LDAP_NO_MEMORY; goto quit; } #if defined(USE_WIN32_LDAP) /* Convert the unescaped string to a tchar */ ludp->lud_filter = curlx_convert_UTF8_to_tchar(unescaped); /* Free the unescaped string as we are done with it */ free(unescaped); if(!ludp->lud_filter) { rc = LDAP_NO_MEMORY; goto quit; } #else ludp->lud_filter = unescaped; #endif } p = q; if(p && !*p) { rc = LDAP_INVALID_SYNTAX; goto quit; } quit: free(path); free(query); return rc; } static int _ldap_url_parse(struct Curl_easy *data, const struct connectdata *conn, LDAPURLDesc **ludpp) { LDAPURLDesc *ludp = calloc(1, sizeof(*ludp)); int rc; *ludpp = NULL; if(!ludp) return LDAP_NO_MEMORY; rc = _ldap_url_parse2(data, conn, ludp); if(rc != LDAP_SUCCESS) { _ldap_free_urldesc(ludp); ludp = NULL; } *ludpp = ludp; return (rc); } static void _ldap_free_urldesc(LDAPURLDesc *ludp) { if(!ludp) return; #if defined(USE_WIN32_LDAP) curlx_unicodefree(ludp->lud_dn); curlx_unicodefree(ludp->lud_filter); #else free(ludp->lud_dn); free(ludp->lud_filter); #endif if(ludp->lud_attrs) { size_t i; for(i = 0; i < ludp->lud_attrs_dups; i++) { #if defined(USE_WIN32_LDAP) curlx_unicodefree(ludp->lud_attrs[i]); #else free(ludp->lud_attrs[i]); #endif } free(ludp->lud_attrs); } free(ludp); } #endif /* !HAVE_LDAP_URL_PARSE */ #endif /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/warnless.h
#ifndef HEADER_CURL_WARNLESS_H #define HEADER_CURL_WARNLESS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifdef USE_WINSOCK #include <curl/curl.h> /* for curl_socket_t */ #endif #define CURLX_FUNCTION_CAST(target_type, func) \ (target_type)(void (*) (void))(func) unsigned short curlx_ultous(unsigned long ulnum); unsigned char curlx_ultouc(unsigned long ulnum); int curlx_uztosi(size_t uznum); curl_off_t curlx_uztoso(size_t uznum); unsigned long curlx_uztoul(size_t uznum); unsigned int curlx_uztoui(size_t uznum); int curlx_sltosi(long slnum); unsigned int curlx_sltoui(long slnum); unsigned short curlx_sltous(long slnum); ssize_t curlx_uztosz(size_t uznum); size_t curlx_sotouz(curl_off_t sonum); int curlx_sztosi(ssize_t sznum); unsigned short curlx_uitous(unsigned int uinum); size_t curlx_sitouz(int sinum); #ifdef USE_WINSOCK int curlx_sktosi(curl_socket_t s); curl_socket_t curlx_sitosk(int i); #endif /* USE_WINSOCK */ #if defined(WIN32) || defined(_WIN32) ssize_t curlx_read(int fd, void *buf, size_t count); ssize_t curlx_write(int fd, const void *buf, size_t count); #ifndef BUILDING_WARNLESS_C # undef read # define read(fd, buf, count) curlx_read(fd, buf, count) # undef write # define write(fd, buf, count) curlx_write(fd, buf, count) #endif #endif /* WIN32 || _WIN32 */ #if defined(__INTEL_COMPILER) && defined(__unix__) int curlx_FD_ISSET(int fd, fd_set *fdset); void curlx_FD_SET(int fd, fd_set *fdset); void curlx_FD_ZERO(fd_set *fdset); unsigned short curlx_htons(unsigned short usnum); unsigned short curlx_ntohs(unsigned short usnum); #endif /* __INTEL_COMPILER && __unix__ */ #endif /* HEADER_CURL_WARNLESS_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/krb5.c
/* GSSAPI/krb5 support for FTP - loosely based on old krb4.c * * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * Copyright (c) 2004 - 2021 Daniel Stenberg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "curl_setup.h" #if defined(HAVE_GSSAPI) && !defined(CURL_DISABLE_FTP) #ifdef HAVE_NETDB_H #include <netdb.h> #endif #include "urldata.h" #include "curl_base64.h" #include "ftp.h" #include "curl_gssapi.h" #include "sendf.h" #include "curl_krb5.h" #include "warnless.h" #include "non-ascii.h" #include "strcase.h" #include "strdup.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" static CURLcode ftpsend(struct Curl_easy *data, struct connectdata *conn, const char *cmd) { ssize_t bytes_written; #define SBUF_SIZE 1024 char s[SBUF_SIZE]; size_t write_len; char *sptr = s; CURLcode result = CURLE_OK; #ifdef HAVE_GSSAPI enum protection_level data_sec = conn->data_prot; #endif if(!cmd) return CURLE_BAD_FUNCTION_ARGUMENT; write_len = strlen(cmd); if(!write_len || write_len > (sizeof(s) -3)) return CURLE_BAD_FUNCTION_ARGUMENT; memcpy(&s, cmd, write_len); strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */ write_len += 2; bytes_written = 0; result = Curl_convert_to_network(data, s, write_len); /* Curl_convert_to_network calls failf if unsuccessful */ if(result) return result; for(;;) { #ifdef HAVE_GSSAPI conn->data_prot = PROT_CMD; #endif result = Curl_write(data, conn->sock[FIRSTSOCKET], sptr, write_len, &bytes_written); #ifdef HAVE_GSSAPI DEBUGASSERT(data_sec > PROT_NONE && data_sec < PROT_LAST); conn->data_prot = data_sec; #endif if(result) break; Curl_debug(data, CURLINFO_HEADER_OUT, sptr, (size_t)bytes_written); if(bytes_written != (ssize_t)write_len) { write_len -= bytes_written; sptr += bytes_written; } else break; } return result; } static int krb5_init(void *app_data) { gss_ctx_id_t *context = app_data; /* Make sure our context is initialized for krb5_end. */ *context = GSS_C_NO_CONTEXT; return 0; } static int krb5_check_prot(void *app_data, int level) { (void)app_data; /* unused */ if(level == PROT_CONFIDENTIAL) return -1; return 0; } static int krb5_decode(void *app_data, void *buf, int len, int level UNUSED_PARAM, struct connectdata *conn UNUSED_PARAM) { gss_ctx_id_t *context = app_data; OM_uint32 maj, min; gss_buffer_desc enc, dec; (void)level; (void)conn; enc.value = buf; enc.length = len; maj = gss_unwrap(&min, *context, &enc, &dec, NULL, NULL); if(maj != GSS_S_COMPLETE) { if(len >= 4) strcpy(buf, "599 "); return -1; } memcpy(buf, dec.value, dec.length); len = curlx_uztosi(dec.length); gss_release_buffer(&min, &dec); return len; } static int krb5_encode(void *app_data, const void *from, int length, int level, void **to) { gss_ctx_id_t *context = app_data; gss_buffer_desc dec, enc; OM_uint32 maj, min; int state; int len; /* NOTE that the cast is safe, neither of the krb5, gnu gss and heimdal * libraries modify the input buffer in gss_wrap() */ dec.value = (void *)from; dec.length = length; maj = gss_wrap(&min, *context, level == PROT_PRIVATE, GSS_C_QOP_DEFAULT, &dec, &state, &enc); if(maj != GSS_S_COMPLETE) return -1; /* malloc a new buffer, in case gss_release_buffer doesn't work as expected */ *to = malloc(enc.length); if(!*to) return -1; memcpy(*to, enc.value, enc.length); len = curlx_uztosi(enc.length); gss_release_buffer(&min, &enc); return len; } static int krb5_auth(void *app_data, struct Curl_easy *data, struct connectdata *conn) { int ret = AUTH_OK; char *p; const char *host = conn->host.name; ssize_t nread; curl_socklen_t l = sizeof(conn->local_addr); CURLcode result; const char *service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : "ftp"; const char *srv_host = "host"; gss_buffer_desc input_buffer, output_buffer, _gssresp, *gssresp; OM_uint32 maj, min; gss_name_t gssname; gss_ctx_id_t *context = app_data; struct gss_channel_bindings_struct chan; size_t base64_sz = 0; struct sockaddr_in **remote_addr = (struct sockaddr_in **)&conn->ip_addr->ai_addr; char *stringp; if(getsockname(conn->sock[FIRSTSOCKET], (struct sockaddr *)&conn->local_addr, &l) < 0) perror("getsockname()"); chan.initiator_addrtype = GSS_C_AF_INET; chan.initiator_address.length = l - 4; chan.initiator_address.value = &conn->local_addr.sin_addr.s_addr; chan.acceptor_addrtype = GSS_C_AF_INET; chan.acceptor_address.length = l - 4; chan.acceptor_address.value = &(*remote_addr)->sin_addr.s_addr; chan.application_data.length = 0; chan.application_data.value = NULL; /* this loop will execute twice (once for service, once for host) */ for(;;) { /* this really shouldn't be repeated here, but can't help it */ if(service == srv_host) { result = ftpsend(data, conn, "AUTH GSSAPI"); if(result) return -2; if(Curl_GetFTPResponse(data, &nread, NULL)) return -1; if(data->state.buffer[0] != '3') return -1; } stringp = aprintf("%s@%s", service, host); if(!stringp) return -2; input_buffer.value = stringp; input_buffer.length = strlen(stringp); maj = gss_import_name(&min, &input_buffer, GSS_C_NT_HOSTBASED_SERVICE, &gssname); free(stringp); if(maj != GSS_S_COMPLETE) { gss_release_name(&min, &gssname); if(service == srv_host) { failf(data, "Error importing service name %s@%s", service, host); return AUTH_ERROR; } service = srv_host; continue; } /* We pass NULL as |output_name_type| to avoid a leak. */ gss_display_name(&min, gssname, &output_buffer, NULL); infof(data, "Trying against %s", output_buffer.value); gssresp = GSS_C_NO_BUFFER; *context = GSS_C_NO_CONTEXT; do { /* Release the buffer at each iteration to avoid leaking: the first time we are releasing the memory from gss_display_name. The last item is taken care by a final gss_release_buffer. */ gss_release_buffer(&min, &output_buffer); ret = AUTH_OK; maj = Curl_gss_init_sec_context(data, &min, context, gssname, &Curl_krb5_mech_oid, &chan, gssresp, &output_buffer, TRUE, NULL); if(gssresp) { free(_gssresp.value); gssresp = NULL; } if(GSS_ERROR(maj)) { infof(data, "Error creating security context"); ret = AUTH_ERROR; break; } if(output_buffer.length) { char *cmd; result = Curl_base64_encode(data, (char *)output_buffer.value, output_buffer.length, &p, &base64_sz); if(result) { infof(data, "base64-encoding: %s", curl_easy_strerror(result)); ret = AUTH_ERROR; break; } cmd = aprintf("ADAT %s", p); if(cmd) result = ftpsend(data, conn, cmd); else result = CURLE_OUT_OF_MEMORY; free(p); free(cmd); if(result) { ret = -2; break; } if(Curl_GetFTPResponse(data, &nread, NULL)) { ret = -1; break; } if(data->state.buffer[0] != '2' && data->state.buffer[0] != '3') { infof(data, "Server didn't accept auth data"); ret = AUTH_ERROR; break; } _gssresp.value = NULL; /* make sure it is initialized */ p = data->state.buffer + 4; p = strstr(p, "ADAT="); if(p) { result = Curl_base64_decode(p + 5, (unsigned char **)&_gssresp.value, &_gssresp.length); if(result) { failf(data, "base64-decoding: %s", curl_easy_strerror(result)); ret = AUTH_CONTINUE; break; } } gssresp = &_gssresp; } } while(maj == GSS_S_CONTINUE_NEEDED); gss_release_name(&min, &gssname); gss_release_buffer(&min, &output_buffer); if(gssresp) free(_gssresp.value); if(ret == AUTH_OK || service == srv_host) return ret; service = srv_host; } return ret; } static void krb5_end(void *app_data) { OM_uint32 min; gss_ctx_id_t *context = app_data; if(*context != GSS_C_NO_CONTEXT) { OM_uint32 maj = gss_delete_sec_context(&min, context, GSS_C_NO_BUFFER); (void)maj; DEBUGASSERT(maj == GSS_S_COMPLETE); } } static const struct Curl_sec_client_mech Curl_krb5_client_mech = { "GSSAPI", sizeof(gss_ctx_id_t), krb5_init, krb5_auth, krb5_end, krb5_check_prot, krb5_encode, krb5_decode }; static const struct { enum protection_level level; const char *name; } level_names[] = { { PROT_CLEAR, "clear" }, { PROT_SAFE, "safe" }, { PROT_CONFIDENTIAL, "confidential" }, { PROT_PRIVATE, "private" } }; static enum protection_level name_to_level(const char *name) { int i; for(i = 0; i < (int)sizeof(level_names)/(int)sizeof(level_names[0]); i++) if(curl_strequal(name, level_names[i].name)) return level_names[i].level; return PROT_NONE; } /* Convert a protocol |level| to its char representation. We take an int to catch programming mistakes. */ static char level_to_char(int level) { switch(level) { case PROT_CLEAR: return 'C'; case PROT_SAFE: return 'S'; case PROT_CONFIDENTIAL: return 'E'; case PROT_PRIVATE: return 'P'; case PROT_CMD: /* Fall through */ default: /* Those 2 cases should not be reached! */ break; } DEBUGASSERT(0); /* Default to the most secure alternative. */ return 'P'; } /* Send an FTP command defined by |message| and the optional arguments. The function returns the ftp_code. If an error occurs, -1 is returned. */ static int ftp_send_command(struct Curl_easy *data, const char *message, ...) { int ftp_code; ssize_t nread = 0; va_list args; char print_buffer[50]; va_start(args, message); mvsnprintf(print_buffer, sizeof(print_buffer), message, args); va_end(args); if(ftpsend(data, data->conn, print_buffer)) { ftp_code = -1; } else { if(Curl_GetFTPResponse(data, &nread, &ftp_code)) ftp_code = -1; } (void)nread; /* Unused */ return ftp_code; } /* Read |len| from the socket |fd| and store it in |to|. Return a CURLcode saying whether an error occurred or CURLE_OK if |len| was read. */ static CURLcode socket_read(curl_socket_t fd, void *to, size_t len) { char *to_p = to; CURLcode result; ssize_t nread = 0; while(len > 0) { result = Curl_read_plain(fd, to_p, len, &nread); if(!result) { len -= nread; to_p += nread; } else { if(result == CURLE_AGAIN) continue; return result; } } return CURLE_OK; } /* Write |len| bytes from the buffer |to| to the socket |fd|. Return a CURLcode saying whether an error occurred or CURLE_OK if |len| was written. */ static CURLcode socket_write(struct Curl_easy *data, curl_socket_t fd, const void *to, size_t len) { const char *to_p = to; CURLcode result; ssize_t written; while(len > 0) { result = Curl_write_plain(data, fd, to_p, len, &written); if(!result) { len -= written; to_p += written; } else { if(result == CURLE_AGAIN) continue; return result; } } return CURLE_OK; } static CURLcode read_data(struct connectdata *conn, curl_socket_t fd, struct krb5buffer *buf) { int len; CURLcode result; result = socket_read(fd, &len, sizeof(len)); if(result) return result; if(len) { /* only realloc if there was a length */ len = ntohl(len); buf->data = Curl_saferealloc(buf->data, len); } if(!len || !buf->data) return CURLE_OUT_OF_MEMORY; result = socket_read(fd, buf->data, len); if(result) return result; buf->size = conn->mech->decode(conn->app_data, buf->data, len, conn->data_prot, conn); buf->index = 0; return CURLE_OK; } static size_t buffer_read(struct krb5buffer *buf, void *data, size_t len) { if(buf->size - buf->index < len) len = buf->size - buf->index; memcpy(data, (char *)buf->data + buf->index, len); buf->index += len; return len; } /* Matches Curl_recv signature */ static ssize_t sec_recv(struct Curl_easy *data, int sockindex, char *buffer, size_t len, CURLcode *err) { size_t bytes_read; size_t total_read = 0; struct connectdata *conn = data->conn; curl_socket_t fd = conn->sock[sockindex]; *err = CURLE_OK; /* Handle clear text response. */ if(conn->sec_complete == 0 || conn->data_prot == PROT_CLEAR) return sread(fd, buffer, len); if(conn->in_buffer.eof_flag) { conn->in_buffer.eof_flag = 0; return 0; } bytes_read = buffer_read(&conn->in_buffer, buffer, len); len -= bytes_read; total_read += bytes_read; buffer += bytes_read; while(len > 0) { if(read_data(conn, fd, &conn->in_buffer)) return -1; if(conn->in_buffer.size == 0) { if(bytes_read > 0) conn->in_buffer.eof_flag = 1; return bytes_read; } bytes_read = buffer_read(&conn->in_buffer, buffer, len); len -= bytes_read; total_read += bytes_read; buffer += bytes_read; } return total_read; } /* Send |length| bytes from |from| to the |fd| socket taking care of encoding and negotiating with the server. |from| can be NULL. */ static void do_sec_send(struct Curl_easy *data, struct connectdata *conn, curl_socket_t fd, const char *from, int length) { int bytes, htonl_bytes; /* 32-bit integers for htonl */ char *buffer = NULL; char *cmd_buffer; size_t cmd_size = 0; CURLcode error; enum protection_level prot_level = conn->data_prot; bool iscmd = (prot_level == PROT_CMD)?TRUE:FALSE; DEBUGASSERT(prot_level > PROT_NONE && prot_level < PROT_LAST); if(iscmd) { if(!strncmp(from, "PASS ", 5) || !strncmp(from, "ACCT ", 5)) prot_level = PROT_PRIVATE; else prot_level = conn->command_prot; } bytes = conn->mech->encode(conn->app_data, from, length, prot_level, (void **)&buffer); if(!buffer || bytes <= 0) return; /* error */ if(iscmd) { error = Curl_base64_encode(data, buffer, curlx_sitouz(bytes), &cmd_buffer, &cmd_size); if(error) { free(buffer); return; /* error */ } if(cmd_size > 0) { static const char *enc = "ENC "; static const char *mic = "MIC "; if(prot_level == PROT_PRIVATE) socket_write(data, fd, enc, 4); else socket_write(data, fd, mic, 4); socket_write(data, fd, cmd_buffer, cmd_size); socket_write(data, fd, "\r\n", 2); infof(data, "Send: %s%s", prot_level == PROT_PRIVATE?enc:mic, cmd_buffer); free(cmd_buffer); } } else { htonl_bytes = htonl(bytes); socket_write(data, fd, &htonl_bytes, sizeof(htonl_bytes)); socket_write(data, fd, buffer, curlx_sitouz(bytes)); } free(buffer); } static ssize_t sec_write(struct Curl_easy *data, struct connectdata *conn, curl_socket_t fd, const char *buffer, size_t length) { ssize_t tx = 0, len = conn->buffer_size; if(len <= 0) len = length; while(length) { if(length < (size_t)len) len = length; do_sec_send(data, conn, fd, buffer, curlx_sztosi(len)); length -= len; buffer += len; tx += len; } return tx; } /* Matches Curl_send signature */ static ssize_t sec_send(struct Curl_easy *data, int sockindex, const void *buffer, size_t len, CURLcode *err) { struct connectdata *conn = data->conn; curl_socket_t fd = conn->sock[sockindex]; *err = CURLE_OK; return sec_write(data, conn, fd, buffer, len); } int Curl_sec_read_msg(struct Curl_easy *data, struct connectdata *conn, char *buffer, enum protection_level level) { /* decoded_len should be size_t or ssize_t but conn->mech->decode returns an int */ int decoded_len; char *buf; int ret_code = 0; size_t decoded_sz = 0; CURLcode error; (void) data; if(!conn->mech) /* not initialized, return error */ return -1; DEBUGASSERT(level > PROT_NONE && level < PROT_LAST); error = Curl_base64_decode(buffer + 4, (unsigned char **)&buf, &decoded_sz); if(error || decoded_sz == 0) return -1; if(decoded_sz > (size_t)INT_MAX) { free(buf); return -1; } decoded_len = curlx_uztosi(decoded_sz); decoded_len = conn->mech->decode(conn->app_data, buf, decoded_len, level, conn); if(decoded_len <= 0) { free(buf); return -1; } { buf[decoded_len] = '\n'; Curl_debug(data, CURLINFO_HEADER_IN, buf, decoded_len + 1); } buf[decoded_len] = '\0'; if(decoded_len <= 3) /* suspiciously short */ return 0; if(buf[3] != '-') /* safe to ignore return code */ (void)sscanf(buf, "%d", &ret_code); if(buf[decoded_len - 1] == '\n') buf[decoded_len - 1] = '\0'; strcpy(buffer, buf); free(buf); return ret_code; } static int sec_set_protection_level(struct Curl_easy *data) { int code; struct connectdata *conn = data->conn; enum protection_level level = conn->request_data_prot; DEBUGASSERT(level > PROT_NONE && level < PROT_LAST); if(!conn->sec_complete) { infof(data, "Trying to change the protection level after the" " completion of the data exchange."); return -1; } /* Bail out if we try to set up the same level */ if(conn->data_prot == level) return 0; if(level) { char *pbsz; unsigned int buffer_size = 1 << 20; /* 1048576 */ code = ftp_send_command(data, "PBSZ %u", buffer_size); if(code < 0) return -1; if(code/100 != 2) { failf(data, "Failed to set the protection's buffer size."); return -1; } conn->buffer_size = buffer_size; pbsz = strstr(data->state.buffer, "PBSZ="); if(pbsz) { /* ignore return code, use default value if it fails */ (void)sscanf(pbsz, "PBSZ=%u", &buffer_size); if(buffer_size < conn->buffer_size) conn->buffer_size = buffer_size; } } /* Now try to negotiate the protection level. */ code = ftp_send_command(data, "PROT %c", level_to_char(level)); if(code < 0) return -1; if(code/100 != 2) { failf(data, "Failed to set the protection level."); return -1; } conn->data_prot = level; if(level == PROT_PRIVATE) conn->command_prot = level; return 0; } int Curl_sec_request_prot(struct connectdata *conn, const char *level) { enum protection_level l = name_to_level(level); if(l == PROT_NONE) return -1; DEBUGASSERT(l > PROT_NONE && l < PROT_LAST); conn->request_data_prot = l; return 0; } static CURLcode choose_mech(struct Curl_easy *data, struct connectdata *conn) { int ret; void *tmp_allocation; const struct Curl_sec_client_mech *mech = &Curl_krb5_client_mech; tmp_allocation = realloc(conn->app_data, mech->size); if(!tmp_allocation) { failf(data, "Failed realloc of size %zu", mech->size); mech = NULL; return CURLE_OUT_OF_MEMORY; } conn->app_data = tmp_allocation; if(mech->init) { ret = mech->init(conn->app_data); if(ret) { infof(data, "Failed initialization for %s. Skipping it.", mech->name); return CURLE_FAILED_INIT; } } infof(data, "Trying mechanism %s...", mech->name); ret = ftp_send_command(data, "AUTH %s", mech->name); if(ret < 0) return CURLE_COULDNT_CONNECT; if(ret/100 != 3) { switch(ret) { case 504: infof(data, "Mechanism %s is not supported by the server (server " "returned ftp code: 504).", mech->name); break; case 534: infof(data, "Mechanism %s was rejected by the server (server returned " "ftp code: 534).", mech->name); break; default: if(ret/100 == 5) { infof(data, "server does not support the security extensions"); return CURLE_USE_SSL_FAILED; } break; } return CURLE_LOGIN_DENIED; } /* Authenticate */ ret = mech->auth(conn->app_data, data, conn); if(ret != AUTH_CONTINUE) { if(ret != AUTH_OK) { /* Mechanism has dumped the error to stderr, don't error here. */ return CURLE_USE_SSL_FAILED; } DEBUGASSERT(ret == AUTH_OK); conn->mech = mech; conn->sec_complete = 1; conn->recv[FIRSTSOCKET] = sec_recv; conn->send[FIRSTSOCKET] = sec_send; conn->recv[SECONDARYSOCKET] = sec_recv; conn->send[SECONDARYSOCKET] = sec_send; conn->command_prot = PROT_SAFE; /* Set the requested protection level */ /* BLOCKING */ (void)sec_set_protection_level(data); } return CURLE_OK; } CURLcode Curl_sec_login(struct Curl_easy *data, struct connectdata *conn) { return choose_mech(data, conn); } void Curl_sec_end(struct connectdata *conn) { if(conn->mech != NULL && conn->mech->end) conn->mech->end(conn->app_data); free(conn->app_data); conn->app_data = NULL; if(conn->in_buffer.data) { free(conn->in_buffer.data); conn->in_buffer.data = NULL; conn->in_buffer.size = 0; conn->in_buffer.index = 0; conn->in_buffer.eof_flag = 0; } conn->sec_complete = 0; conn->data_prot = PROT_CLEAR; conn->mech = NULL; } #endif /* HAVE_GSSAPI && !CURL_DISABLE_FTP */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/speedcheck.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "multiif.h" #include "speedcheck.h" void Curl_speedinit(struct Curl_easy *data) { memset(&data->state.keeps_speed, 0, sizeof(struct curltime)); } /* * @unittest: 1606 */ CURLcode Curl_speedcheck(struct Curl_easy *data, struct curltime now) { if(data->req.keepon & KEEP_RECV_PAUSE) /* A paused transfer is not qualified for speed checks */ return CURLE_OK; if((data->progress.current_speed >= 0) && data->set.low_speed_time) { if(data->progress.current_speed < data->set.low_speed_limit) { if(!data->state.keeps_speed.tv_sec) /* under the limit at this very moment */ data->state.keeps_speed = now; else { /* how long has it been under the limit */ timediff_t howlong = Curl_timediff(now, data->state.keeps_speed); if(howlong >= data->set.low_speed_time * 1000) { /* too long */ failf(data, "Operation too slow. " "Less than %ld bytes/sec transferred the last %ld seconds", data->set.low_speed_limit, data->set.low_speed_time); return CURLE_OPERATION_TIMEDOUT; } } } else /* faster right now */ data->state.keeps_speed.tv_sec = 0; } if(data->set.low_speed_limit) /* if low speed limit is enabled, set the expire timer to make this connection's speed get checked again in a second */ Curl_expire(data, 1000, EXPIRE_SPEEDCHECK); return CURLE_OK; }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/config-vxworks.h
#ifndef HEADER_CURL_CONFIG_VXWORKS_H #define HEADER_CURL_CONFIG_VXWORKS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* =============================================================== */ /* Hand crafted config file for VxWorks */ /* =============================================================== */ /* Location of default ca bundle */ /* #undef CURL_CA_BUNDLE */ /* Location of default ca path */ /* #undef CURL_CA_PATH */ /* to disable cookies support */ /* #undef CURL_DISABLE_COOKIES */ /* to disable cryptographic authentication */ /* #undef CURL_DISABLE_CRYPTO_AUTH */ /* to disable DICT */ /* #undef CURL_DISABLE_DICT */ /* to disable FILE */ /* #undef CURL_DISABLE_FILE */ /* to disable FTP */ #define CURL_DISABLE_FTP 1 /* to disable HTTP */ /* #undef CURL_DISABLE_HTTP */ /* to disable LDAP */ #define CURL_DISABLE_LDAP 1 /* to disable LDAPS */ #define CURL_DISABLE_LDAPS 1 /* to disable NTLM authentication */ #define CURL_DISABLE_NTLM 1 /* to disable proxies */ /* #undef CURL_DISABLE_PROXY */ /* to disable TELNET */ #define CURL_DISABLE_TELNET 1 /* to disable TFTP */ #define CURL_DISABLE_TFTP 1 /* to disable verbose strings */ /* #undef CURL_DISABLE_VERBOSE_STRINGS */ /* Definition to make a library symbol externally visible. */ /* #undef CURL_EXTERN_SYMBOL */ /* Use Windows LDAP implementation */ /* #undef USE_WIN32_LDAP */ /* your Entropy Gathering Daemon socket pathname */ /* #undef EGD_SOCKET */ /* Define if you want to enable IPv6 support */ #define ENABLE_IPV6 1 /* Define to 1 if you have the alarm function. */ #define HAVE_ALARM 1 /* Define to 1 if you have the <alloca.h> header file. */ #define HAVE_ALLOCA_H 1 /* Define to 1 if you have the <arpa/inet.h> header file. */ #define HAVE_ARPA_INET_H 1 /* Define to 1 if you have the <arpa/tftp.h> header file. */ /* #undef HAVE_ARPA_TFTP_H */ /* Define to 1 if you have the <assert.h> header file. */ #define HAVE_ASSERT_H 1 /* Define to 1 if you have the `basename' function. */ /* #undef HAVE_BASENAME */ /* Define to 1 if bool is an available type. */ #define HAVE_BOOL_T 1 /* Define to 1 if you have the clock_gettime function and monotonic timer. */ /* #undef HAVE_CLOCK_GETTIME_MONOTONIC */ /* Define to 1 if you have the `closesocket' function. */ /* #undef HAVE_CLOSESOCKET */ /* Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. */ #define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1 /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the <errno.h> header file. */ #define HAVE_ERRNO_H 1 /* Define to 1 if you have the fcntl function. */ #define HAVE_FCNTL 1 /* Define to 1 if you have the <fcntl.h> header file. */ #define HAVE_FCNTL_H 1 /* Define to 1 if you have a working fcntl O_NONBLOCK function. */ #define HAVE_FCNTL_O_NONBLOCK 1 /* Define to 1 if you have the freeaddrinfo function. */ #define HAVE_FREEADDRINFO 1 /* Define to 1 if you have the ftruncate function. */ #define HAVE_FTRUNCATE 1 /* Define to 1 if you have a working getaddrinfo function. */ #define HAVE_GETADDRINFO 1 /* Define to 1 if you have the `geteuid' function. */ /* #undef HAVE_GETEUID */ /* Define to 1 if you have the gethostbyname function. */ #define HAVE_GETHOSTBYNAME 1 /* Define to 1 if you have the gethostbyname_r function. */ /* #undef HAVE_GETHOSTBYNAME_R */ /* gethostbyname_r() takes 3 args */ /* #undef HAVE_GETHOSTBYNAME_R_3 */ /* gethostbyname_r() takes 5 args */ /* #undef HAVE_GETHOSTBYNAME_R_5 */ /* gethostbyname_r() takes 6 args */ /* #undef HAVE_GETHOSTBYNAME_R_6 */ /* Define to 1 if you have the gethostname function. */ #define HAVE_GETHOSTNAME 1 /* Define to 1 if you have a working getifaddrs function. */ /* #undef HAVE_GETIFADDRS */ /* Define to 1 if you have the `getpass_r' function. */ /* #undef HAVE_GETPASS_R */ /* Define to 1 if you have the `getppid' function. */ #define HAVE_GETPPID 1 /* Define to 1 if you have the `getprotobyname' function. */ #define HAVE_GETPROTOBYNAME 1 /* Define to 1 if you have the `getpwuid' function. */ /* #undef HAVE_GETPWUID */ /* Define to 1 if you have the `getrlimit' function. */ #define HAVE_GETRLIMIT 1 /* Define to 1 if you have the `gettimeofday' function. */ /* #undef HAVE_GETTIMEOFDAY */ /* Define to 1 if you have a working glibc-style strerror_r function. */ /* #undef HAVE_GLIBC_STRERROR_R */ /* Define to 1 if you have a working gmtime_r function. */ #define HAVE_GMTIME_R 1 /* if you have the gssapi libraries */ /* #undef HAVE_GSSAPI */ /* Define to 1 if you have the <gssapi/gssapi_generic.h> header file. */ /* #undef HAVE_GSSAPI_GSSAPI_GENERIC_H */ /* Define to 1 if you have the <gssapi/gssapi.h> header file. */ /* #undef HAVE_GSSAPI_GSSAPI_H */ /* Define to 1 if you have the <gssapi/gssapi_krb5.h> header file. */ /* #undef HAVE_GSSAPI_GSSAPI_KRB5_H */ /* if you have the GNU gssapi libraries */ /* #undef HAVE_GSSGNU */ /* if you have the Heimdal gssapi libraries */ /* #undef HAVE_GSSHEIMDAL */ /* if you have the MIT gssapi libraries */ /* #undef HAVE_GSSMIT */ /* Define to 1 if you have the `idna_strerror' function. */ /* #undef HAVE_IDNA_STRERROR */ /* Define to 1 if you have the `idn_free' function. */ /* #undef HAVE_IDN_FREE */ /* Define to 1 if you have the <idn-free.h> header file. */ /* #undef HAVE_IDN_FREE_H */ /* Define to 1 if you have the <ifaddrs.h> header file. */ /* #undef HAVE_IFADDRS_H */ /* Define to 1 if you have the `inet_addr' function. */ #define HAVE_INET_ADDR 1 /* Define to 1 if you have a IPv6 capable working inet_ntop function. */ /* #undef HAVE_INET_NTOP */ /* Define to 1 if you have a IPv6 capable working inet_pton function. */ /* #undef HAVE_INET_PTON */ /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the ioctl function. */ #define HAVE_IOCTL 1 /* Define to 1 if you have the ioctlsocket function. */ /* #undef HAVE_IOCTLSOCKET */ /* Define to 1 if you have the IoctlSocket camel case function. */ /* #undef HAVE_IOCTLSOCKET_CAMEL */ /* Define to 1 if you have a working IoctlSocket camel case FIONBIO function. */ /* #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO */ /* Define to 1 if you have a working ioctlsocket FIONBIO function. */ /* #undef HAVE_IOCTLSOCKET_FIONBIO */ /* Define to 1 if you have a working ioctl FIONBIO function. */ #define HAVE_IOCTL_FIONBIO 1 /* Define to 1 if you have a working ioctl SIOCGIFADDR function. */ #define HAVE_IOCTL_SIOCGIFADDR 1 /* Define to 1 if you have the <io.h> header file. */ #define HAVE_IO_H 1 /* if you have the Kerberos4 libraries (including -ldes) */ /* #undef HAVE_KRB4 */ /* Define to 1 if you have the `krb_get_our_ip_for_realm' function. */ /* #undef HAVE_KRB_GET_OUR_IP_FOR_REALM */ /* Define to 1 if you have the <krb.h> header file. */ /* #undef HAVE_KRB_H */ /* Define to 1 if you have the lber.h header file. */ /* #undef HAVE_LBER_H */ /* Define to 1 if you have the ldapssl.h header file. */ /* #undef HAVE_LDAPSSL_H */ /* Define to 1 if you have the ldap.h header file. */ /* #undef HAVE_LDAP_H */ /* Use LDAPS implementation */ /* #undef HAVE_LDAP_SSL */ /* Define to 1 if you have the ldap_ssl.h header file. */ /* #undef HAVE_LDAP_SSL_H */ /* Define to 1 if you have the `ldap_url_parse' function. */ /* #undef HAVE_LDAP_URL_PARSE */ /* Define to 1 if you have the <libgen.h> header file. */ /* #undef HAVE_LIBGEN_H */ /* Define to 1 if you have the `idn' library (-lidn). */ /* #undef HAVE_LIBIDN */ /* Define to 1 if you have the `resolv' library (-lresolv). */ /* #undef HAVE_LIBRESOLV */ /* Define to 1 if you have the `resolve' library (-lresolve). */ /* #undef HAVE_LIBRESOLVE */ /* Define to 1 if you have the `socket' library (-lsocket). */ /* #undef HAVE_LIBSOCKET */ /* Define to 1 if you have the `ssh2' library (-lssh2). */ /* #undef HAVE_LIBSSH2 */ /* Define to 1 if you have the <libssh2.h> header file. */ /* #undef HAVE_LIBSSH2_H */ /* Define to 1 if you have the `libssh2_version' function. */ /* #undef HAVE_LIBSSH2_VERSION */ /* if zlib is available */ #define HAVE_LIBZ 1 /* if your compiler supports LL */ #define HAVE_LL 1 /* Define to 1 if you have the <locale.h> header file. */ #define HAVE_LOCALE_H 1 /* Define to 1 if you have a working localtime_r function. */ #define HAVE_LOCALTIME_R 1 /* Define to 1 if the compiler supports the 'long long' data type. */ #define HAVE_LONGLONG 1 /* Define to 1 if you have the malloc.h header file. */ #define HAVE_MALLOC_H 1 /* Define to 1 if you have the memory.h header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the MSG_NOSIGNAL flag. */ /* #undef HAVE_MSG_NOSIGNAL */ /* Define to 1 if you have the <netdb.h> header file. */ #define HAVE_NETDB_H 1 /* Define to 1 if you have the <netinet/in.h> header file. */ #define HAVE_NETINET_IN_H 1 /* Define to 1 if you have the <netinet/tcp.h> header file. */ #define HAVE_NETINET_TCP_H 1 /* Define to 1 if you have the <net/if.h> header file. */ #define HAVE_NET_IF_H 1 /* Define to 1 if NI_WITHSCOPEID exists and works. */ /* #undef HAVE_NI_WITHSCOPEID */ /* if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE */ /* #undef HAVE_OLD_GSSMIT */ /* Define to 1 if you have the <openssl/crypto.h> header file. */ #define HAVE_OPENSSL_CRYPTO_H 1 /* Define to 1 if you have the <openssl/err.h> header file. */ #define HAVE_OPENSSL_ERR_H 1 /* Define to 1 if you have the <openssl/pem.h> header file. */ #define HAVE_OPENSSL_PEM_H 1 /* Define to 1 if you have the <openssl/pkcs12.h> header file. */ #define HAVE_OPENSSL_PKCS12_H 1 /* Define to 1 if you have the <openssl/rsa.h> header file. */ #define HAVE_OPENSSL_RSA_H 1 /* Define to 1 if you have the <openssl/ssl.h> header file. */ #define HAVE_OPENSSL_SSL_H 1 /* Define to 1 if you have the <openssl/x509.h> header file. */ #define HAVE_OPENSSL_X509_H 1 /* Define to 1 if you have the <pem.h> header file. */ /* #undef HAVE_PEM_H */ /* Define to 1 if you have the `pipe' function. */ #define HAVE_PIPE 1 /* Define to 1 if you have a working poll function. */ /* #undef HAVE_POLL */ /* If you have a fine poll */ /* #undef HAVE_POLL_FINE */ /* Define to 1 if you have the <poll.h> header file. */ /* #undef HAVE_POLL_H */ /* Define to 1 if you have a working POSIX-style strerror_r function. */ /* #undef HAVE_POSIX_STRERROR_R */ /* Define to 1 if you have the <pwd.h> header file. */ /* #undef HAVE_PWD_H */ /* Define to 1 if you have the `RAND_egd' function. */ #define HAVE_RAND_EGD 1 /* Define to 1 if you have the `RAND_screen' function. */ /* #undef HAVE_RAND_SCREEN */ /* Define to 1 if you have the `RAND_status' function. */ #define HAVE_RAND_STATUS 1 /* Define to 1 if you have the recv function. */ #define HAVE_RECV 1 /* Define to 1 if you have the recvfrom function. */ #define HAVE_RECVFROM 1 /* Define to 1 if you have the select function. */ #define HAVE_SELECT 1 /* Define to 1 if you have the send function. */ #define HAVE_SEND 1 /* Define to 1 if you have the <setjmp.h> header file. */ #define HAVE_SETJMP_H 1 /* Define to 1 if you have the `setlocale' function. */ #define HAVE_SETLOCALE 1 /* Define to 1 if you have the `setmode' function. */ #define HAVE_SETMODE 1 /* Define to 1 if you have the `setrlimit' function. */ #define HAVE_SETRLIMIT 1 /* Define to 1 if you have the setsockopt function. */ #define HAVE_SETSOCKOPT 1 /* Define to 1 if you have a working setsockopt SO_NONBLOCK function. */ /* #undef HAVE_SETSOCKOPT_SO_NONBLOCK */ /* Define to 1 if you have the sigaction function. */ #define HAVE_SIGACTION 1 /* Define to 1 if you have the siginterrupt function. */ #define HAVE_SIGINTERRUPT 1 /* Define to 1 if you have the signal function. */ #define HAVE_SIGNAL 1 /* Define to 1 if you have the <signal.h> header file. */ #define HAVE_SIGNAL_H 1 /* Define to 1 if you have the sigsetjmp function or macro. */ /* #undef HAVE_SIGSETJMP */ /* Define to 1 if struct sockaddr_in6 has the sin6_scope_id member */ #define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 /* Define to 1 if you have the `socket' function. */ #define HAVE_SOCKET 1 /* Define to 1 if you have the <ssl.h> header file. */ /* #undef HAVE_SSL_H */ /* Define to 1 if you have the <stdbool.h> header file. */ #define HAVE_STDBOOL_H 1 /* Define to 1 if you have the <stdint.h> header file. */ /* #undef HAVE_STDINT_H */ /* Define to 1 if you have the <stdio.h> header file. */ #define HAVE_STDIO_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the strcasecmp function. */ #define HAVE_STRCASECMP 1 /* Define to 1 if you have the strcmpi function. */ /* #undef HAVE_STRCMPI */ /* Define to 1 if you have the strdup function. */ #define HAVE_STRDUP 1 /* Define to 1 if you have the strerror_r function. */ #define HAVE_STRERROR_R 1 /* Define to 1 if you have the stricmp function. */ /* #undef HAVE_STRICMP */ /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the strncmpi function. */ /* #undef HAVE_STRNCMPI */ /* Define to 1 if you have the strnicmp function. */ /* #undef HAVE_STRNICMP */ /* Define to 1 if you have the <stropts.h> header file. */ /* #undef HAVE_STROPTS_H */ /* Define to 1 if you have the strstr function. */ #define HAVE_STRSTR 1 /* Define to 1 if you have the strtok_r function. */ #define HAVE_STRTOK_R 1 /* Define to 1 if you have the strtoll function. */ /* #undef HAVE_STRTOLL */ /* if struct sockaddr_storage is defined */ #define HAVE_STRUCT_SOCKADDR_STORAGE 1 /* Define to 1 if you have the timeval struct. */ #define HAVE_STRUCT_TIMEVAL 1 /* Define to 1 if you have the <sys/filio.h> header file. */ /* #undef HAVE_SYS_FILIO_H */ /* Define to 1 if you have the <sys/ioctl.h> header file. */ #define HAVE_SYS_IOCTL_H 1 /* Define to 1 if you have the <sys/param.h> header file. */ /* #undef HAVE_SYS_PARAM_H */ /* Define to 1 if you have the <sys/poll.h> header file. */ /* #undef HAVE_SYS_POLL_H */ /* Define to 1 if you have the <sys/resource.h> header file. */ #define HAVE_SYS_RESOURCE_H 1 /* Define to 1 if you have the <sys/select.h> header file. */ /* #undef HAVE_SYS_SELECT_H */ /* Define to 1 if you have the <sys/socket.h> header file. */ #define HAVE_SYS_SOCKET_H 1 /* Define to 1 if you have the <sys/sockio.h> header file. */ /* #undef HAVE_SYS_SOCKIO_H */ /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/time.h> header file. */ /* #undef HAVE_SYS_TIME_H */ /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <sys/uio.h> header file. */ #define HAVE_SYS_UIO_H 1 /* Define to 1 if you have the <sys/un.h> header file. */ #define HAVE_SYS_UN_H 1 /* Define to 1 if you have the <sys/utime.h> header file. */ #define HAVE_SYS_UTIME_H 1 /* Define to 1 if you have the <termios.h> header file. */ #define HAVE_TERMIOS_H 1 /* Define to 1 if you have the <termio.h> header file. */ #define HAVE_TERMIO_H 1 /* Define to 1 if you have the <time.h> header file. */ #define HAVE_TIME_H 1 /* Define to 1 if you have the <tld.h> header file. */ /* #undef HAVE_TLD_H */ /* Define to 1 if you have the `tld_strerror' function. */ /* #undef HAVE_TLD_STRERROR */ /* Define to 1 if you have the `uname' function. */ #define HAVE_UNAME 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the `utime' function. */ #define HAVE_UTIME 1 /* Define to 1 if you have the <utime.h> header file. */ #define HAVE_UTIME_H 1 /* Define to 1 if compiler supports C99 variadic macro style. */ #define HAVE_VARIADIC_MACROS_C99 1 /* Define to 1 if compiler supports old gcc variadic macro style. */ #define HAVE_VARIADIC_MACROS_GCC 1 /* Define to 1 if you have a working vxworks-style strerror_r function. */ #define HAVE_VXWORKS_STRERROR_R 1 /* Define to 1 if you have the winber.h header file. */ /* #undef HAVE_WINBER_H */ /* Define to 1 if you have the windows.h header file. */ /* #undef HAVE_WINDOWS_H */ /* Define to 1 if you have the winldap.h header file. */ /* #undef HAVE_WINLDAP_H */ /* Define to 1 if you have the winsock2.h header file. */ /* #undef HAVE_WINSOCK2_H */ /* Define this symbol if your OS supports changing the contents of argv */ #define HAVE_WRITABLE_ARGV 1 /* Define to 1 if you have the writev function. */ #define HAVE_WRITEV 1 /* Define to 1 if you have the ws2tcpip.h header file. */ /* #undef HAVE_WS2TCPIP_H */ /* Define to 1 if you have the <x509.h> header file. */ /* #undef HAVE_X509_H */ /* if you have the zlib.h header file */ #define HAVE_ZLIB_H 1 /* Define to 1 if you need the lber.h header file even with ldap.h */ /* #undef NEED_LBER_H */ /* Define to 1 if you need the malloc.h header file even with stdlib.h */ /* #undef NEED_MALLOC_H */ /* Define to 1 if you need the memory.h header file even with stdlib.h */ /* #undef NEED_MEMORY_H */ /* Define to 1 if _REENTRANT preprocessor symbol must be defined. */ /* #undef NEED_REENTRANT */ /* Define to 1 if _THREAD_SAFE preprocessor symbol must be defined. */ /* #undef NEED_THREAD_SAFE */ /* Define to 1 if the open function requires three arguments. */ #define OPEN_NEEDS_ARG3 1 /* cpu-machine-OS */ #define OS "unknown-unknown-vxworks" /* Name of package */ #define PACKAGE "curl" /* a suitable file to read random data from */ #define RANDOM_FILE "/dev/urandom" /* Define to the type of arg 1 for recvfrom. */ #define RECVFROM_TYPE_ARG1 int /* Define to the type pointed by arg 2 for recvfrom. */ #define RECVFROM_TYPE_ARG2 void /* Define to 1 if the type pointed by arg 2 for recvfrom is void. */ #define RECVFROM_TYPE_ARG2_IS_VOID 1 /* Define to the type of arg 3 for recvfrom. */ #define RECVFROM_TYPE_ARG3 size_t /* Define to the type of arg 4 for recvfrom. */ #define RECVFROM_TYPE_ARG4 int /* Define to the type pointed by arg 5 for recvfrom. */ #define RECVFROM_TYPE_ARG5 struct sockaddr /* Define to 1 if the type pointed by arg 5 for recvfrom is void. */ /* #undef RECVFROM_TYPE_ARG5_IS_VOID */ /* Define to the type pointed by arg 6 for recvfrom. */ #define RECVFROM_TYPE_ARG6 socklen_t /* Define to 1 if the type pointed by arg 6 for recvfrom is void. */ /* #undef RECVFROM_TYPE_ARG6_IS_VOID */ /* Define to the function return type for recvfrom. */ #define RECVFROM_TYPE_RETV int /* Define to the type of arg 1 for recv. */ #define RECV_TYPE_ARG1 int /* Define to the type of arg 2 for recv. */ #define RECV_TYPE_ARG2 void * /* Define to the type of arg 3 for recv. */ #define RECV_TYPE_ARG3 size_t /* Define to the type of arg 4 for recv. */ #define RECV_TYPE_ARG4 int /* Define to the function return type for recv. */ #define RECV_TYPE_RETV int /* Define to the type qualifier of arg 5 for select. */ #define SELECT_QUAL_ARG5 /* Define to the type of arg 1 for select. */ #define SELECT_TYPE_ARG1 int /* Define to the type of args 2, 3 and 4 for select. */ #define SELECT_TYPE_ARG234 fd_set * /* Define to the type of arg 5 for select. */ #define SELECT_TYPE_ARG5 struct timeval * /* Define to the function return type for select. */ #define SELECT_TYPE_RETV int /* Define to the type qualifier of arg 2 for send. */ #define SEND_QUAL_ARG2 const /* Define to the type of arg 1 for send. */ #define SEND_TYPE_ARG1 int /* Define to the type of arg 2 for send. */ #define SEND_TYPE_ARG2 void * /* Define to the type of arg 3 for send. */ #define SEND_TYPE_ARG3 size_t /* Define to the type of arg 4 for send. */ #define SEND_TYPE_ARG4 int /* Define to the function return type for send. */ #define SEND_TYPE_RETV int /* The size of `int', as computed by sizeof. */ #define SIZEOF_INT 4 /* The size of `long', as computed by sizeof. */ #define SIZEOF_LONG 4 /* The size of `off_t', as computed by sizeof. */ #define SIZEOF_OFF_T 8 /* The size of `short', as computed by sizeof. */ #define SIZEOF_SHORT 2 /* The size of `size_t', as computed by sizeof. */ #define SIZEOF_SIZE_T 4 /* The size of `time_t', as computed by sizeof. */ #define SIZEOF_TIME_T 4 /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define to the type of arg 3 for strerror_r. */ /* #undef STRERROR_R_TYPE_ARG3 */ /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ /* #undef TIME_WITH_SYS_TIME */ /* Define if you want to enable c-ares support */ /* #undef USE_ARES */ /* if GnuTLS is enabled */ /* #undef USE_GNUTLS */ /* if libSSH2 is in use */ /* #undef USE_LIBSSH2 */ /* If you want to build curl with the built-in manual */ #define USE_MANUAL 1 /* if NSS is enabled */ /* #undef USE_NSS */ /* if OpenSSL is in use */ #define USE_OPENSSL 1 /* Define to 1 if you are building a Windows target without large file support. */ /* #undef USE_WIN32_LARGE_FILES */ /* to enable SSPI support */ /* #undef USE_WINDOWS_SSPI */ /* Define to 1 if using yaSSL in OpenSSL compatibility mode. */ /* #undef USE_YASSLEMUL */ /* Define to avoid automatic inclusion of winsock.h */ /* #undef WIN32_LEAN_AND_MEAN */ /* Define to 1 if OS is AIX. */ #ifndef _ALL_SOURCE /* # undef _ALL_SOURCE */ #endif /* Number of bits in a file offset, on hosts where this is settable. */ /* #undef _FILE_OFFSET_BITS */ /* Define for large files, on AIX-style hosts. */ /* #undef _LARGE_FILES */ /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */ /* Type to use in place of in_addr_t when system does not provide it. */ /* #undef in_addr_t */ /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus /* #undef inline */ #endif /* Define to `unsigned int' if <sys/types.h> does not define. */ /* #undef size_t */ /* the signed version of size_t */ /* #undef ssize_t */ #endif /* HEADER_CURL_CONFIG_VXWORKS_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_sasl.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2012 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC2195 CRAM-MD5 authentication * RFC2617 Basic and Digest Access Authentication * RFC2831 DIGEST-MD5 authentication * RFC4422 Simple Authentication and Security Layer (SASL) * RFC4616 PLAIN authentication * RFC5802 SCRAM-SHA-1 authentication * RFC7677 SCRAM-SHA-256 authentication * RFC6749 OAuth 2.0 Authorization Framework * RFC7628 A Set of SASL Mechanisms for OAuth * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_IMAP) || !defined(CURL_DISABLE_SMTP) || \ !defined(CURL_DISABLE_POP3) #include <curl/curl.h> #include "urldata.h" #include "curl_base64.h" #include "curl_md5.h" #include "vauth/vauth.h" #include "vtls/vtls.h" #include "curl_hmac.h" #include "curl_sasl.h" #include "warnless.h" #include "strtok.h" #include "sendf.h" #include "non-ascii.h" /* included for Curl_convert_... prototypes */ /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* Supported mechanisms */ static const struct { const char *name; /* Name */ size_t len; /* Name length */ unsigned short bit; /* Flag bit */ } mechtable[] = { { "LOGIN", 5, SASL_MECH_LOGIN }, { "PLAIN", 5, SASL_MECH_PLAIN }, { "CRAM-MD5", 8, SASL_MECH_CRAM_MD5 }, { "DIGEST-MD5", 10, SASL_MECH_DIGEST_MD5 }, { "GSSAPI", 6, SASL_MECH_GSSAPI }, { "EXTERNAL", 8, SASL_MECH_EXTERNAL }, { "NTLM", 4, SASL_MECH_NTLM }, { "XOAUTH2", 7, SASL_MECH_XOAUTH2 }, { "OAUTHBEARER", 11, SASL_MECH_OAUTHBEARER }, { "SCRAM-SHA-1", 11, SASL_MECH_SCRAM_SHA_1 }, { "SCRAM-SHA-256",13, SASL_MECH_SCRAM_SHA_256 }, { ZERO_NULL, 0, 0 } }; /* * Curl_sasl_cleanup() * * This is used to cleanup any libraries or curl modules used by the sasl * functions. * * Parameters: * * conn [in] - The connection data. * authused [in] - The authentication mechanism used. */ void Curl_sasl_cleanup(struct connectdata *conn, unsigned short authused) { (void)conn; (void)authused; #if defined(USE_KERBEROS5) /* Cleanup the gssapi structure */ if(authused == SASL_MECH_GSSAPI) { Curl_auth_cleanup_gssapi(&conn->krb5); } #endif #if defined(USE_GSASL) /* Cleanup the GSASL structure */ if(authused & (SASL_MECH_SCRAM_SHA_1 | SASL_MECH_SCRAM_SHA_256)) { Curl_auth_gsasl_cleanup(&conn->gsasl); } #endif #if defined(USE_NTLM) /* Cleanup the NTLM structure */ if(authused == SASL_MECH_NTLM) { Curl_auth_cleanup_ntlm(&conn->ntlm); } #endif } /* * Curl_sasl_decode_mech() * * Convert a SASL mechanism name into a token. * * Parameters: * * ptr [in] - The mechanism string. * maxlen [in] - Maximum mechanism string length. * len [out] - If not NULL, effective name length. * * Returns the SASL mechanism token or 0 if no match. */ unsigned short Curl_sasl_decode_mech(const char *ptr, size_t maxlen, size_t *len) { unsigned int i; char c; for(i = 0; mechtable[i].name; i++) { if(maxlen >= mechtable[i].len && !memcmp(ptr, mechtable[i].name, mechtable[i].len)) { if(len) *len = mechtable[i].len; if(maxlen == mechtable[i].len) return mechtable[i].bit; c = ptr[mechtable[i].len]; if(!ISUPPER(c) && !ISDIGIT(c) && c != '-' && c != '_') return mechtable[i].bit; } } return 0; } /* * Curl_sasl_parse_url_auth_option() * * Parse the URL login options. */ CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, const char *value, size_t len) { CURLcode result = CURLE_OK; size_t mechlen; if(!len) return CURLE_URL_MALFORMAT; if(sasl->resetprefs) { sasl->resetprefs = FALSE; sasl->prefmech = SASL_AUTH_NONE; } if(!strncmp(value, "*", len)) sasl->prefmech = SASL_AUTH_DEFAULT; else { unsigned short mechbit = Curl_sasl_decode_mech(value, len, &mechlen); if(mechbit && mechlen == len) sasl->prefmech |= mechbit; else result = CURLE_URL_MALFORMAT; } return result; } /* * Curl_sasl_init() * * Initializes the SASL structure. */ void Curl_sasl_init(struct SASL *sasl, struct Curl_easy *data, const struct SASLproto *params) { unsigned long auth = data->set.httpauth; sasl->params = params; /* Set protocol dependent parameters */ sasl->state = SASL_STOP; /* Not yet running */ sasl->curmech = NULL; /* No mechanism yet. */ sasl->authmechs = SASL_AUTH_NONE; /* No known authentication mechanism yet */ sasl->prefmech = params->defmechs; /* Default preferred mechanisms */ sasl->authused = SASL_AUTH_NONE; /* The authentication mechanism used */ sasl->resetprefs = TRUE; /* Reset prefmech upon AUTH parsing. */ sasl->mutual_auth = FALSE; /* No mutual authentication (GSSAPI only) */ sasl->force_ir = FALSE; /* Respect external option */ if(auth != CURLAUTH_BASIC) { sasl->resetprefs = FALSE; sasl->prefmech = SASL_AUTH_NONE; if(auth & CURLAUTH_BASIC) sasl->prefmech |= SASL_MECH_PLAIN | SASL_MECH_LOGIN; if(auth & CURLAUTH_DIGEST) sasl->prefmech |= SASL_MECH_DIGEST_MD5; if(auth & CURLAUTH_NTLM) sasl->prefmech |= SASL_MECH_NTLM; if(auth & CURLAUTH_BEARER) sasl->prefmech |= SASL_MECH_OAUTHBEARER | SASL_MECH_XOAUTH2; if(auth & CURLAUTH_GSSAPI) sasl->prefmech |= SASL_MECH_GSSAPI; } } /* * state() * * This is the ONLY way to change SASL state! */ static void state(struct SASL *sasl, struct Curl_easy *data, saslstate newstate) { #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[]={ "STOP", "PLAIN", "LOGIN", "LOGIN_PASSWD", "EXTERNAL", "CRAMMD5", "DIGESTMD5", "DIGESTMD5_RESP", "NTLM", "NTLM_TYPE2MSG", "GSSAPI", "GSSAPI_TOKEN", "GSSAPI_NO_DATA", "OAUTH2", "OAUTH2_RESP", "GSASL", "CANCEL", "FINAL", /* LAST */ }; if(sasl->state != newstate) infof(data, "SASL %p state change from %s to %s", (void *)sasl, names[sasl->state], names[newstate]); #else (void) data; #endif sasl->state = newstate; } /* Get the SASL server message and convert it to binary. */ static CURLcode get_server_message(struct SASL *sasl, struct Curl_easy *data, struct bufref *out) { CURLcode result = CURLE_OK; result = sasl->params->getmessage(data, out); if(!result && (sasl->params->flags & SASL_FLAG_BASE64)) { unsigned char *msg; size_t msglen; const char *serverdata = (const char *) Curl_bufref_ptr(out); if(!*serverdata || *serverdata == '=') Curl_bufref_set(out, NULL, 0, NULL); else { result = Curl_base64_decode(serverdata, &msg, &msglen); if(!result) Curl_bufref_set(out, msg, msglen, curl_free); } } return result; } /* Encode the outgoing SASL message. */ static CURLcode build_message(struct SASL *sasl, struct Curl_easy *data, struct bufref *msg) { CURLcode result = CURLE_OK; if(sasl->params->flags & SASL_FLAG_BASE64) { if(!Curl_bufref_ptr(msg)) /* Empty message. */ Curl_bufref_set(msg, "", 0, NULL); else if(!Curl_bufref_len(msg)) /* Explicit empty response. */ Curl_bufref_set(msg, "=", 1, NULL); else { char *base64; size_t base64len; result = Curl_base64_encode(data, (const char *) Curl_bufref_ptr(msg), Curl_bufref_len(msg), &base64, &base64len); if(!result) Curl_bufref_set(msg, base64, base64len, curl_free); } } return result; } /* * Curl_sasl_can_authenticate() * * Check if we have enough auth data and capabilities to authenticate. */ bool Curl_sasl_can_authenticate(struct SASL *sasl, struct connectdata *conn) { /* Have credentials been provided? */ if(conn->bits.user_passwd) return TRUE; /* EXTERNAL can authenticate without a user name and/or password */ if(sasl->authmechs & sasl->prefmech & SASL_MECH_EXTERNAL) return TRUE; return FALSE; } /* * Curl_sasl_start() * * Calculate the required login details for SASL authentication. */ CURLcode Curl_sasl_start(struct SASL *sasl, struct Curl_easy *data, bool force_ir, saslprogress *progress) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; unsigned short enabledmechs; const char *mech = NULL; struct bufref resp; saslstate state1 = SASL_STOP; saslstate state2 = SASL_FINAL; const char * const hostname = SSL_HOST_NAME(); const long int port = SSL_HOST_PORT(); #if defined(USE_KERBEROS5) || defined(USE_NTLM) const char *service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : sasl->params->service; #endif const char *oauth_bearer = data->set.str[STRING_BEARER]; struct bufref nullmsg; Curl_bufref_init(&nullmsg); Curl_bufref_init(&resp); sasl->force_ir = force_ir; /* Latch for future use */ sasl->authused = 0; /* No mechanism used yet */ enabledmechs = sasl->authmechs & sasl->prefmech; *progress = SASL_IDLE; /* Calculate the supported authentication mechanism, by decreasing order of security, as well as the initial response where appropriate */ if((enabledmechs & SASL_MECH_EXTERNAL) && !conn->passwd[0]) { mech = SASL_MECH_STRING_EXTERNAL; state1 = SASL_EXTERNAL; sasl->authused = SASL_MECH_EXTERNAL; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_external_message(conn->user, &resp); } else if(conn->bits.user_passwd) { #if defined(USE_KERBEROS5) if((enabledmechs & SASL_MECH_GSSAPI) && Curl_auth_is_gssapi_supported() && Curl_auth_user_contains_domain(conn->user)) { sasl->mutual_auth = FALSE; mech = SASL_MECH_STRING_GSSAPI; state1 = SASL_GSSAPI; state2 = SASL_GSSAPI_TOKEN; sasl->authused = SASL_MECH_GSSAPI; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_gssapi_user_message(data, conn->user, conn->passwd, service, conn->host.name, sasl->mutual_auth, NULL, &conn->krb5, &resp); } else #endif #ifdef USE_GSASL if((enabledmechs & SASL_MECH_SCRAM_SHA_256) && Curl_auth_gsasl_is_supported(data, SASL_MECH_STRING_SCRAM_SHA_256, &conn->gsasl)) { mech = SASL_MECH_STRING_SCRAM_SHA_256; sasl->authused = SASL_MECH_SCRAM_SHA_256; state1 = SASL_GSASL; state2 = SASL_GSASL; result = Curl_auth_gsasl_start(data, conn->user, conn->passwd, &conn->gsasl); if(result == CURLE_OK && (force_ir || data->set.sasl_ir)) result = Curl_auth_gsasl_token(data, &nullmsg, &conn->gsasl, &resp); } else if((enabledmechs & SASL_MECH_SCRAM_SHA_1) && Curl_auth_gsasl_is_supported(data, SASL_MECH_STRING_SCRAM_SHA_1, &conn->gsasl)) { mech = SASL_MECH_STRING_SCRAM_SHA_1; sasl->authused = SASL_MECH_SCRAM_SHA_1; state1 = SASL_GSASL; state2 = SASL_GSASL; result = Curl_auth_gsasl_start(data, conn->user, conn->passwd, &conn->gsasl); if(result == CURLE_OK && (force_ir || data->set.sasl_ir)) result = Curl_auth_gsasl_token(data, &nullmsg, &conn->gsasl, &resp); } else #endif #ifndef CURL_DISABLE_CRYPTO_AUTH if((enabledmechs & SASL_MECH_DIGEST_MD5) && Curl_auth_is_digest_supported()) { mech = SASL_MECH_STRING_DIGEST_MD5; state1 = SASL_DIGESTMD5; sasl->authused = SASL_MECH_DIGEST_MD5; } else if(enabledmechs & SASL_MECH_CRAM_MD5) { mech = SASL_MECH_STRING_CRAM_MD5; state1 = SASL_CRAMMD5; sasl->authused = SASL_MECH_CRAM_MD5; } else #endif #ifdef USE_NTLM if((enabledmechs & SASL_MECH_NTLM) && Curl_auth_is_ntlm_supported()) { mech = SASL_MECH_STRING_NTLM; state1 = SASL_NTLM; state2 = SASL_NTLM_TYPE2MSG; sasl->authused = SASL_MECH_NTLM; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_ntlm_type1_message(data, conn->user, conn->passwd, service, hostname, &conn->ntlm, &resp); } else #endif if((enabledmechs & SASL_MECH_OAUTHBEARER) && oauth_bearer) { mech = SASL_MECH_STRING_OAUTHBEARER; state1 = SASL_OAUTH2; state2 = SASL_OAUTH2_RESP; sasl->authused = SASL_MECH_OAUTHBEARER; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_oauth_bearer_message(conn->user, hostname, port, oauth_bearer, &resp); } else if((enabledmechs & SASL_MECH_XOAUTH2) && oauth_bearer) { mech = SASL_MECH_STRING_XOAUTH2; state1 = SASL_OAUTH2; sasl->authused = SASL_MECH_XOAUTH2; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_xoauth_bearer_message(conn->user, oauth_bearer, &resp); } else if(enabledmechs & SASL_MECH_PLAIN) { mech = SASL_MECH_STRING_PLAIN; state1 = SASL_PLAIN; sasl->authused = SASL_MECH_PLAIN; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_plain_message(conn->sasl_authzid, conn->user, conn->passwd, &resp); } else if(enabledmechs & SASL_MECH_LOGIN) { mech = SASL_MECH_STRING_LOGIN; state1 = SASL_LOGIN; state2 = SASL_LOGIN_PASSWD; sasl->authused = SASL_MECH_LOGIN; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_login_message(conn->user, &resp); } } if(!result && mech) { sasl->curmech = mech; if(Curl_bufref_ptr(&resp)) result = build_message(sasl, data, &resp); if(sasl->params->maxirlen && strlen(mech) + Curl_bufref_len(&resp) > sasl->params->maxirlen) Curl_bufref_free(&resp); if(!result) result = sasl->params->sendauth(data, mech, &resp); if(!result) { *progress = SASL_INPROGRESS; state(sasl, data, Curl_bufref_ptr(&resp) ? state2 : state1); } } Curl_bufref_free(&resp); return result; } /* * Curl_sasl_continue() * * Continue the authentication. */ CURLcode Curl_sasl_continue(struct SASL *sasl, struct Curl_easy *data, int code, saslprogress *progress) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; saslstate newstate = SASL_FINAL; struct bufref resp; const char * const hostname = SSL_HOST_NAME(); const long int port = SSL_HOST_PORT(); #if !defined(CURL_DISABLE_CRYPTO_AUTH) || defined(USE_KERBEROS5) || \ defined(USE_NTLM) const char *service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : sasl->params->service; #endif const char *oauth_bearer = data->set.str[STRING_BEARER]; struct bufref serverdata; Curl_bufref_init(&serverdata); Curl_bufref_init(&resp); *progress = SASL_INPROGRESS; if(sasl->state == SASL_FINAL) { if(code != sasl->params->finalcode) result = CURLE_LOGIN_DENIED; *progress = SASL_DONE; state(sasl, data, SASL_STOP); return result; } if(sasl->state != SASL_CANCEL && sasl->state != SASL_OAUTH2_RESP && code != sasl->params->contcode) { *progress = SASL_DONE; state(sasl, data, SASL_STOP); return CURLE_LOGIN_DENIED; } switch(sasl->state) { case SASL_STOP: *progress = SASL_DONE; return result; case SASL_PLAIN: result = Curl_auth_create_plain_message(conn->sasl_authzid, conn->user, conn->passwd, &resp); break; case SASL_LOGIN: result = Curl_auth_create_login_message(conn->user, &resp); newstate = SASL_LOGIN_PASSWD; break; case SASL_LOGIN_PASSWD: result = Curl_auth_create_login_message(conn->passwd, &resp); break; case SASL_EXTERNAL: result = Curl_auth_create_external_message(conn->user, &resp); break; #ifndef CURL_DISABLE_CRYPTO_AUTH #ifdef USE_GSASL case SASL_GSASL: result = get_server_message(sasl, data, &serverdata); if(!result) result = Curl_auth_gsasl_token(data, &serverdata, &conn->gsasl, &resp); if(!result && Curl_bufref_len(&resp) > 0) newstate = SASL_GSASL; break; #endif case SASL_CRAMMD5: result = get_server_message(sasl, data, &serverdata); if(!result) result = Curl_auth_create_cram_md5_message(&serverdata, conn->user, conn->passwd, &resp); break; case SASL_DIGESTMD5: result = get_server_message(sasl, data, &serverdata); if(!result) result = Curl_auth_create_digest_md5_message(data, &serverdata, conn->user, conn->passwd, service, &resp); if(!result && (sasl->params->flags & SASL_FLAG_BASE64)) newstate = SASL_DIGESTMD5_RESP; break; case SASL_DIGESTMD5_RESP: /* Keep response NULL to output an empty line. */ break; #endif #ifdef USE_NTLM case SASL_NTLM: /* Create the type-1 message */ result = Curl_auth_create_ntlm_type1_message(data, conn->user, conn->passwd, service, hostname, &conn->ntlm, &resp); newstate = SASL_NTLM_TYPE2MSG; break; case SASL_NTLM_TYPE2MSG: /* Decode the type-2 message */ result = get_server_message(sasl, data, &serverdata); if(!result) result = Curl_auth_decode_ntlm_type2_message(data, &serverdata, &conn->ntlm); if(!result) result = Curl_auth_create_ntlm_type3_message(data, conn->user, conn->passwd, &conn->ntlm, &resp); break; #endif #if defined(USE_KERBEROS5) case SASL_GSSAPI: result = Curl_auth_create_gssapi_user_message(data, conn->user, conn->passwd, service, conn->host.name, sasl->mutual_auth, NULL, &conn->krb5, &resp); newstate = SASL_GSSAPI_TOKEN; break; case SASL_GSSAPI_TOKEN: result = get_server_message(sasl, data, &serverdata); if(!result) { if(sasl->mutual_auth) { /* Decode the user token challenge and create the optional response message */ result = Curl_auth_create_gssapi_user_message(data, NULL, NULL, NULL, NULL, sasl->mutual_auth, &serverdata, &conn->krb5, &resp); newstate = SASL_GSSAPI_NO_DATA; } else /* Decode the security challenge and create the response message */ result = Curl_auth_create_gssapi_security_message(data, conn->sasl_authzid, &serverdata, &conn->krb5, &resp); } break; case SASL_GSSAPI_NO_DATA: /* Decode the security challenge and create the response message */ result = get_server_message(sasl, data, &serverdata); if(!result) result = Curl_auth_create_gssapi_security_message(data, conn->sasl_authzid, &serverdata, &conn->krb5, &resp); break; #endif case SASL_OAUTH2: /* Create the authorisation message */ if(sasl->authused == SASL_MECH_OAUTHBEARER) { result = Curl_auth_create_oauth_bearer_message(conn->user, hostname, port, oauth_bearer, &resp); /* Failures maybe sent by the server as continuations for OAUTHBEARER */ newstate = SASL_OAUTH2_RESP; } else result = Curl_auth_create_xoauth_bearer_message(conn->user, oauth_bearer, &resp); break; case SASL_OAUTH2_RESP: /* The continuation is optional so check the response code */ if(code == sasl->params->finalcode) { /* Final response was received so we are done */ *progress = SASL_DONE; state(sasl, data, SASL_STOP); return result; } else if(code == sasl->params->contcode) { /* Acknowledge the continuation by sending a 0x01 response. */ Curl_bufref_set(&resp, "\x01", 1, NULL); break; } else { *progress = SASL_DONE; state(sasl, data, SASL_STOP); return CURLE_LOGIN_DENIED; } case SASL_CANCEL: /* Remove the offending mechanism from the supported list */ sasl->authmechs ^= sasl->authused; /* Start an alternative SASL authentication */ return Curl_sasl_start(sasl, data, sasl->force_ir, progress); default: failf(data, "Unsupported SASL authentication mechanism"); result = CURLE_UNSUPPORTED_PROTOCOL; /* Should not happen */ break; } Curl_bufref_free(&serverdata); switch(result) { case CURLE_BAD_CONTENT_ENCODING: /* Cancel dialog */ result = sasl->params->cancelauth(data, sasl->curmech); newstate = SASL_CANCEL; break; case CURLE_OK: result = build_message(sasl, data, &resp); if(!result) result = sasl->params->contauth(data, sasl->curmech, &resp); break; default: newstate = SASL_STOP; /* Stop on error */ *progress = SASL_DONE; break; } Curl_bufref_free(&resp); state(sasl, data, newstate); return result; } #endif /* protocols are enabled that use SASL */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/http_digest.h
#ifndef HEADER_CURL_HTTP_DIGEST_H #define HEADER_CURL_HTTP_DIGEST_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) /* this is for digest header input */ CURLcode Curl_input_digest(struct Curl_easy *data, bool proxy, const char *header); /* this is for creating digest header output */ CURLcode Curl_output_digest(struct Curl_easy *data, bool proxy, const unsigned char *request, const unsigned char *uripath); void Curl_http_auth_cleanup_digest(struct Curl_easy *data); #endif /* !CURL_DISABLE_HTTP && !CURL_DISABLE_CRYPTO_AUTH */ #endif /* HEADER_CURL_HTTP_DIGEST_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/rand.h
#ifndef HEADER_CURL_RAND_H #define HEADER_CURL_RAND_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Curl_rand() stores 'num' number of random unsigned characters in the buffer * 'rnd' points to. * * If libcurl is built without TLS support or with a TLS backend that lacks a * proper random API (Gskit or mbedTLS), this function will use "weak" random. * * When built *with* TLS support and a backend that offers strong random, it * will return error if it cannot provide strong random values. * * NOTE: 'data' may be passed in as NULL when coming from external API without * easy handle! * */ CURLcode Curl_rand(struct Curl_easy *data, unsigned char *rnd, size_t num); /* * Curl_rand_hex() fills the 'rnd' buffer with a given 'num' size with random * hexadecimal digits PLUS a zero terminating byte. It must be an odd number * size. */ CURLcode Curl_rand_hex(struct Curl_easy *data, unsigned char *rnd, size_t num); #endif /* HEADER_CURL_RAND_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/socketpair.h
#ifndef HEADER_CURL_SOCKETPAIR_H #define HEADER_CURL_SOCKETPAIR_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2019 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef HAVE_SOCKETPAIR int Curl_socketpair(int domain, int type, int protocol, curl_socket_t socks[2]); #else #define Curl_socketpair(a,b,c,d) socketpair(a,b,c,d) #endif #endif /* HEADER_CURL_SOCKETPAIR_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/asyn-thread.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "socketpair.h" /*********************************************************************** * Only for threaded name resolves builds **********************************************************************/ #ifdef CURLRES_THREADED #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #if defined(USE_THREADS_POSIX) # ifdef HAVE_PTHREAD_H # include <pthread.h> # endif #elif defined(USE_THREADS_WIN32) # ifdef HAVE_PROCESS_H # include <process.h> # endif #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif #ifdef HAVE_GETADDRINFO # define RESOLVER_ENOMEM EAI_MEMORY #else # define RESOLVER_ENOMEM ENOMEM #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "url.h" #include "multiif.h" #include "inet_ntop.h" #include "curl_threads.h" #include "connect.h" #include "socketpair.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" struct resdata { struct curltime start; }; /* * Curl_resolver_global_init() * Called from curl_global_init() to initialize global resolver environment. * Does nothing here. */ int Curl_resolver_global_init(void) { return CURLE_OK; } /* * Curl_resolver_global_cleanup() * Called from curl_global_cleanup() to destroy global resolver environment. * Does nothing here. */ void Curl_resolver_global_cleanup(void) { } /* * Curl_resolver_init() * Called from curl_easy_init() -> Curl_open() to initialize resolver * URL-state specific environment ('resolver' member of the UrlState * structure). */ CURLcode Curl_resolver_init(struct Curl_easy *easy, void **resolver) { (void)easy; *resolver = calloc(1, sizeof(struct resdata)); if(!*resolver) return CURLE_OUT_OF_MEMORY; return CURLE_OK; } /* * Curl_resolver_cleanup() * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver * URL-state specific environment ('resolver' member of the UrlState * structure). */ void Curl_resolver_cleanup(void *resolver) { free(resolver); } /* * Curl_resolver_duphandle() * Called from curl_easy_duphandle() to duplicate resolver URL state-specific * environment ('resolver' member of the UrlState structure). */ CURLcode Curl_resolver_duphandle(struct Curl_easy *easy, void **to, void *from) { (void)from; return Curl_resolver_init(easy, to); } static void destroy_async_data(struct Curl_async *); /* * Cancel all possibly still on-going resolves for this connection. */ void Curl_resolver_cancel(struct Curl_easy *data) { destroy_async_data(&data->state.async); } /* This function is used to init a threaded resolve */ static bool init_resolve_thread(struct Curl_easy *data, const char *hostname, int port, const struct addrinfo *hints); /* Data for synchronization between resolver thread and its parent */ struct thread_sync_data { curl_mutex_t *mtx; int done; int port; char *hostname; /* hostname to resolve, Curl_async.hostname duplicate */ #ifndef CURL_DISABLE_SOCKETPAIR struct Curl_easy *data; curl_socket_t sock_pair[2]; /* socket pair */ #endif int sock_error; struct Curl_addrinfo *res; #ifdef HAVE_GETADDRINFO struct addrinfo hints; #endif struct thread_data *td; /* for thread-self cleanup */ }; struct thread_data { curl_thread_t thread_hnd; unsigned int poll_interval; timediff_t interval_end; struct thread_sync_data tsd; }; static struct thread_sync_data *conn_thread_sync_data(struct Curl_easy *data) { return &(data->state.async.tdata->tsd); } /* Destroy resolver thread synchronization data */ static void destroy_thread_sync_data(struct thread_sync_data *tsd) { if(tsd->mtx) { Curl_mutex_destroy(tsd->mtx); free(tsd->mtx); } free(tsd->hostname); if(tsd->res) Curl_freeaddrinfo(tsd->res); #ifndef CURL_DISABLE_SOCKETPAIR /* * close one end of the socket pair (may be done in resolver thread); * the other end (for reading) is always closed in the parent thread. */ if(tsd->sock_pair[1] != CURL_SOCKET_BAD) { sclose(tsd->sock_pair[1]); } #endif memset(tsd, 0, sizeof(*tsd)); } /* Initialize resolver thread synchronization data */ static int init_thread_sync_data(struct thread_data *td, const char *hostname, int port, const struct addrinfo *hints) { struct thread_sync_data *tsd = &td->tsd; memset(tsd, 0, sizeof(*tsd)); tsd->td = td; tsd->port = port; /* Treat the request as done until the thread actually starts so any early * cleanup gets done properly. */ tsd->done = 1; #ifdef HAVE_GETADDRINFO DEBUGASSERT(hints); tsd->hints = *hints; #else (void) hints; #endif tsd->mtx = malloc(sizeof(curl_mutex_t)); if(!tsd->mtx) goto err_exit; Curl_mutex_init(tsd->mtx); #ifndef CURL_DISABLE_SOCKETPAIR /* create socket pair, avoid AF_LOCAL since it doesn't build on Solaris */ if(Curl_socketpair(AF_UNIX, SOCK_STREAM, 0, &tsd->sock_pair[0]) < 0) { tsd->sock_pair[0] = CURL_SOCKET_BAD; tsd->sock_pair[1] = CURL_SOCKET_BAD; goto err_exit; } #endif tsd->sock_error = CURL_ASYNC_SUCCESS; /* Copying hostname string because original can be destroyed by parent * thread during gethostbyname execution. */ tsd->hostname = strdup(hostname); if(!tsd->hostname) goto err_exit; return 1; err_exit: /* Memory allocation failed */ destroy_thread_sync_data(tsd); return 0; } static int getaddrinfo_complete(struct Curl_easy *data) { struct thread_sync_data *tsd = conn_thread_sync_data(data); int rc; rc = Curl_addrinfo_callback(data, tsd->sock_error, tsd->res); /* The tsd->res structure has been copied to async.dns and perhaps the DNS cache. Set our copy to NULL so destroy_thread_sync_data doesn't free it. */ tsd->res = NULL; return rc; } #ifdef HAVE_GETADDRINFO /* * getaddrinfo_thread() resolves a name and then exits. * * For builds without ARES, but with ENABLE_IPV6, create a resolver thread * and wait on it. */ static unsigned int CURL_STDCALL getaddrinfo_thread(void *arg) { struct thread_sync_data *tsd = (struct thread_sync_data *)arg; struct thread_data *td = tsd->td; char service[12]; int rc; #ifndef CURL_DISABLE_SOCKETPAIR char buf[1]; #endif msnprintf(service, sizeof(service), "%d", tsd->port); rc = Curl_getaddrinfo_ex(tsd->hostname, service, &tsd->hints, &tsd->res); if(rc) { tsd->sock_error = SOCKERRNO?SOCKERRNO:rc; if(tsd->sock_error == 0) tsd->sock_error = RESOLVER_ENOMEM; } else { Curl_addrinfo_set_port(tsd->res, tsd->port); } Curl_mutex_acquire(tsd->mtx); if(tsd->done) { /* too late, gotta clean up the mess */ Curl_mutex_release(tsd->mtx); destroy_thread_sync_data(tsd); free(td); } else { #ifndef CURL_DISABLE_SOCKETPAIR if(tsd->sock_pair[1] != CURL_SOCKET_BAD) { /* DNS has been resolved, signal client task */ buf[0] = 1; if(swrite(tsd->sock_pair[1], buf, sizeof(buf)) < 0) { /* update sock_erro to errno */ tsd->sock_error = SOCKERRNO; } } #endif tsd->done = 1; Curl_mutex_release(tsd->mtx); } return 0; } #else /* HAVE_GETADDRINFO */ /* * gethostbyname_thread() resolves a name and then exits. */ static unsigned int CURL_STDCALL gethostbyname_thread(void *arg) { struct thread_sync_data *tsd = (struct thread_sync_data *)arg; struct thread_data *td = tsd->td; tsd->res = Curl_ipv4_resolve_r(tsd->hostname, tsd->port); if(!tsd->res) { tsd->sock_error = SOCKERRNO; if(tsd->sock_error == 0) tsd->sock_error = RESOLVER_ENOMEM; } Curl_mutex_acquire(tsd->mtx); if(tsd->done) { /* too late, gotta clean up the mess */ Curl_mutex_release(tsd->mtx); destroy_thread_sync_data(tsd); free(td); } else { tsd->done = 1; Curl_mutex_release(tsd->mtx); } return 0; } #endif /* HAVE_GETADDRINFO */ /* * destroy_async_data() cleans up async resolver data and thread handle. */ static void destroy_async_data(struct Curl_async *async) { if(async->tdata) { struct thread_data *td = async->tdata; int done; #ifndef CURL_DISABLE_SOCKETPAIR curl_socket_t sock_rd = td->tsd.sock_pair[0]; struct Curl_easy *data = td->tsd.data; #endif /* * if the thread is still blocking in the resolve syscall, detach it and * let the thread do the cleanup... */ Curl_mutex_acquire(td->tsd.mtx); done = td->tsd.done; td->tsd.done = 1; Curl_mutex_release(td->tsd.mtx); if(!done) { Curl_thread_destroy(td->thread_hnd); } else { if(td->thread_hnd != curl_thread_t_null) Curl_thread_join(&td->thread_hnd); destroy_thread_sync_data(&td->tsd); free(async->tdata); } #ifndef CURL_DISABLE_SOCKETPAIR /* * ensure CURLMOPT_SOCKETFUNCTION fires CURL_POLL_REMOVE * before the FD is invalidated to avoid EBADF on EPOLL_CTL_DEL */ Curl_multi_closed(data, sock_rd); sclose(sock_rd); #endif } async->tdata = NULL; free(async->hostname); async->hostname = NULL; } /* * init_resolve_thread() starts a new thread that performs the actual * resolve. This function returns before the resolve is done. * * Returns FALSE in case of failure, otherwise TRUE. */ static bool init_resolve_thread(struct Curl_easy *data, const char *hostname, int port, const struct addrinfo *hints) { struct thread_data *td = calloc(1, sizeof(struct thread_data)); int err = ENOMEM; struct Curl_async *asp = &data->state.async; data->state.async.tdata = td; if(!td) goto errno_exit; asp->port = port; asp->done = FALSE; asp->status = 0; asp->dns = NULL; td->thread_hnd = curl_thread_t_null; if(!init_thread_sync_data(td, hostname, port, hints)) { asp->tdata = NULL; free(td); goto errno_exit; } free(asp->hostname); asp->hostname = strdup(hostname); if(!asp->hostname) goto err_exit; /* The thread will set this to 1 when complete. */ td->tsd.done = 0; #ifdef HAVE_GETADDRINFO td->thread_hnd = Curl_thread_create(getaddrinfo_thread, &td->tsd); #else td->thread_hnd = Curl_thread_create(gethostbyname_thread, &td->tsd); #endif if(!td->thread_hnd) { /* The thread never started, so mark it as done here for proper cleanup. */ td->tsd.done = 1; err = errno; goto err_exit; } return TRUE; err_exit: destroy_async_data(asp); errno_exit: errno = err; return FALSE; } /* * 'entry' may be NULL and then no data is returned */ static CURLcode thread_wait_resolv(struct Curl_easy *data, struct Curl_dns_entry **entry, bool report) { struct thread_data *td; CURLcode result = CURLE_OK; DEBUGASSERT(data); td = data->state.async.tdata; DEBUGASSERT(td); DEBUGASSERT(td->thread_hnd != curl_thread_t_null); /* wait for the thread to resolve the name */ if(Curl_thread_join(&td->thread_hnd)) { if(entry) result = getaddrinfo_complete(data); } else DEBUGASSERT(0); data->state.async.done = TRUE; if(entry) *entry = data->state.async.dns; if(!data->state.async.dns && report) /* a name was not resolved, report error */ result = Curl_resolver_error(data); destroy_async_data(&data->state.async); if(!data->state.async.dns && report) connclose(data->conn, "asynch resolve failed"); return result; } /* * Until we gain a way to signal the resolver threads to stop early, we must * simply wait for them and ignore their results. */ void Curl_resolver_kill(struct Curl_easy *data) { struct thread_data *td = data->state.async.tdata; /* If we're still resolving, we must wait for the threads to fully clean up, unfortunately. Otherwise, we can simply cancel to clean up any resolver data. */ if(td && td->thread_hnd != curl_thread_t_null) (void)thread_wait_resolv(data, NULL, FALSE); else Curl_resolver_cancel(data); } /* * Curl_resolver_wait_resolv() * * Waits for a resolve to finish. This function should be avoided since using * this risk getting the multi interface to "hang". * * If 'entry' is non-NULL, make it point to the resolved dns entry * * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, * CURLE_OPERATION_TIMEDOUT if a time-out occurred, or other errors. * * This is the version for resolves-in-a-thread. */ CURLcode Curl_resolver_wait_resolv(struct Curl_easy *data, struct Curl_dns_entry **entry) { return thread_wait_resolv(data, entry, TRUE); } /* * Curl_resolver_is_resolved() is called repeatedly to check if a previous * name resolve request has completed. It should also make sure to time-out if * the operation seems to take too long. */ CURLcode Curl_resolver_is_resolved(struct Curl_easy *data, struct Curl_dns_entry **entry) { struct thread_data *td = data->state.async.tdata; int done = 0; DEBUGASSERT(entry); *entry = NULL; if(!td) { DEBUGASSERT(td); return CURLE_COULDNT_RESOLVE_HOST; } Curl_mutex_acquire(td->tsd.mtx); done = td->tsd.done; Curl_mutex_release(td->tsd.mtx); if(done) { getaddrinfo_complete(data); if(!data->state.async.dns) { CURLcode result = Curl_resolver_error(data); destroy_async_data(&data->state.async); return result; } destroy_async_data(&data->state.async); *entry = data->state.async.dns; } else { /* poll for name lookup done with exponential backoff up to 250ms */ /* should be fine even if this converts to 32 bit */ timediff_t elapsed = Curl_timediff(Curl_now(), data->progress.t_startsingle); if(elapsed < 0) elapsed = 0; if(td->poll_interval == 0) /* Start at 1ms poll interval */ td->poll_interval = 1; else if(elapsed >= td->interval_end) /* Back-off exponentially if last interval expired */ td->poll_interval *= 2; if(td->poll_interval > 250) td->poll_interval = 250; td->interval_end = elapsed + td->poll_interval; Curl_expire(data, td->poll_interval, EXPIRE_ASYNC_NAME); } return CURLE_OK; } int Curl_resolver_getsock(struct Curl_easy *data, curl_socket_t *socks) { int ret_val = 0; timediff_t milli; timediff_t ms; struct resdata *reslv = (struct resdata *)data->state.async.resolver; #ifndef CURL_DISABLE_SOCKETPAIR struct thread_data *td = data->state.async.tdata; #else (void)socks; #endif #ifndef CURL_DISABLE_SOCKETPAIR if(td) { /* return read fd to client for polling the DNS resolution status */ socks[0] = td->tsd.sock_pair[0]; td->tsd.data = data; ret_val = GETSOCK_READSOCK(0); } else { #endif ms = Curl_timediff(Curl_now(), reslv->start); if(ms < 3) milli = 0; else if(ms <= 50) milli = ms/3; else if(ms <= 250) milli = 50; else milli = 200; Curl_expire(data, milli, EXPIRE_ASYNC_NAME); #ifndef CURL_DISABLE_SOCKETPAIR } #endif return ret_val; } #ifndef HAVE_GETADDRINFO /* * Curl_getaddrinfo() - for platforms without getaddrinfo */ struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data, const char *hostname, int port, int *waitp) { struct resdata *reslv = (struct resdata *)data->state.async.resolver; *waitp = 0; /* default to synchronous response */ reslv->start = Curl_now(); /* fire up a new resolver thread! */ if(init_resolve_thread(data, hostname, port, NULL)) { *waitp = 1; /* expect asynchronous response */ return NULL; } failf(data, "getaddrinfo() thread failed"); return NULL; } #else /* !HAVE_GETADDRINFO */ /* * Curl_resolver_getaddrinfo() - for getaddrinfo */ struct Curl_addrinfo *Curl_resolver_getaddrinfo(struct Curl_easy *data, const char *hostname, int port, int *waitp) { struct addrinfo hints; int pf = PF_INET; struct resdata *reslv = (struct resdata *)data->state.async.resolver; *waitp = 0; /* default to synchronous response */ #ifdef CURLRES_IPV6 if(Curl_ipv6works(data)) /* The stack seems to be IPv6-enabled */ pf = PF_UNSPEC; #endif /* CURLRES_IPV6 */ memset(&hints, 0, sizeof(hints)); hints.ai_family = pf; hints.ai_socktype = (data->conn->transport == TRNSPRT_TCP)? SOCK_STREAM : SOCK_DGRAM; reslv->start = Curl_now(); /* fire up a new resolver thread! */ if(init_resolve_thread(data, hostname, port, &hints)) { *waitp = 1; /* expect asynchronous response */ return NULL; } failf(data, "getaddrinfo() thread failed to start"); return NULL; } #endif /* !HAVE_GETADDRINFO */ CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers) { (void)data; (void)servers; return CURLE_NOT_BUILT_IN; } CURLcode Curl_set_dns_interface(struct Curl_easy *data, const char *interf) { (void)data; (void)interf; return CURLE_NOT_BUILT_IN; } CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, const char *local_ip4) { (void)data; (void)local_ip4; return CURLE_NOT_BUILT_IN; } CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, const char *local_ip6) { (void)data; (void)local_ip6; return CURLE_NOT_BUILT_IN; } #endif /* CURLRES_THREADED */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_gssapi.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2011 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_GSSAPI #include "curl_gssapi.h" #include "sendf.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" gss_OID_desc Curl_spnego_mech_oid = { 6, (char *)"\x2b\x06\x01\x05\x05\x02" }; gss_OID_desc Curl_krb5_mech_oid = { 9, (char *)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" }; OM_uint32 Curl_gss_init_sec_context( struct Curl_easy *data, OM_uint32 *minor_status, gss_ctx_id_t *context, gss_name_t target_name, gss_OID mech_type, gss_channel_bindings_t input_chan_bindings, gss_buffer_t input_token, gss_buffer_t output_token, const bool mutual_auth, OM_uint32 *ret_flags) { OM_uint32 req_flags = GSS_C_REPLAY_FLAG; if(mutual_auth) req_flags |= GSS_C_MUTUAL_FLAG; if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_POLICY_FLAG) { #ifdef GSS_C_DELEG_POLICY_FLAG req_flags |= GSS_C_DELEG_POLICY_FLAG; #else infof(data, "warning: support for CURLGSSAPI_DELEGATION_POLICY_FLAG not " "compiled in"); #endif } if(data->set.gssapi_delegation & CURLGSSAPI_DELEGATION_FLAG) req_flags |= GSS_C_DELEG_FLAG; return gss_init_sec_context(minor_status, GSS_C_NO_CREDENTIAL, /* cred_handle */ context, target_name, mech_type, req_flags, 0, /* time_req */ input_chan_bindings, input_token, NULL, /* actual_mech_type */ output_token, ret_flags, NULL /* time_rec */); } #define GSS_LOG_BUFFER_LEN 1024 static size_t display_gss_error(OM_uint32 status, int type, char *buf, size_t len) { OM_uint32 maj_stat; OM_uint32 min_stat; OM_uint32 msg_ctx = 0; gss_buffer_desc status_string; do { maj_stat = gss_display_status(&min_stat, status, type, GSS_C_NO_OID, &msg_ctx, &status_string); if(GSS_LOG_BUFFER_LEN > len + status_string.length + 3) { len += msnprintf(buf + len, GSS_LOG_BUFFER_LEN - len, "%.*s. ", (int)status_string.length, (char *)status_string.value); } gss_release_buffer(&min_stat, &status_string); } while(!GSS_ERROR(maj_stat) && msg_ctx); return len; } /* * Curl_gss_log_error() * * This is used to log a GSS-API error status. * * Parameters: * * data [in] - The session handle. * prefix [in] - The prefix of the log message. * major [in] - The major status code. * minor [in] - The minor status code. */ void Curl_gss_log_error(struct Curl_easy *data, const char *prefix, OM_uint32 major, OM_uint32 minor) { char buf[GSS_LOG_BUFFER_LEN]; size_t len = 0; if(major != GSS_S_FAILURE) len = display_gss_error(major, GSS_C_GSS_CODE, buf, len); display_gss_error(minor, GSS_C_MECH_CODE, buf, len); infof(data, "%s%s", prefix, buf); #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)data; (void)prefix; #endif } #endif /* HAVE_GSSAPI */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/psl.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #ifdef USE_LIBPSL #include "psl.h" #include "share.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" void Curl_psl_destroy(struct PslCache *pslcache) { if(pslcache->psl) { if(pslcache->dynamic) psl_free((psl_ctx_t *) pslcache->psl); pslcache->psl = NULL; pslcache->dynamic = FALSE; } } static time_t now_seconds(void) { struct curltime now = Curl_now(); return now.tv_sec; } const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy) { struct PslCache *pslcache = easy->psl; const psl_ctx_t *psl; time_t now; if(!pslcache) return NULL; Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED); now = now_seconds(); if(!pslcache->psl || pslcache->expires <= now) { /* Let a chance to other threads to do the job: avoids deadlock. */ Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); /* Update cache: this needs an exclusive lock. */ Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SINGLE); /* Recheck in case another thread did the job. */ now = now_seconds(); if(!pslcache->psl || pslcache->expires <= now) { bool dynamic = FALSE; time_t expires = TIME_T_MAX; #if defined(PSL_VERSION_NUMBER) && PSL_VERSION_NUMBER >= 0x001000 psl = psl_latest(NULL); dynamic = psl != NULL; /* Take care of possible time computation overflow. */ expires = now < TIME_T_MAX - PSL_TTL? now + PSL_TTL: TIME_T_MAX; /* Only get the built-in PSL if we do not already have the "latest". */ if(!psl && !pslcache->dynamic) #endif psl = psl_builtin(); if(psl) { Curl_psl_destroy(pslcache); pslcache->psl = psl; pslcache->dynamic = dynamic; pslcache->expires = expires; } } Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); /* Release exclusive lock. */ Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED); } psl = pslcache->psl; if(!psl) Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); return psl; } void Curl_psl_release(struct Curl_easy *easy) { Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); } #endif /* USE_LIBPSL */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/url.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_IPHLPAPI_H #include <Iphlpapi.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_SYS_UN_H #include <sys/un.h> #endif #ifndef HAVE_SOCKET #error "We can't compile without socket() support!" #endif #include <limits.h> #ifdef USE_LIBIDN2 #include <idn2.h> #if defined(WIN32) && defined(UNICODE) #define IDN2_LOOKUP(name, host, flags) \ idn2_lookup_u8((const uint8_t *)name, (uint8_t **)host, flags) #else #define IDN2_LOOKUP(name, host, flags) \ idn2_lookup_ul((const char *)name, (char **)host, flags) #endif #elif defined(USE_WIN32_IDN) /* prototype for curl_win32_idn_to_ascii() */ bool curl_win32_idn_to_ascii(const char *in, char **out); #endif /* USE_LIBIDN2 */ #include "urldata.h" #include "netrc.h" #include "formdata.h" #include "mime.h" #include "vtls/vtls.h" #include "hostip.h" #include "transfer.h" #include "sendf.h" #include "progress.h" #include "cookie.h" #include "strcase.h" #include "strerror.h" #include "escape.h" #include "strtok.h" #include "share.h" #include "content_encoding.h" #include "http_digest.h" #include "http_negotiate.h" #include "select.h" #include "multiif.h" #include "easyif.h" #include "speedcheck.h" #include "warnless.h" #include "non-ascii.h" #include "getinfo.h" #include "urlapi-int.h" #include "system_win32.h" #include "hsts.h" /* And now for the protocols */ #include "ftp.h" #include "dict.h" #include "telnet.h" #include "tftp.h" #include "http.h" #include "http2.h" #include "file.h" #include "curl_ldap.h" #include "vssh/ssh.h" #include "imap.h" #include "url.h" #include "connect.h" #include "inet_ntop.h" #include "http_ntlm.h" #include "curl_rtmp.h" #include "gopher.h" #include "mqtt.h" #include "http_proxy.h" #include "conncache.h" #include "multihandle.h" #include "dotdot.h" #include "strdup.h" #include "setopt.h" #include "altsvc.h" #include "dynbuf.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" static void conn_free(struct connectdata *conn); /* Some parts of the code (e.g. chunked encoding) assume this buffer has at * more than just a few bytes to play with. Don't let it become too small or * bad things will happen. */ #if READBUFFER_SIZE < READBUFFER_MIN # error READBUFFER_SIZE is too small #endif /* * get_protocol_family() * * This is used to return the protocol family for a given protocol. * * Parameters: * * 'h' [in] - struct Curl_handler pointer. * * Returns the family as a single bit protocol identifier. */ static unsigned int get_protocol_family(const struct Curl_handler *h) { DEBUGASSERT(h); DEBUGASSERT(h->family); return h->family; } /* * Protocol table. Schemes (roughly) in 2019 popularity order: * * HTTPS, HTTP, FTP, FTPS, SFTP, FILE, SCP, SMTP, LDAP, IMAPS, TELNET, IMAP, * LDAPS, SMTPS, TFTP, SMB, POP3, GOPHER POP3S, RTSP, RTMP, SMBS, DICT */ static const struct Curl_handler * const protocols[] = { #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP) &Curl_handler_https, #endif #ifndef CURL_DISABLE_HTTP &Curl_handler_http, #endif #ifndef CURL_DISABLE_FTP &Curl_handler_ftp, #endif #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP) &Curl_handler_ftps, #endif #if defined(USE_SSH) &Curl_handler_sftp, #endif #ifndef CURL_DISABLE_FILE &Curl_handler_file, #endif #if defined(USE_SSH) && !defined(USE_WOLFSSH) &Curl_handler_scp, #endif #ifndef CURL_DISABLE_SMTP &Curl_handler_smtp, #ifdef USE_SSL &Curl_handler_smtps, #endif #endif #ifndef CURL_DISABLE_LDAP &Curl_handler_ldap, #if !defined(CURL_DISABLE_LDAPS) && \ ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \ (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL))) &Curl_handler_ldaps, #endif #endif #ifndef CURL_DISABLE_IMAP &Curl_handler_imap, #ifdef USE_SSL &Curl_handler_imaps, #endif #endif #ifndef CURL_DISABLE_TELNET &Curl_handler_telnet, #endif #ifndef CURL_DISABLE_TFTP &Curl_handler_tftp, #endif #ifndef CURL_DISABLE_POP3 &Curl_handler_pop3, #ifdef USE_SSL &Curl_handler_pop3s, #endif #endif #if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) && \ (SIZEOF_CURL_OFF_T > 4) &Curl_handler_smb, #ifdef USE_SSL &Curl_handler_smbs, #endif #endif #ifndef CURL_DISABLE_RTSP &Curl_handler_rtsp, #endif #ifndef CURL_DISABLE_MQTT &Curl_handler_mqtt, #endif #ifndef CURL_DISABLE_GOPHER &Curl_handler_gopher, #ifdef USE_SSL &Curl_handler_gophers, #endif #endif #ifdef USE_LIBRTMP &Curl_handler_rtmp, &Curl_handler_rtmpt, &Curl_handler_rtmpe, &Curl_handler_rtmpte, &Curl_handler_rtmps, &Curl_handler_rtmpts, #endif #ifndef CURL_DISABLE_DICT &Curl_handler_dict, #endif (struct Curl_handler *) NULL }; /* * Dummy handler for undefined protocol schemes. */ static const struct Curl_handler Curl_handler_dummy = { "<no protocol>", /* scheme */ ZERO_NULL, /* setup_connection */ ZERO_NULL, /* do_it */ ZERO_NULL, /* done */ ZERO_NULL, /* do_more */ ZERO_NULL, /* connect_it */ ZERO_NULL, /* connecting */ ZERO_NULL, /* doing */ ZERO_NULL, /* proto_getsock */ ZERO_NULL, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ ZERO_NULL, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ ZERO_NULL, /* attach connection */ 0, /* defport */ 0, /* protocol */ 0, /* family */ PROTOPT_NONE /* flags */ }; void Curl_freeset(struct Curl_easy *data) { /* Free all dynamic strings stored in the data->set substructure. */ enum dupstring i; enum dupblob j; for(i = (enum dupstring)0; i < STRING_LAST; i++) { Curl_safefree(data->set.str[i]); } for(j = (enum dupblob)0; j < BLOB_LAST; j++) { Curl_safefree(data->set.blobs[j]); } if(data->state.referer_alloc) { Curl_safefree(data->state.referer); data->state.referer_alloc = FALSE; } data->state.referer = NULL; if(data->state.url_alloc) { Curl_safefree(data->state.url); data->state.url_alloc = FALSE; } data->state.url = NULL; Curl_mime_cleanpart(&data->set.mimepost); } /* free the URL pieces */ static void up_free(struct Curl_easy *data) { struct urlpieces *up = &data->state.up; Curl_safefree(up->scheme); Curl_safefree(up->hostname); Curl_safefree(up->port); Curl_safefree(up->user); Curl_safefree(up->password); Curl_safefree(up->options); Curl_safefree(up->path); Curl_safefree(up->query); curl_url_cleanup(data->state.uh); data->state.uh = NULL; } /* * This is the internal function curl_easy_cleanup() calls. This should * cleanup and free all resources associated with this sessionhandle. * * NOTE: if we ever add something that attempts to write to a socket or * similar here, we must ignore SIGPIPE first. It is currently only done * when curl_easy_perform() is invoked. */ CURLcode Curl_close(struct Curl_easy **datap) { struct Curl_multi *m; struct Curl_easy *data; if(!datap || !*datap) return CURLE_OK; data = *datap; *datap = NULL; Curl_expire_clear(data); /* shut off timers */ /* Detach connection if any is left. This should not be normal, but can be the case for example with CONNECT_ONLY + recv/send (test 556) */ Curl_detach_connnection(data); m = data->multi; if(m) /* This handle is still part of a multi handle, take care of this first and detach this handle from there. */ curl_multi_remove_handle(data->multi, data); if(data->multi_easy) { /* when curl_easy_perform() is used, it creates its own multi handle to use and this is the one */ curl_multi_cleanup(data->multi_easy); data->multi_easy = NULL; } /* Destroy the timeout list that is held in the easy handle. It is /normally/ done by curl_multi_remove_handle() but this is "just in case" */ Curl_llist_destroy(&data->state.timeoutlist, NULL); data->magic = 0; /* force a clear AFTER the possibly enforced removal from the multi handle, since that function uses the magic field! */ if(data->state.rangestringalloc) free(data->state.range); /* freed here just in case DONE wasn't called */ Curl_free_request_state(data); /* Close down all open SSL info and sessions */ Curl_ssl_close_all(data); Curl_safefree(data->state.first_host); Curl_safefree(data->state.scratch); Curl_ssl_free_certinfo(data); /* Cleanup possible redirect junk */ free(data->req.newurl); data->req.newurl = NULL; if(data->state.referer_alloc) { Curl_safefree(data->state.referer); data->state.referer_alloc = FALSE; } data->state.referer = NULL; up_free(data); Curl_safefree(data->state.buffer); Curl_dyn_free(&data->state.headerb); Curl_safefree(data->state.ulbuf); Curl_flush_cookies(data, TRUE); Curl_altsvc_save(data, data->asi, data->set.str[STRING_ALTSVC]); Curl_altsvc_cleanup(&data->asi); Curl_hsts_save(data, data->hsts, data->set.str[STRING_HSTS]); Curl_hsts_cleanup(&data->hsts); #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) Curl_http_auth_cleanup_digest(data); #endif Curl_safefree(data->info.contenttype); Curl_safefree(data->info.wouldredirect); /* this destroys the channel and we cannot use it anymore after this */ Curl_resolver_cleanup(data->state.async.resolver); Curl_http2_cleanup_dependencies(data); Curl_convert_close(data); /* No longer a dirty share, if it exists */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } Curl_safefree(data->state.aptr.proxyuserpwd); Curl_safefree(data->state.aptr.uagent); Curl_safefree(data->state.aptr.userpwd); Curl_safefree(data->state.aptr.accept_encoding); Curl_safefree(data->state.aptr.te); Curl_safefree(data->state.aptr.rangeline); Curl_safefree(data->state.aptr.ref); Curl_safefree(data->state.aptr.host); Curl_safefree(data->state.aptr.cookiehost); Curl_safefree(data->state.aptr.rtsp_transport); Curl_safefree(data->state.aptr.user); Curl_safefree(data->state.aptr.passwd); Curl_safefree(data->state.aptr.proxyuser); Curl_safefree(data->state.aptr.proxypasswd); #ifndef CURL_DISABLE_DOH if(data->req.doh) { Curl_dyn_free(&data->req.doh->probe[0].serverdoh); Curl_dyn_free(&data->req.doh->probe[1].serverdoh); curl_slist_free_all(data->req.doh->headers); Curl_safefree(data->req.doh); } #endif /* destruct wildcard structures if it is needed */ Curl_wildcard_dtor(&data->wildcard); Curl_freeset(data); free(data); return CURLE_OK; } /* * Initialize the UserDefined fields within a Curl_easy. * This may be safely called on a new or existing Curl_easy. */ CURLcode Curl_init_userdefined(struct Curl_easy *data) { struct UserDefined *set = &data->set; CURLcode result = CURLE_OK; set->out = stdout; /* default output to stdout */ set->in_set = stdin; /* default input from stdin */ set->err = stderr; /* default stderr to stderr */ /* use fwrite as default function to store output */ set->fwrite_func = (curl_write_callback)fwrite; /* use fread as default function to read input */ set->fread_func_set = (curl_read_callback)fread; set->is_fread_set = 0; set->is_fwrite_set = 0; set->seek_func = ZERO_NULL; set->seek_client = ZERO_NULL; /* conversion callbacks for non-ASCII hosts */ set->convfromnetwork = ZERO_NULL; set->convtonetwork = ZERO_NULL; set->convfromutf8 = ZERO_NULL; set->filesize = -1; /* we don't know the size */ set->postfieldsize = -1; /* unknown size */ set->maxredirs = -1; /* allow any amount by default */ set->method = HTTPREQ_GET; /* Default HTTP request */ set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */ #ifndef CURL_DISABLE_FTP set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */ set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */ set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */ set->ftp_filemethod = FTPFILE_MULTICWD; set->ftp_skip_ip = TRUE; /* skip PASV IP by default */ #endif set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */ /* Set the default size of the SSL session ID cache */ set->general_ssl.max_ssl_sessions = 5; set->proxyport = 0; set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */ set->httpauth = CURLAUTH_BASIC; /* defaults to basic */ set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */ /* SOCKS5 proxy auth defaults to username/password + GSS-API */ set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI; /* make libcurl quiet by default: */ set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */ Curl_mime_initpart(&set->mimepost, data); /* * libcurl 7.10 introduced SSL verification *by default*! This needs to be * switched off unless wanted. */ set->doh_verifyhost = TRUE; set->doh_verifypeer = TRUE; set->ssl.primary.verifypeer = TRUE; set->ssl.primary.verifyhost = TRUE; #ifdef USE_TLS_SRP set->ssl.authtype = CURL_TLSAUTH_NONE; #endif set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth type */ set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by default */ #ifndef CURL_DISABLE_PROXY set->proxy_ssl = set->ssl; #endif set->new_file_perms = 0644; /* Default permissions */ set->new_directory_perms = 0755; /* Default permissions */ /* for the *protocols fields we don't use the CURLPROTO_ALL convenience define since we internally only use the lower 16 bits for the passed in bitmask to not conflict with the private bits */ set->allowed_protocols = CURLPROTO_ALL; set->redir_protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | CURLPROTO_FTPS; #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) /* * disallow unprotected protection negotiation NEC reference implementation * seem not to follow rfc1961 section 4.3/4.4 */ set->socks5_gssapi_nec = FALSE; #endif /* Set the default CA cert bundle/path detected/specified at build time. * * If Schannel is the selected SSL backend then these locations are * ignored. We allow setting CA location for schannel only when explicitly * specified by the user via CURLOPT_CAINFO / --cacert. */ if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) { #if defined(CURL_CA_BUNDLE) result = Curl_setstropt(&set->str[STRING_SSL_CAFILE], CURL_CA_BUNDLE); if(result) return result; result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY], CURL_CA_BUNDLE); if(result) return result; #endif #if defined(CURL_CA_PATH) result = Curl_setstropt(&set->str[STRING_SSL_CAPATH], CURL_CA_PATH); if(result) return result; result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH); if(result) return result; #endif } set->wildcard_enabled = FALSE; set->chunk_bgn = ZERO_NULL; set->chunk_end = ZERO_NULL; set->tcp_keepalive = FALSE; set->tcp_keepintvl = 60; set->tcp_keepidle = 60; set->tcp_fastopen = FALSE; set->tcp_nodelay = TRUE; set->ssl_enable_npn = TRUE; set->ssl_enable_alpn = TRUE; set->expect_100_timeout = 1000L; /* Wait for a second by default. */ set->sep_headers = TRUE; /* separated header lists by default */ set->buffer_size = READBUFFER_SIZE; set->upload_buffer_size = UPLOADBUFFER_DEFAULT; set->happy_eyeballs_timeout = CURL_HET_DEFAULT; set->fnmatch = ZERO_NULL; set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT; set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */ set->maxage_conn = 118; set->maxlifetime_conn = 0; set->http09_allowed = FALSE; set->httpwant = #ifdef USE_NGHTTP2 CURL_HTTP_VERSION_2TLS #else CURL_HTTP_VERSION_1_1 #endif ; Curl_http2_init_userset(set); return result; } /** * Curl_open() * * @param curl is a pointer to a sessionhandle pointer that gets set by this * function. * @return CURLcode */ CURLcode Curl_open(struct Curl_easy **curl) { CURLcode result; struct Curl_easy *data; /* Very simple start-up: alloc the struct, init it with zeroes and return */ data = calloc(1, sizeof(struct Curl_easy)); if(!data) { /* this is a very serious error */ DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n")); return CURLE_OUT_OF_MEMORY; } data->magic = CURLEASY_MAGIC_NUMBER; result = Curl_resolver_init(data, &data->state.async.resolver); if(result) { DEBUGF(fprintf(stderr, "Error: resolver_init failed\n")); free(data); return result; } result = Curl_init_userdefined(data); if(!result) { Curl_dyn_init(&data->state.headerb, CURL_MAX_HTTP_HEADER); Curl_convert_init(data); Curl_initinfo(data); /* most recent connection is not yet defined */ data->state.lastconnect_id = -1; data->progress.flags |= PGRS_HIDE; data->state.current_speed = -1; /* init to negative == impossible */ } if(result) { Curl_resolver_cleanup(data->state.async.resolver); Curl_dyn_free(&data->state.headerb); Curl_freeset(data); free(data); data = NULL; } else *curl = data; return result; } #ifdef USE_RECV_BEFORE_SEND_WORKAROUND static void conn_reset_postponed_data(struct connectdata *conn, int num) { struct postponed_data * const psnd = &(conn->postponed[num]); if(psnd->buffer) { DEBUGASSERT(psnd->allocated_size > 0); DEBUGASSERT(psnd->recv_size <= psnd->allocated_size); DEBUGASSERT(psnd->recv_size ? (psnd->recv_processed < psnd->recv_size) : (psnd->recv_processed == 0)); DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD); free(psnd->buffer); psnd->buffer = NULL; psnd->allocated_size = 0; psnd->recv_size = 0; psnd->recv_processed = 0; #ifdef DEBUGBUILD psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */ #endif /* DEBUGBUILD */ } else { DEBUGASSERT(psnd->allocated_size == 0); DEBUGASSERT(psnd->recv_size == 0); DEBUGASSERT(psnd->recv_processed == 0); DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD); } } static void conn_reset_all_postponed_data(struct connectdata *conn) { conn_reset_postponed_data(conn, 0); conn_reset_postponed_data(conn, 1); } #else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ /* Use "do-nothing" macro instead of function when workaround not used */ #define conn_reset_all_postponed_data(c) do {} while(0) #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */ static void conn_shutdown(struct Curl_easy *data, struct connectdata *conn) { DEBUGASSERT(conn); DEBUGASSERT(data); infof(data, "Closing connection %ld", conn->connection_id); #ifndef USE_HYPER if(conn->connect_state && conn->connect_state->prot_save) { /* If this was closed with a CONNECT in progress, cleanup this temporary struct arrangement */ data->req.p.http = NULL; Curl_safefree(conn->connect_state->prot_save); } #endif /* possible left-overs from the async name resolvers */ Curl_resolver_cancel(data); /* close the SSL stuff before we close any sockets since they will/may write to the sockets */ Curl_ssl_close(data, conn, FIRSTSOCKET); Curl_ssl_close(data, conn, SECONDARYSOCKET); /* close possibly still open sockets */ if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) Curl_closesocket(data, conn, conn->sock[SECONDARYSOCKET]); if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET]) Curl_closesocket(data, conn, conn->sock[FIRSTSOCKET]); if(CURL_SOCKET_BAD != conn->tempsock[0]) Curl_closesocket(data, conn, conn->tempsock[0]); if(CURL_SOCKET_BAD != conn->tempsock[1]) Curl_closesocket(data, conn, conn->tempsock[1]); } static void conn_free(struct connectdata *conn) { DEBUGASSERT(conn); Curl_free_idnconverted_hostname(&conn->host); Curl_free_idnconverted_hostname(&conn->conn_to_host); #ifndef CURL_DISABLE_PROXY Curl_free_idnconverted_hostname(&conn->http_proxy.host); Curl_free_idnconverted_hostname(&conn->socks_proxy.host); Curl_safefree(conn->http_proxy.user); Curl_safefree(conn->socks_proxy.user); Curl_safefree(conn->http_proxy.passwd); Curl_safefree(conn->socks_proxy.passwd); Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */ Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */ Curl_free_primary_ssl_config(&conn->proxy_ssl_config); #endif Curl_safefree(conn->user); Curl_safefree(conn->passwd); Curl_safefree(conn->sasl_authzid); Curl_safefree(conn->options); Curl_dyn_free(&conn->trailer); Curl_safefree(conn->host.rawalloc); /* host name buffer */ Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */ Curl_safefree(conn->hostname_resolve); Curl_safefree(conn->secondaryhostname); Curl_safefree(conn->connect_state); conn_reset_all_postponed_data(conn); Curl_llist_destroy(&conn->easyq, NULL); Curl_safefree(conn->localdev); Curl_free_primary_ssl_config(&conn->ssl_config); #ifdef USE_UNIX_SOCKETS Curl_safefree(conn->unix_domain_socket); #endif #ifdef USE_SSL Curl_safefree(conn->ssl_extra); #endif free(conn); /* free all the connection oriented data */ } /* * Disconnects the given connection. Note the connection may not be the * primary connection, like when freeing room in the connection cache or * killing of a dead old connection. * * A connection needs an easy handle when closing down. We support this passed * in separately since the connection to get closed here is often already * disassociated from an easy handle. * * This function MUST NOT reset state in the Curl_easy struct if that * isn't strictly bound to the life-time of *this* particular connection. * */ CURLcode Curl_disconnect(struct Curl_easy *data, struct connectdata *conn, bool dead_connection) { /* there must be a connection to close */ DEBUGASSERT(conn); /* it must be removed from the connection cache */ DEBUGASSERT(!conn->bundle); /* there must be an associated transfer */ DEBUGASSERT(data); /* the transfer must be detached from the connection */ DEBUGASSERT(!data->conn); /* * If this connection isn't marked to force-close, leave it open if there * are other users of it */ if(CONN_INUSE(conn) && !dead_connection) { DEBUGF(infof(data, "Curl_disconnect when inuse: %zu", CONN_INUSE(conn))); return CURLE_OK; } if(conn->dns_entry != NULL) { Curl_resolv_unlock(data, conn->dns_entry); conn->dns_entry = NULL; } /* Cleanup NTLM connection-related data */ Curl_http_auth_cleanup_ntlm(conn); /* Cleanup NEGOTIATE connection-related data */ Curl_http_auth_cleanup_negotiate(conn); if(conn->bits.connect_only) /* treat the connection as dead in CONNECT_ONLY situations */ dead_connection = TRUE; /* temporarily attach the connection to this transfer handle for the disconnect and shutdown */ Curl_attach_connnection(data, conn); if(conn->handler->disconnect) /* This is set if protocol-specific cleanups should be made */ conn->handler->disconnect(data, conn, dead_connection); conn_shutdown(data, conn); /* detach it again */ Curl_detach_connnection(data); conn_free(conn); return CURLE_OK; } /* * This function should return TRUE if the socket is to be assumed to * be dead. Most commonly this happens when the server has closed the * connection due to inactivity. */ static bool SocketIsDead(curl_socket_t sock) { int sval; bool ret_val = TRUE; sval = SOCKET_READABLE(sock, 0); if(sval == 0) /* timeout */ ret_val = FALSE; return ret_val; } /* * IsMultiplexingPossible() * * Return a bitmask with the available multiplexing options for the given * requested connection. */ static int IsMultiplexingPossible(const struct Curl_easy *handle, const struct connectdata *conn) { int avail = 0; /* If a HTTP protocol and multiplexing is enabled */ if((conn->handler->protocol & PROTO_FAMILY_HTTP) && (!conn->bits.protoconnstart || !conn->bits.close)) { if(Curl_multiplex_wanted(handle->multi) && (handle->state.httpwant >= CURL_HTTP_VERSION_2)) /* allows HTTP/2 */ avail |= CURLPIPE_MULTIPLEX; } return avail; } #ifndef CURL_DISABLE_PROXY static bool proxy_info_matches(const struct proxy_info *data, const struct proxy_info *needle) { if((data->proxytype == needle->proxytype) && (data->port == needle->port) && Curl_safe_strcasecompare(data->host.name, needle->host.name)) return TRUE; return FALSE; } static bool socks_proxy_info_matches(const struct proxy_info *data, const struct proxy_info *needle) { if(!proxy_info_matches(data, needle)) return FALSE; /* the user information is case-sensitive or at least it is not defined as case-insensitive see https://tools.ietf.org/html/rfc3986#section-3.2.1 */ if(!data->user != !needle->user) return FALSE; /* curl_strequal does a case insentive comparison, so do not use it here! */ if(data->user && needle->user && strcmp(data->user, needle->user) != 0) return FALSE; if(!data->passwd != !needle->passwd) return FALSE; /* curl_strequal does a case insentive comparison, so do not use it here! */ if(data->passwd && needle->passwd && strcmp(data->passwd, needle->passwd) != 0) return FALSE; return TRUE; } #else /* disabled, won't get called */ #define proxy_info_matches(x,y) FALSE #define socks_proxy_info_matches(x,y) FALSE #endif /* A connection has to have been idle for a shorter time than 'maxage_conn' (the success rate is just too low after this), or created less than 'maxlifetime_conn' ago, to be subject for reuse. */ static bool conn_maxage(struct Curl_easy *data, struct connectdata *conn, struct curltime now) { timediff_t idletime, lifetime; idletime = Curl_timediff(now, conn->lastused); idletime /= 1000; /* integer seconds is fine */ if(idletime > data->set.maxage_conn) { infof(data, "Too old connection (%ld seconds idle), disconnect it", idletime); return TRUE; } lifetime = Curl_timediff(now, conn->created); lifetime /= 1000; /* integer seconds is fine */ if(data->set.maxlifetime_conn && lifetime > data->set.maxlifetime_conn) { infof(data, "Too old connection (%ld seconds since creation), disconnect it", lifetime); return TRUE; } return FALSE; } /* * This function checks if the given connection is dead and extracts it from * the connection cache if so. * * When this is called as a Curl_conncache_foreach() callback, the connection * cache lock is held! * * Returns TRUE if the connection was dead and extracted. */ static bool extract_if_dead(struct connectdata *conn, struct Curl_easy *data) { if(!CONN_INUSE(conn)) { /* The check for a dead socket makes sense only if the connection isn't in use */ bool dead; struct curltime now = Curl_now(); if(conn_maxage(data, conn, now)) { /* avoid check if already too old */ dead = TRUE; } else if(conn->handler->connection_check) { /* The protocol has a special method for checking the state of the connection. Use it to check if the connection is dead. */ unsigned int state; /* briefly attach the connection to this transfer for the purpose of checking it */ Curl_attach_connnection(data, conn); state = conn->handler->connection_check(data, conn, CONNCHECK_ISDEAD); dead = (state & CONNRESULT_DEAD); /* detach the connection again */ Curl_detach_connnection(data); } else { /* Use the general method for determining the death of a connection */ dead = SocketIsDead(conn->sock[FIRSTSOCKET]); } if(dead) { infof(data, "Connection %ld seems to be dead!", conn->connection_id); Curl_conncache_remove_conn(data, conn, FALSE); return TRUE; } } return FALSE; } struct prunedead { struct Curl_easy *data; struct connectdata *extracted; }; /* * Wrapper to use extract_if_dead() function in Curl_conncache_foreach() * */ static int call_extract_if_dead(struct Curl_easy *data, struct connectdata *conn, void *param) { struct prunedead *p = (struct prunedead *)param; if(extract_if_dead(conn, data)) { /* stop the iteration here, pass back the connection that was extracted */ p->extracted = conn; return 1; } return 0; /* continue iteration */ } /* * This function scans the connection cache for half-open/dead connections, * closes and removes them. The cleanup is done at most once per second. * * When called, this transfer has no connection attached. */ static void prune_dead_connections(struct Curl_easy *data) { struct curltime now = Curl_now(); timediff_t elapsed; DEBUGASSERT(!data->conn); /* no connection */ CONNCACHE_LOCK(data); elapsed = Curl_timediff(now, data->state.conn_cache->last_cleanup); CONNCACHE_UNLOCK(data); if(elapsed >= 1000L) { struct prunedead prune; prune.data = data; prune.extracted = NULL; while(Curl_conncache_foreach(data, data->state.conn_cache, &prune, call_extract_if_dead)) { /* unlocked */ /* remove connection from cache */ Curl_conncache_remove_conn(data, prune.extracted, TRUE); /* disconnect it */ (void)Curl_disconnect(data, prune.extracted, TRUE); } CONNCACHE_LOCK(data); data->state.conn_cache->last_cleanup = now; CONNCACHE_UNLOCK(data); } } /* * Given one filled in connection struct (named needle), this function should * detect if there already is one that has all the significant details * exactly the same and thus should be used instead. * * If there is a match, this function returns TRUE - and has marked the * connection as 'in-use'. It must later be called with ConnectionDone() to * return back to 'idle' (unused) state. * * The force_reuse flag is set if the connection must be used. */ static bool ConnectionExists(struct Curl_easy *data, struct connectdata *needle, struct connectdata **usethis, bool *force_reuse, bool *waitpipe) { struct connectdata *check; struct connectdata *chosen = 0; bool foundPendingCandidate = FALSE; bool canmultiplex = IsMultiplexingPossible(data, needle); struct connectbundle *bundle; const char *hostbundle; #ifdef USE_NTLM bool wantNTLMhttp = ((data->state.authhost.want & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && (needle->handler->protocol & PROTO_FAMILY_HTTP)); #ifndef CURL_DISABLE_PROXY bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd && ((data->state.authproxy.want & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && (needle->handler->protocol & PROTO_FAMILY_HTTP))); #else bool wantProxyNTLMhttp = FALSE; #endif #endif *force_reuse = FALSE; *waitpipe = FALSE; /* Look up the bundle with all the connections to this particular host. Locks the connection cache, beware of early returns! */ bundle = Curl_conncache_find_bundle(data, needle, data->state.conn_cache, &hostbundle); if(bundle) { /* Max pipe length is zero (unlimited) for multiplexed connections */ struct Curl_llist_element *curr; infof(data, "Found bundle for host %s: %p [%s]", hostbundle, (void *)bundle, (bundle->multiuse == BUNDLE_MULTIPLEX ? "can multiplex" : "serially")); /* We can't multiplex if we don't know anything about the server */ if(canmultiplex) { if(bundle->multiuse == BUNDLE_UNKNOWN) { if(data->set.pipewait) { infof(data, "Server doesn't support multiplex yet, wait"); *waitpipe = TRUE; CONNCACHE_UNLOCK(data); return FALSE; /* no re-use */ } infof(data, "Server doesn't support multiplex (yet)"); canmultiplex = FALSE; } if((bundle->multiuse == BUNDLE_MULTIPLEX) && !Curl_multiplex_wanted(data->multi)) { infof(data, "Could multiplex, but not asked to!"); canmultiplex = FALSE; } if(bundle->multiuse == BUNDLE_NO_MULTIUSE) { infof(data, "Can not multiplex, even if we wanted to!"); canmultiplex = FALSE; } } curr = bundle->conn_list.head; while(curr) { bool match = FALSE; size_t multiplexed = 0; /* * Note that if we use a HTTP proxy in normal mode (no tunneling), we * check connections to that proxy and not to the actual remote server. */ check = curr->ptr; curr = curr->next; if(check->bits.connect_only || check->bits.close) /* connect-only or to-be-closed connections will not be reused */ continue; if(extract_if_dead(check, data)) { /* disconnect it */ (void)Curl_disconnect(data, check, TRUE); continue; } if(data->set.ipver != CURL_IPRESOLVE_WHATEVER && data->set.ipver != check->ip_version) { /* skip because the connection is not via the requested IP version */ continue; } if(bundle->multiuse == BUNDLE_MULTIPLEX) multiplexed = CONN_INUSE(check); if(!canmultiplex) { if(multiplexed) { /* can only happen within multi handles, and means that another easy handle is using this connection */ continue; } if(Curl_resolver_asynch()) { /* primary_ip[0] is NUL only if the resolving of the name hasn't completed yet and until then we don't re-use this connection */ if(!check->primary_ip[0]) { infof(data, "Connection #%ld is still name resolving, can't reuse", check->connection_id); continue; } } if(check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) { foundPendingCandidate = TRUE; /* Don't pick a connection that hasn't connected yet */ infof(data, "Connection #%ld isn't open enough, can't reuse", check->connection_id); continue; } } #ifdef USE_UNIX_SOCKETS if(needle->unix_domain_socket) { if(!check->unix_domain_socket) continue; if(strcmp(needle->unix_domain_socket, check->unix_domain_socket)) continue; if(needle->bits.abstract_unix_socket != check->bits.abstract_unix_socket) continue; } else if(check->unix_domain_socket) continue; #endif if((needle->handler->flags&PROTOPT_SSL) != (check->handler->flags&PROTOPT_SSL)) /* don't do mixed SSL and non-SSL connections */ if(get_protocol_family(check->handler) != needle->handler->protocol || !check->bits.tls_upgraded) /* except protocols that have been upgraded via TLS */ continue; #ifndef CURL_DISABLE_PROXY if(needle->bits.httpproxy != check->bits.httpproxy || needle->bits.socksproxy != check->bits.socksproxy) continue; if(needle->bits.socksproxy && !socks_proxy_info_matches(&needle->socks_proxy, &check->socks_proxy)) continue; #endif if(needle->bits.conn_to_host != check->bits.conn_to_host) /* don't mix connections that use the "connect to host" feature and * connections that don't use this feature */ continue; if(needle->bits.conn_to_port != check->bits.conn_to_port) /* don't mix connections that use the "connect to port" feature and * connections that don't use this feature */ continue; #ifndef CURL_DISABLE_PROXY if(needle->bits.httpproxy) { if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy)) continue; if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy) continue; if(needle->http_proxy.proxytype == CURLPROXY_HTTPS) { /* use https proxy */ if(needle->handler->flags&PROTOPT_SSL) { /* use double layer ssl */ if(!Curl_ssl_config_matches(&needle->proxy_ssl_config, &check->proxy_ssl_config)) continue; if(check->proxy_ssl[FIRSTSOCKET].state != ssl_connection_complete) continue; } else { if(!Curl_ssl_config_matches(&needle->ssl_config, &check->ssl_config)) continue; if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) continue; } } } #endif if(!canmultiplex && CONN_INUSE(check)) /* this request can't be multiplexed but the checked connection is already in use so we skip it */ continue; if(CONN_INUSE(check)) { /* Subject for multiplex use if 'checks' belongs to the same multi handle as 'data' is. */ struct Curl_llist_element *e = check->easyq.head; struct Curl_easy *entry = e->ptr; if(entry->multi != data->multi) continue; } if(needle->localdev || needle->localport) { /* If we are bound to a specific local end (IP+port), we must not re-use a random other one, although if we didn't ask for a particular one we can reuse one that was bound. This comparison is a bit rough and too strict. Since the input parameters can be specified in numerous ways and still end up the same it would take a lot of processing to make it really accurate. Instead, this matching will assume that re-uses of bound connections will most likely also re-use the exact same binding parameters and missing out a few edge cases shouldn't hurt anyone very much. */ if((check->localport != needle->localport) || (check->localportrange != needle->localportrange) || (needle->localdev && (!check->localdev || strcmp(check->localdev, needle->localdev)))) continue; } if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) { /* This protocol requires credentials per connection, so verify that we're using the same name and password as well */ if(strcmp(needle->user, check->user) || strcmp(needle->passwd, check->passwd)) { /* one of them was different */ continue; } } /* If multiplexing isn't enabled on the h2 connection and h1 is explicitly requested, handle it: */ if((needle->handler->protocol & PROTO_FAMILY_HTTP) && (check->httpversion >= 20) && (data->state.httpwant < CURL_HTTP_VERSION_2_0)) continue; if((needle->handler->flags&PROTOPT_SSL) #ifndef CURL_DISABLE_PROXY || !needle->bits.httpproxy || needle->bits.tunnel_proxy #endif ) { /* The requested connection does not use a HTTP proxy or it uses SSL or it is a non-SSL protocol tunneled or it is a non-SSL protocol which is allowed to be upgraded via TLS */ if((strcasecompare(needle->handler->scheme, check->handler->scheme) || (get_protocol_family(check->handler) == needle->handler->protocol && check->bits.tls_upgraded)) && (!needle->bits.conn_to_host || strcasecompare( needle->conn_to_host.name, check->conn_to_host.name)) && (!needle->bits.conn_to_port || needle->conn_to_port == check->conn_to_port) && strcasecompare(needle->host.name, check->host.name) && needle->remote_port == check->remote_port) { /* The schemes match or the protocol family is the same and the previous connection was TLS upgraded, and the hostname and host port match */ if(needle->handler->flags & PROTOPT_SSL) { /* This is a SSL connection so verify that we're using the same SSL options as well */ if(!Curl_ssl_config_matches(&needle->ssl_config, &check->ssl_config)) { DEBUGF(infof(data, "Connection #%ld has different SSL parameters, " "can't reuse", check->connection_id)); continue; } if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) { foundPendingCandidate = TRUE; DEBUGF(infof(data, "Connection #%ld has not started SSL connect, " "can't reuse", check->connection_id)); continue; } } match = TRUE; } } else { /* The requested connection is using the same HTTP proxy in normal mode (no tunneling) */ match = TRUE; } if(match) { #if defined(USE_NTLM) /* If we are looking for an HTTP+NTLM connection, check if this is already authenticating with the right credentials. If not, keep looking so that we can reuse NTLM connections if possible. (Especially we must not reuse the same connection if partway through a handshake!) */ if(wantNTLMhttp) { if(strcmp(needle->user, check->user) || strcmp(needle->passwd, check->passwd)) { /* we prefer a credential match, but this is at least a connection that can be reused and "upgraded" to NTLM */ if(check->http_ntlm_state == NTLMSTATE_NONE) chosen = check; continue; } } else if(check->http_ntlm_state != NTLMSTATE_NONE) { /* Connection is using NTLM auth but we don't want NTLM */ continue; } #ifndef CURL_DISABLE_PROXY /* Same for Proxy NTLM authentication */ if(wantProxyNTLMhttp) { /* Both check->http_proxy.user and check->http_proxy.passwd can be * NULL */ if(!check->http_proxy.user || !check->http_proxy.passwd) continue; if(strcmp(needle->http_proxy.user, check->http_proxy.user) || strcmp(needle->http_proxy.passwd, check->http_proxy.passwd)) continue; } else if(check->proxy_ntlm_state != NTLMSTATE_NONE) { /* Proxy connection is using NTLM auth but we don't want NTLM */ continue; } #endif if(wantNTLMhttp || wantProxyNTLMhttp) { /* Credentials are already checked, we can use this connection */ chosen = check; if((wantNTLMhttp && (check->http_ntlm_state != NTLMSTATE_NONE)) || (wantProxyNTLMhttp && (check->proxy_ntlm_state != NTLMSTATE_NONE))) { /* We must use this connection, no other */ *force_reuse = TRUE; break; } /* Continue look up for a better connection */ continue; } #endif if(canmultiplex) { /* We can multiplex if we want to. Let's continue looking for the optimal connection to use. */ if(!multiplexed) { /* We have the optimal connection. Let's stop looking. */ chosen = check; break; } #ifdef USE_NGHTTP2 /* If multiplexed, make sure we don't go over concurrency limit */ if(check->bits.multiplex) { /* Multiplexed connections can only be HTTP/2 for now */ struct http_conn *httpc = &check->proto.httpc; if(multiplexed >= httpc->settings.max_concurrent_streams) { infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)", multiplexed); continue; } else if(multiplexed >= Curl_multi_max_concurrent_streams(data->multi)) { infof(data, "client side MAX_CONCURRENT_STREAMS reached" ", skip (%zu)", multiplexed); continue; } } #endif /* When not multiplexed, we have a match here! */ chosen = check; infof(data, "Multiplexed connection found!"); break; } else { /* We have found a connection. Let's stop searching. */ chosen = check; break; } } } } if(chosen) { /* mark it as used before releasing the lock */ Curl_attach_connnection(data, chosen); CONNCACHE_UNLOCK(data); *usethis = chosen; return TRUE; /* yes, we found one to use! */ } CONNCACHE_UNLOCK(data); if(foundPendingCandidate && data->set.pipewait) { infof(data, "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set"); *waitpipe = TRUE; } return FALSE; /* no matching connecting exists */ } /* * verboseconnect() displays verbose information after a connect */ #ifndef CURL_DISABLE_VERBOSE_STRINGS void Curl_verboseconnect(struct Curl_easy *data, struct connectdata *conn) { if(data->set.verbose) infof(data, "Connected to %s (%s) port %u (#%ld)", #ifndef CURL_DISABLE_PROXY conn->bits.socksproxy ? conn->socks_proxy.host.dispname : conn->bits.httpproxy ? conn->http_proxy.host.dispname : #endif conn->bits.conn_to_host ? conn->conn_to_host.dispname : conn->host.dispname, conn->primary_ip, conn->port, conn->connection_id); } #endif /* * Helpers for IDNA conversions. */ bool Curl_is_ASCII_name(const char *hostname) { /* get an UNSIGNED local version of the pointer */ const unsigned char *ch = (const unsigned char *)hostname; if(!hostname) /* bad input, consider it ASCII! */ return TRUE; while(*ch) { if(*ch++ & 0x80) return FALSE; } return TRUE; } /* * Strip single trailing dot in the hostname, * primarily for SNI and http host header. */ static void strip_trailing_dot(struct hostname *host) { size_t len; if(!host || !host->name) return; len = strlen(host->name); if(len && (host->name[len-1] == '.')) host->name[len-1] = 0; } /* * Perform any necessary IDN conversion of hostname */ CURLcode Curl_idnconvert_hostname(struct Curl_easy *data, struct hostname *host) { #ifndef USE_LIBIDN2 (void)data; (void)data; #elif defined(CURL_DISABLE_VERBOSE_STRINGS) (void)data; #endif /* set the name we use to display the host name */ host->dispname = host->name; /* Check name for non-ASCII and convert hostname to ACE form if we can */ if(!Curl_is_ASCII_name(host->name)) { #ifdef USE_LIBIDN2 if(idn2_check_version(IDN2_VERSION)) { char *ace_hostname = NULL; #if IDN2_VERSION_NUMBER >= 0x00140000 /* IDN2_NFC_INPUT: Normalize input string using normalization form C. IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional processing. */ int flags = IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL; #else int flags = IDN2_NFC_INPUT; #endif int rc = IDN2_LOOKUP(host->name, &ace_hostname, flags); if(rc != IDN2_OK) /* fallback to TR46 Transitional mode for better IDNA2003 compatibility */ rc = IDN2_LOOKUP(host->name, &ace_hostname, IDN2_TRANSITIONAL); if(rc == IDN2_OK) { host->encalloc = (char *)ace_hostname; /* change the name pointer to point to the encoded hostname */ host->name = host->encalloc; } else { failf(data, "Failed to convert %s to ACE; %s", host->name, idn2_strerror(rc)); return CURLE_URL_MALFORMAT; } } #elif defined(USE_WIN32_IDN) char *ace_hostname = NULL; if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) { host->encalloc = ace_hostname; /* change the name pointer to point to the encoded hostname */ host->name = host->encalloc; } else { char buffer[STRERROR_LEN]; failf(data, "Failed to convert %s to ACE; %s", host->name, Curl_winapi_strerror(GetLastError(), buffer, sizeof(buffer))); return CURLE_URL_MALFORMAT; } #else infof(data, "IDN support not present, can't parse Unicode domains"); #endif } return CURLE_OK; } /* * Frees data allocated by idnconvert_hostname() */ void Curl_free_idnconverted_hostname(struct hostname *host) { #if defined(USE_LIBIDN2) if(host->encalloc) { idn2_free(host->encalloc); /* must be freed with idn2_free() since this was allocated by libidn */ host->encalloc = NULL; } #elif defined(USE_WIN32_IDN) free(host->encalloc); /* must be freed with free() since this was allocated by curl_win32_idn_to_ascii */ host->encalloc = NULL; #else (void)host; #endif } /* * Allocate and initialize a new connectdata object. */ static struct connectdata *allocate_conn(struct Curl_easy *data) { struct connectdata *conn = calloc(1, sizeof(struct connectdata)); if(!conn) return NULL; #ifdef USE_SSL /* The SSL backend-specific data (ssl_backend_data) objects are allocated as a separate array to ensure suitable alignment. Note that these backend pointers can be swapped by vtls (eg ssl backend data becomes proxy backend data). */ { size_t sslsize = Curl_ssl->sizeof_ssl_backend_data; char *ssl = calloc(4, sslsize); if(!ssl) { free(conn); return NULL; } conn->ssl_extra = ssl; conn->ssl[0].backend = (void *)ssl; conn->ssl[1].backend = (void *)(ssl + sslsize); #ifndef CURL_DISABLE_PROXY conn->proxy_ssl[0].backend = (void *)(ssl + 2 * sslsize); conn->proxy_ssl[1].backend = (void *)(ssl + 3 * sslsize); #endif } #endif conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined already from start to avoid NULL situations and checks */ /* and we setup a few fields in case we end up actually using this struct */ conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */ conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */ conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */ conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */ conn->connection_id = -1; /* no ID */ conn->port = -1; /* unknown at this point */ conn->remote_port = -1; /* unknown at this point */ #if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD) conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */ conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */ #endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */ /* Default protocol-independent behavior doesn't support persistent connections, so we set this to force-close. Protocols that support this need to set this to FALSE in their "curl_do" functions. */ connclose(conn, "Default to force-close"); /* Store creation time to help future close decision making */ conn->created = Curl_now(); /* Store current time to give a baseline to keepalive connection times. */ conn->keepalive = Curl_now(); #ifndef CURL_DISABLE_PROXY conn->http_proxy.proxytype = data->set.proxytype; conn->socks_proxy.proxytype = CURLPROXY_SOCKS4; /* note that these two proxy bits are now just on what looks to be requested, they may be altered down the road */ conn->bits.proxy = (data->set.str[STRING_PROXY] && *data->set.str[STRING_PROXY]) ? TRUE : FALSE; conn->bits.httpproxy = (conn->bits.proxy && (conn->http_proxy.proxytype == CURLPROXY_HTTP || conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 || conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ? TRUE : FALSE; conn->bits.socksproxy = (conn->bits.proxy && !conn->bits.httpproxy) ? TRUE : FALSE; if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) { conn->bits.proxy = TRUE; conn->bits.socksproxy = TRUE; } conn->bits.proxy_user_passwd = (data->state.aptr.proxyuser) ? TRUE : FALSE; conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy; #endif /* CURL_DISABLE_PROXY */ conn->bits.user_passwd = (data->state.aptr.user) ? TRUE : FALSE; #ifndef CURL_DISABLE_FTP conn->bits.ftp_use_epsv = data->set.ftp_use_epsv; conn->bits.ftp_use_eprt = data->set.ftp_use_eprt; #endif conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus; conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer; conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost; #ifndef CURL_DISABLE_PROXY conn->proxy_ssl_config.verifystatus = data->set.proxy_ssl.primary.verifystatus; conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer; conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost; #endif conn->ip_version = data->set.ipver; conn->bits.connect_only = data->set.connect_only; conn->transport = TRNSPRT_TCP; /* most of them are TCP streams */ #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \ defined(NTLM_WB_ENABLED) conn->ntlm.ntlm_auth_hlpr_socket = CURL_SOCKET_BAD; conn->proxyntlm.ntlm_auth_hlpr_socket = CURL_SOCKET_BAD; #endif /* Initialize the easy handle list */ Curl_llist_init(&conn->easyq, NULL); #ifdef HAVE_GSSAPI conn->data_prot = PROT_CLEAR; #endif /* Store the local bind parameters that will be used for this connection */ if(data->set.str[STRING_DEVICE]) { conn->localdev = strdup(data->set.str[STRING_DEVICE]); if(!conn->localdev) goto error; } conn->localportrange = data->set.localportrange; conn->localport = data->set.localport; /* the close socket stuff needs to be copied to the connection struct as it may live on without (this specific) Curl_easy */ conn->fclosesocket = data->set.fclosesocket; conn->closesocket_client = data->set.closesocket_client; conn->lastused = Curl_now(); /* used now */ return conn; error: Curl_llist_destroy(&conn->easyq, NULL); free(conn->localdev); #ifdef USE_SSL free(conn->ssl_extra); #endif free(conn); return NULL; } /* returns the handler if the given scheme is built-in */ const struct Curl_handler *Curl_builtin_scheme(const char *scheme) { const struct Curl_handler * const *pp; const struct Curl_handler *p; /* Scan protocol handler table and match against 'scheme'. The handler may be changed later when the protocol specific setup function is called. */ for(pp = protocols; (p = *pp) != NULL; pp++) if(strcasecompare(p->scheme, scheme)) /* Protocol found in table. Check if allowed */ return p; return NULL; /* not found */ } static CURLcode findprotocol(struct Curl_easy *data, struct connectdata *conn, const char *protostr) { const struct Curl_handler *p = Curl_builtin_scheme(protostr); if(p && /* Protocol found in table. Check if allowed */ (data->set.allowed_protocols & p->protocol)) { /* it is allowed for "normal" request, now do an extra check if this is the result of a redirect */ if(data->state.this_is_a_follow && !(data->set.redir_protocols & p->protocol)) /* nope, get out */ ; else { /* Perform setup complement if some. */ conn->handler = conn->given = p; /* 'port' and 'remote_port' are set in setup_connection_internals() */ return CURLE_OK; } } /* The protocol was not found in the table, but we don't have to assign it to anything since it is already assigned to a dummy-struct in the create_conn() function when the connectdata struct is allocated. */ failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME, protostr); return CURLE_UNSUPPORTED_PROTOCOL; } CURLcode Curl_uc_to_curlcode(CURLUcode uc) { switch(uc) { default: return CURLE_URL_MALFORMAT; case CURLUE_UNSUPPORTED_SCHEME: return CURLE_UNSUPPORTED_PROTOCOL; case CURLUE_OUT_OF_MEMORY: return CURLE_OUT_OF_MEMORY; case CURLUE_USER_NOT_ALLOWED: return CURLE_LOGIN_DENIED; } } /* * If the URL was set with an IPv6 numerical address with a zone id part, set * the scope_id based on that! */ static void zonefrom_url(CURLU *uh, struct Curl_easy *data, struct connectdata *conn) { char *zoneid; CURLUcode uc = curl_url_get(uh, CURLUPART_ZONEID, &zoneid, 0); #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)data; #endif if(!uc && zoneid) { char *endp; unsigned long scope = strtoul(zoneid, &endp, 10); if(!*endp && (scope < UINT_MAX)) /* A plain number, use it directly as a scope id. */ conn->scope_id = (unsigned int)scope; #if defined(HAVE_IF_NAMETOINDEX) else { #elif defined(WIN32) else if(Curl_if_nametoindex) { #endif #if defined(HAVE_IF_NAMETOINDEX) || defined(WIN32) /* Zone identifier is not numeric */ unsigned int scopeidx = 0; #if defined(WIN32) scopeidx = Curl_if_nametoindex(zoneid); #else scopeidx = if_nametoindex(zoneid); #endif if(!scopeidx) { #ifndef CURL_DISABLE_VERBOSE_STRINGS char buffer[STRERROR_LEN]; infof(data, "Invalid zoneid: %s; %s", zoneid, Curl_strerror(errno, buffer, sizeof(buffer))); #endif } else conn->scope_id = scopeidx; } #endif /* HAVE_IF_NAMETOINDEX || WIN32 */ free(zoneid); } } /* * Parse URL and fill in the relevant members of the connection struct. */ static CURLcode parseurlandfillconn(struct Curl_easy *data, struct connectdata *conn) { CURLcode result; CURLU *uh; CURLUcode uc; char *hostname; bool use_set_uh = (data->set.uh && !data->state.this_is_a_follow); up_free(data); /* cleanup previous leftovers first */ /* parse the URL */ if(use_set_uh) { uh = data->state.uh = curl_url_dup(data->set.uh); } else { uh = data->state.uh = curl_url(); } if(!uh) return CURLE_OUT_OF_MEMORY; if(data->set.str[STRING_DEFAULT_PROTOCOL] && !Curl_is_absolute_url(data->state.url, NULL, MAX_SCHEME_LEN)) { char *url = aprintf("%s://%s", data->set.str[STRING_DEFAULT_PROTOCOL], data->state.url); if(!url) return CURLE_OUT_OF_MEMORY; if(data->state.url_alloc) free(data->state.url); data->state.url = url; data->state.url_alloc = TRUE; } if(!use_set_uh) { char *newurl; uc = curl_url_set(uh, CURLUPART_URL, data->state.url, CURLU_GUESS_SCHEME | CURLU_NON_SUPPORT_SCHEME | (data->set.disallow_username_in_url ? CURLU_DISALLOW_USER : 0) | (data->set.path_as_is ? CURLU_PATH_AS_IS : 0)); if(uc) { DEBUGF(infof(data, "curl_url_set rejected %s: %s", data->state.url, curl_url_strerror(uc))); return Curl_uc_to_curlcode(uc); } /* after it was parsed, get the generated normalized version */ uc = curl_url_get(uh, CURLUPART_URL, &newurl, 0); if(uc) return Curl_uc_to_curlcode(uc); if(data->state.url_alloc) free(data->state.url); data->state.url = newurl; data->state.url_alloc = TRUE; } uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0); if(uc) return Curl_uc_to_curlcode(uc); uc = curl_url_get(uh, CURLUPART_HOST, &data->state.up.hostname, 0); if(uc) { if(!strcasecompare("file", data->state.up.scheme)) return CURLE_OUT_OF_MEMORY; } #ifndef CURL_DISABLE_HSTS if(data->hsts && strcasecompare("http", data->state.up.scheme)) { if(Curl_hsts(data->hsts, data->state.up.hostname, TRUE)) { char *url; Curl_safefree(data->state.up.scheme); uc = curl_url_set(uh, CURLUPART_SCHEME, "https", 0); if(uc) return Curl_uc_to_curlcode(uc); if(data->state.url_alloc) Curl_safefree(data->state.url); /* after update, get the updated version */ uc = curl_url_get(uh, CURLUPART_URL, &url, 0); if(uc) return Curl_uc_to_curlcode(uc); uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0); if(uc) { free(url); return Curl_uc_to_curlcode(uc); } data->state.url = url; data->state.url_alloc = TRUE; infof(data, "Switched from HTTP to HTTPS due to HSTS => %s", data->state.url); } } #endif result = findprotocol(data, conn, data->state.up.scheme); if(result) return result; /* * User name and password set with their own options override the * credentials possibly set in the URL. */ if(!data->state.aptr.user) { /* we don't use the URL API's URL decoder option here since it rejects control codes and we want to allow them for some schemes in the user and password fields */ uc = curl_url_get(uh, CURLUPART_USER, &data->state.up.user, 0); if(!uc) { char *decoded; result = Curl_urldecode(NULL, data->state.up.user, 0, &decoded, NULL, conn->handler->flags&PROTOPT_USERPWDCTRL ? REJECT_ZERO : REJECT_CTRL); if(result) return result; conn->user = decoded; conn->bits.user_passwd = TRUE; result = Curl_setstropt(&data->state.aptr.user, decoded); if(result) return result; } else if(uc != CURLUE_NO_USER) return Curl_uc_to_curlcode(uc); } if(!data->state.aptr.passwd) { uc = curl_url_get(uh, CURLUPART_PASSWORD, &data->state.up.password, 0); if(!uc) { char *decoded; result = Curl_urldecode(NULL, data->state.up.password, 0, &decoded, NULL, conn->handler->flags&PROTOPT_USERPWDCTRL ? REJECT_ZERO : REJECT_CTRL); if(result) return result; conn->passwd = decoded; conn->bits.user_passwd = TRUE; result = Curl_setstropt(&data->state.aptr.passwd, decoded); if(result) return result; } else if(uc != CURLUE_NO_PASSWORD) return Curl_uc_to_curlcode(uc); } uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options, CURLU_URLDECODE); if(!uc) { conn->options = strdup(data->state.up.options); if(!conn->options) return CURLE_OUT_OF_MEMORY; } else if(uc != CURLUE_NO_OPTIONS) return Curl_uc_to_curlcode(uc); uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, 0); if(uc) return Curl_uc_to_curlcode(uc); uc = curl_url_get(uh, CURLUPART_PORT, &data->state.up.port, CURLU_DEFAULT_PORT); if(uc) { if(!strcasecompare("file", data->state.up.scheme)) return CURLE_OUT_OF_MEMORY; } else { unsigned long port = strtoul(data->state.up.port, NULL, 10); conn->port = conn->remote_port = (data->set.use_port && data->state.allow_port) ? (int)data->set.use_port : curlx_ultous(port); } (void)curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, 0); hostname = data->state.up.hostname; if(hostname && hostname[0] == '[') { /* This looks like an IPv6 address literal. See if there is an address scope. */ size_t hlen; conn->bits.ipv6_ip = TRUE; /* cut off the brackets! */ hostname++; hlen = strlen(hostname); hostname[hlen - 1] = 0; zonefrom_url(uh, data, conn); } /* make sure the connect struct gets its own copy of the host name */ conn->host.rawalloc = strdup(hostname ? hostname : ""); if(!conn->host.rawalloc) return CURLE_OUT_OF_MEMORY; conn->host.name = conn->host.rawalloc; if(data->set.scope_id) /* Override any scope that was set above. */ conn->scope_id = data->set.scope_id; return CURLE_OK; } /* * If we're doing a resumed transfer, we need to setup our stuff * properly. */ static CURLcode setup_range(struct Curl_easy *data) { struct UrlState *s = &data->state; s->resume_from = data->set.set_resume_from; if(s->resume_from || data->set.str[STRING_SET_RANGE]) { if(s->rangestringalloc) free(s->range); if(s->resume_from) s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from); else s->range = strdup(data->set.str[STRING_SET_RANGE]); s->rangestringalloc = (s->range) ? TRUE : FALSE; if(!s->range) return CURLE_OUT_OF_MEMORY; /* tell ourselves to fetch this range */ s->use_range = TRUE; /* enable range download */ } else s->use_range = FALSE; /* disable range download */ return CURLE_OK; } /* * setup_connection_internals() - * * Setup connection internals specific to the requested protocol in the * Curl_easy. This is inited and setup before the connection is made but * is about the particular protocol that is to be used. * * This MUST get called after proxy magic has been figured out. */ static CURLcode setup_connection_internals(struct Curl_easy *data, struct connectdata *conn) { const struct Curl_handler *p; CURLcode result; /* Perform setup complement if some. */ p = conn->handler; if(p->setup_connection) { result = (*p->setup_connection)(data, conn); if(result) return result; p = conn->handler; /* May have changed. */ } if(conn->port < 0) /* we check for -1 here since if proxy was detected already, this was very likely already set to the proxy port */ conn->port = p->defport; return CURLE_OK; } /* * Curl_free_request_state() should free temp data that was allocated in the * Curl_easy for this single request. */ void Curl_free_request_state(struct Curl_easy *data) { Curl_safefree(data->req.p.http); Curl_safefree(data->req.newurl); #ifndef CURL_DISABLE_DOH if(data->req.doh) { Curl_close(&data->req.doh->probe[0].easy); Curl_close(&data->req.doh->probe[1].easy); } #endif } #ifndef CURL_DISABLE_PROXY /**************************************************************** * Checks if the host is in the noproxy list. returns true if it matches * and therefore the proxy should NOT be used. ****************************************************************/ static bool check_noproxy(const char *name, const char *no_proxy) { /* no_proxy=domain1.dom,host.domain2.dom * (a comma-separated list of hosts which should * not be proxied, or an asterisk to override * all proxy variables) */ if(no_proxy && no_proxy[0]) { size_t tok_start; size_t tok_end; const char *separator = ", "; size_t no_proxy_len; size_t namelen; char *endptr; if(strcasecompare("*", no_proxy)) { return TRUE; } /* NO_PROXY was specified and it wasn't just an asterisk */ no_proxy_len = strlen(no_proxy); if(name[0] == '[') { /* IPv6 numerical address */ endptr = strchr(name, ']'); if(!endptr) return FALSE; name++; namelen = endptr - name; } else namelen = strlen(name); for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) { while(tok_start < no_proxy_len && strchr(separator, no_proxy[tok_start]) != NULL) { /* Look for the beginning of the token. */ ++tok_start; } if(tok_start == no_proxy_len) break; /* It was all trailing separator chars, no more tokens. */ for(tok_end = tok_start; tok_end < no_proxy_len && strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end) /* Look for the end of the token. */ ; /* To match previous behavior, where it was necessary to specify * ".local.com" to prevent matching "notlocal.com", we will leave * the '.' off. */ if(no_proxy[tok_start] == '.') ++tok_start; if((tok_end - tok_start) <= namelen) { /* Match the last part of the name to the domain we are checking. */ const char *checkn = name + namelen - (tok_end - tok_start); if(strncasecompare(no_proxy + tok_start, checkn, tok_end - tok_start)) { if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') { /* We either have an exact match, or the previous character is a . * so it is within the same domain, so no proxy for this host. */ return TRUE; } } } /* if((tok_end - tok_start) <= namelen) */ } /* for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) */ } /* NO_PROXY was specified and it wasn't just an asterisk */ return FALSE; } #ifndef CURL_DISABLE_HTTP /**************************************************************** * Detect what (if any) proxy to use. Remember that this selects a host * name and is not limited to HTTP proxies only. * The returned pointer must be freed by the caller (unless NULL) ****************************************************************/ static char *detect_proxy(struct Curl_easy *data, struct connectdata *conn) { char *proxy = NULL; /* If proxy was not specified, we check for default proxy environment * variables, to enable i.e Lynx compliance: * * http_proxy=http://some.server.dom:port/ * https_proxy=http://some.server.dom:port/ * ftp_proxy=http://some.server.dom:port/ * no_proxy=domain1.dom,host.domain2.dom * (a comma-separated list of hosts which should * not be proxied, or an asterisk to override * all proxy variables) * all_proxy=http://some.server.dom:port/ * (seems to exist for the CERN www lib. Probably * the first to check for.) * * For compatibility, the all-uppercase versions of these variables are * checked if the lowercase versions don't exist. */ char proxy_env[128]; const char *protop = conn->handler->scheme; char *envp = proxy_env; char *prox; #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)data; #endif /* Now, build <protocol>_proxy and check for such a one to use */ while(*protop) *envp++ = (char)tolower((int)*protop++); /* append _proxy */ strcpy(envp, "_proxy"); /* read the protocol proxy: */ prox = curl_getenv(proxy_env); /* * We don't try the uppercase version of HTTP_PROXY because of * security reasons: * * When curl is used in a webserver application * environment (cgi or php), this environment variable can * be controlled by the web server user by setting the * http header 'Proxy:' to some value. * * This can cause 'internal' http/ftp requests to be * arbitrarily redirected by any external attacker. */ if(!prox && !strcasecompare("http_proxy", proxy_env)) { /* There was no lowercase variable, try the uppercase version: */ Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env)); prox = curl_getenv(proxy_env); } envp = proxy_env; if(prox) { proxy = prox; /* use this */ } else { envp = (char *)"all_proxy"; proxy = curl_getenv(envp); /* default proxy to use */ if(!proxy) { envp = (char *)"ALL_PROXY"; proxy = curl_getenv(envp); } } if(proxy) infof(data, "Uses proxy env variable %s == '%s'", envp, proxy); return proxy; } #endif /* CURL_DISABLE_HTTP */ /* * If this is supposed to use a proxy, we need to figure out the proxy * host name, so that we can re-use an existing connection * that may exist registered to the same proxy host. */ static CURLcode parse_proxy(struct Curl_easy *data, struct connectdata *conn, char *proxy, curl_proxytype proxytype) { char *portptr = NULL; int port = -1; char *proxyuser = NULL; char *proxypasswd = NULL; char *host; bool sockstype; CURLUcode uc; struct proxy_info *proxyinfo; CURLU *uhp = curl_url(); CURLcode result = CURLE_OK; char *scheme = NULL; if(!uhp) { result = CURLE_OUT_OF_MEMORY; goto error; } /* When parsing the proxy, allowing non-supported schemes since we have these made up ones for proxies. Guess scheme for URLs without it. */ uc = curl_url_set(uhp, CURLUPART_URL, proxy, CURLU_NON_SUPPORT_SCHEME|CURLU_GUESS_SCHEME); if(!uc) { /* parsed okay as a URL */ uc = curl_url_get(uhp, CURLUPART_SCHEME, &scheme, 0); if(uc) { result = CURLE_OUT_OF_MEMORY; goto error; } if(strcasecompare("https", scheme)) proxytype = CURLPROXY_HTTPS; else if(strcasecompare("socks5h", scheme)) proxytype = CURLPROXY_SOCKS5_HOSTNAME; else if(strcasecompare("socks5", scheme)) proxytype = CURLPROXY_SOCKS5; else if(strcasecompare("socks4a", scheme)) proxytype = CURLPROXY_SOCKS4A; else if(strcasecompare("socks4", scheme) || strcasecompare("socks", scheme)) proxytype = CURLPROXY_SOCKS4; else if(strcasecompare("http", scheme)) ; /* leave it as HTTP or HTTP/1.0 */ else { /* Any other xxx:// reject! */ failf(data, "Unsupported proxy scheme for \'%s\'", proxy); result = CURLE_COULDNT_CONNECT; goto error; } } else { failf(data, "Unsupported proxy syntax in \'%s\'", proxy); result = CURLE_COULDNT_RESOLVE_PROXY; goto error; } #ifdef USE_SSL if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY)) #endif if(proxytype == CURLPROXY_HTTPS) { failf(data, "Unsupported proxy \'%s\', libcurl is built without the " "HTTPS-proxy support.", proxy); result = CURLE_NOT_BUILT_IN; goto error; } sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME || proxytype == CURLPROXY_SOCKS5 || proxytype == CURLPROXY_SOCKS4A || proxytype == CURLPROXY_SOCKS4; proxyinfo = sockstype ? &conn->socks_proxy : &conn->http_proxy; proxyinfo->proxytype = proxytype; /* Is there a username and password given in this proxy url? */ uc = curl_url_get(uhp, CURLUPART_USER, &proxyuser, CURLU_URLDECODE); if(uc && (uc != CURLUE_NO_USER)) goto error; uc = curl_url_get(uhp, CURLUPART_PASSWORD, &proxypasswd, CURLU_URLDECODE); if(uc && (uc != CURLUE_NO_PASSWORD)) goto error; if(proxyuser || proxypasswd) { Curl_safefree(proxyinfo->user); proxyinfo->user = proxyuser; result = Curl_setstropt(&data->state.aptr.proxyuser, proxyuser); proxyuser = NULL; if(result) goto error; Curl_safefree(proxyinfo->passwd); if(!proxypasswd) { proxypasswd = strdup(""); if(!proxypasswd) { result = CURLE_OUT_OF_MEMORY; goto error; } } proxyinfo->passwd = proxypasswd; result = Curl_setstropt(&data->state.aptr.proxypasswd, proxypasswd); proxypasswd = NULL; if(result) goto error; conn->bits.proxy_user_passwd = TRUE; /* enable it */ } (void)curl_url_get(uhp, CURLUPART_PORT, &portptr, 0); if(portptr) { port = (int)strtol(portptr, NULL, 10); free(portptr); } else { if(data->set.proxyport) /* None given in the proxy string, then get the default one if it is given */ port = (int)data->set.proxyport; else { if(proxytype == CURLPROXY_HTTPS) port = CURL_DEFAULT_HTTPS_PROXY_PORT; else port = CURL_DEFAULT_PROXY_PORT; } } if(port >= 0) { proxyinfo->port = port; if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc) conn->port = port; } /* now, clone the proxy host name */ uc = curl_url_get(uhp, CURLUPART_HOST, &host, CURLU_URLDECODE); if(uc) { result = CURLE_OUT_OF_MEMORY; goto error; } Curl_safefree(proxyinfo->host.rawalloc); proxyinfo->host.rawalloc = host; if(host[0] == '[') { /* this is a numerical IPv6, strip off the brackets */ size_t len = strlen(host); host[len-1] = 0; /* clear the trailing bracket */ host++; zonefrom_url(uhp, data, conn); } proxyinfo->host.name = host; error: free(proxyuser); free(proxypasswd); free(scheme); curl_url_cleanup(uhp); return result; } /* * Extract the user and password from the authentication string */ static CURLcode parse_proxy_auth(struct Curl_easy *data, struct connectdata *conn) { const char *proxyuser = data->state.aptr.proxyuser ? data->state.aptr.proxyuser : ""; const char *proxypasswd = data->state.aptr.proxypasswd ? data->state.aptr.proxypasswd : ""; CURLcode result = CURLE_OK; if(proxyuser) { result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL, REJECT_ZERO); if(!result) result = Curl_setstropt(&data->state.aptr.proxyuser, conn->http_proxy.user); } if(!result && proxypasswd) { result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd, NULL, REJECT_ZERO); if(!result) result = Curl_setstropt(&data->state.aptr.proxypasswd, conn->http_proxy.passwd); } return result; } /* create_conn helper to parse and init proxy values. to be called after unix socket init but before any proxy vars are evaluated. */ static CURLcode create_conn_helper_init_proxy(struct Curl_easy *data, struct connectdata *conn) { char *proxy = NULL; char *socksproxy = NULL; char *no_proxy = NULL; CURLcode result = CURLE_OK; /************************************************************* * Extract the user and password from the authentication string *************************************************************/ if(conn->bits.proxy_user_passwd) { result = parse_proxy_auth(data, conn); if(result) goto out; } /************************************************************* * Detect what (if any) proxy to use *************************************************************/ if(data->set.str[STRING_PROXY]) { proxy = strdup(data->set.str[STRING_PROXY]); /* if global proxy is set, this is it */ if(NULL == proxy) { failf(data, "memory shortage"); result = CURLE_OUT_OF_MEMORY; goto out; } } if(data->set.str[STRING_PRE_PROXY]) { socksproxy = strdup(data->set.str[STRING_PRE_PROXY]); /* if global socks proxy is set, this is it */ if(NULL == socksproxy) { failf(data, "memory shortage"); result = CURLE_OUT_OF_MEMORY; goto out; } } if(!data->set.str[STRING_NOPROXY]) { const char *p = "no_proxy"; no_proxy = curl_getenv(p); if(!no_proxy) { p = "NO_PROXY"; no_proxy = curl_getenv(p); } if(no_proxy) { infof(data, "Uses proxy env variable %s == '%s'", p, no_proxy); } } if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ? data->set.str[STRING_NOPROXY] : no_proxy)) { Curl_safefree(proxy); Curl_safefree(socksproxy); } #ifndef CURL_DISABLE_HTTP else if(!proxy && !socksproxy) /* if the host is not in the noproxy list, detect proxy. */ proxy = detect_proxy(data, conn); #endif /* CURL_DISABLE_HTTP */ Curl_safefree(no_proxy); #ifdef USE_UNIX_SOCKETS /* For the time being do not mix proxy and unix domain sockets. See #1274 */ if(proxy && conn->unix_domain_socket) { free(proxy); proxy = NULL; } #endif if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) { free(proxy); /* Don't bother with an empty proxy string or if the protocol doesn't work with network */ proxy = NULL; } if(socksproxy && (!*socksproxy || (conn->handler->flags & PROTOPT_NONETWORK))) { free(socksproxy); /* Don't bother with an empty socks proxy string or if the protocol doesn't work with network */ socksproxy = NULL; } /*********************************************************************** * If this is supposed to use a proxy, we need to figure out the proxy host * name, proxy type and port number, so that we can re-use an existing * connection that may exist registered to the same proxy host. ***********************************************************************/ if(proxy || socksproxy) { if(proxy) { result = parse_proxy(data, conn, proxy, conn->http_proxy.proxytype); Curl_safefree(proxy); /* parse_proxy copies the proxy string */ if(result) goto out; } if(socksproxy) { result = parse_proxy(data, conn, socksproxy, conn->socks_proxy.proxytype); /* parse_proxy copies the socks proxy string */ Curl_safefree(socksproxy); if(result) goto out; } if(conn->http_proxy.host.rawalloc) { #ifdef CURL_DISABLE_HTTP /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */ result = CURLE_UNSUPPORTED_PROTOCOL; goto out; #else /* force this connection's protocol to become HTTP if compatible */ if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) { if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) && !conn->bits.tunnel_proxy) conn->handler = &Curl_handler_http; else /* if not converting to HTTP over the proxy, enforce tunneling */ conn->bits.tunnel_proxy = TRUE; } conn->bits.httpproxy = TRUE; #endif } else { conn->bits.httpproxy = FALSE; /* not a HTTP proxy */ conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */ } if(conn->socks_proxy.host.rawalloc) { if(!conn->http_proxy.host.rawalloc) { /* once a socks proxy */ if(!conn->socks_proxy.user) { conn->socks_proxy.user = conn->http_proxy.user; conn->http_proxy.user = NULL; Curl_safefree(conn->socks_proxy.passwd); conn->socks_proxy.passwd = conn->http_proxy.passwd; conn->http_proxy.passwd = NULL; } } conn->bits.socksproxy = TRUE; } else conn->bits.socksproxy = FALSE; /* not a socks proxy */ } else { conn->bits.socksproxy = FALSE; conn->bits.httpproxy = FALSE; } conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy; if(!conn->bits.proxy) { /* we aren't using the proxy after all... */ conn->bits.proxy = FALSE; conn->bits.httpproxy = FALSE; conn->bits.socksproxy = FALSE; conn->bits.proxy_user_passwd = FALSE; conn->bits.tunnel_proxy = FALSE; /* CURLPROXY_HTTPS does not have its own flag in conn->bits, yet we need to signal that CURLPROXY_HTTPS is not used for this connection */ conn->http_proxy.proxytype = CURLPROXY_HTTP; } out: free(socksproxy); free(proxy); return result; } #endif /* CURL_DISABLE_PROXY */ /* * Curl_parse_login_details() * * This is used to parse a login string for user name, password and options in * the following formats: * * user * user:password * user:password;options * user;options * user;options:password * :password * :password;options * ;options * ;options:password * * Parameters: * * login [in] - The login string. * len [in] - The length of the login string. * userp [in/out] - The address where a pointer to newly allocated memory * holding the user will be stored upon completion. * passwdp [in/out] - The address where a pointer to newly allocated memory * holding the password will be stored upon completion. * optionsp [in/out] - The address where a pointer to newly allocated memory * holding the options will be stored upon completion. * * Returns CURLE_OK on success. */ CURLcode Curl_parse_login_details(const char *login, const size_t len, char **userp, char **passwdp, char **optionsp) { CURLcode result = CURLE_OK; char *ubuf = NULL; char *pbuf = NULL; char *obuf = NULL; const char *psep = NULL; const char *osep = NULL; size_t ulen; size_t plen; size_t olen; /* the input length check is because this is called directly from setopt and isn't going through the regular string length check */ size_t llen = strlen(login); if(llen > CURL_MAX_INPUT_LENGTH) return CURLE_BAD_FUNCTION_ARGUMENT; /* Attempt to find the password separator */ if(passwdp) { psep = strchr(login, ':'); /* Within the constraint of the login string */ if(psep >= login + len) psep = NULL; } /* Attempt to find the options separator */ if(optionsp) { osep = strchr(login, ';'); /* Within the constraint of the login string */ if(osep >= login + len) osep = NULL; } /* Calculate the portion lengths */ ulen = (psep ? (size_t)(osep && psep > osep ? osep - login : psep - login) : (osep ? (size_t)(osep - login) : len)); plen = (psep ? (osep && osep > psep ? (size_t)(osep - psep) : (size_t)(login + len - psep)) - 1 : 0); olen = (osep ? (psep && psep > osep ? (size_t)(psep - osep) : (size_t)(login + len - osep)) - 1 : 0); /* Allocate the user portion buffer */ if(userp && ulen) { ubuf = malloc(ulen + 1); if(!ubuf) result = CURLE_OUT_OF_MEMORY; } /* Allocate the password portion buffer */ if(!result && passwdp && plen) { pbuf = malloc(plen + 1); if(!pbuf) { free(ubuf); result = CURLE_OUT_OF_MEMORY; } } /* Allocate the options portion buffer */ if(!result && optionsp && olen) { obuf = malloc(olen + 1); if(!obuf) { free(pbuf); free(ubuf); result = CURLE_OUT_OF_MEMORY; } } if(!result) { /* Store the user portion if necessary */ if(ubuf) { memcpy(ubuf, login, ulen); ubuf[ulen] = '\0'; Curl_safefree(*userp); *userp = ubuf; } /* Store the password portion if necessary */ if(pbuf) { memcpy(pbuf, psep + 1, plen); pbuf[plen] = '\0'; Curl_safefree(*passwdp); *passwdp = pbuf; } /* Store the options portion if necessary */ if(obuf) { memcpy(obuf, osep + 1, olen); obuf[olen] = '\0'; Curl_safefree(*optionsp); *optionsp = obuf; } } return result; } /************************************************************* * Figure out the remote port number and fix it in the URL * * No matter if we use a proxy or not, we have to figure out the remote * port number of various reasons. * * The port number embedded in the URL is replaced, if necessary. *************************************************************/ static CURLcode parse_remote_port(struct Curl_easy *data, struct connectdata *conn) { if(data->set.use_port && data->state.allow_port) { /* if set, we use this instead of the port possibly given in the URL */ char portbuf[16]; CURLUcode uc; conn->remote_port = (unsigned short)data->set.use_port; msnprintf(portbuf, sizeof(portbuf), "%d", conn->remote_port); uc = curl_url_set(data->state.uh, CURLUPART_PORT, portbuf, 0); if(uc) return CURLE_OUT_OF_MEMORY; } return CURLE_OK; } /* * Override the login details from the URL with that in the CURLOPT_USERPWD * option or a .netrc file, if applicable. */ static CURLcode override_login(struct Curl_easy *data, struct connectdata *conn) { CURLUcode uc; char **userp = &conn->user; char **passwdp = &conn->passwd; char **optionsp = &conn->options; #ifndef CURL_DISABLE_NETRC if(data->set.use_netrc == CURL_NETRC_REQUIRED && conn->bits.user_passwd) { Curl_safefree(*userp); Curl_safefree(*passwdp); conn->bits.user_passwd = FALSE; /* disable user+password */ } #endif if(data->set.str[STRING_OPTIONS]) { free(*optionsp); *optionsp = strdup(data->set.str[STRING_OPTIONS]); if(!*optionsp) return CURLE_OUT_OF_MEMORY; } #ifndef CURL_DISABLE_NETRC conn->bits.netrc = FALSE; if(data->set.use_netrc && !data->set.str[STRING_USERNAME]) { bool netrc_user_changed = FALSE; bool netrc_passwd_changed = FALSE; int ret; ret = Curl_parsenetrc(conn->host.name, userp, passwdp, &netrc_user_changed, &netrc_passwd_changed, data->set.str[STRING_NETRC_FILE]); if(ret > 0) { infof(data, "Couldn't find host %s in the %s file; using defaults", conn->host.name, data->set.str[STRING_NETRC_FILE]); } else if(ret < 0) { return CURLE_OUT_OF_MEMORY; } else { /* set bits.netrc TRUE to remember that we got the name from a .netrc file, so that it is safe to use even if we followed a Location: to a different host or similar. */ conn->bits.netrc = TRUE; conn->bits.user_passwd = TRUE; /* enable user+password */ } } #endif /* for updated strings, we update them in the URL */ if(*userp) { CURLcode result = Curl_setstropt(&data->state.aptr.user, *userp); if(result) return result; } if(data->state.aptr.user) { uc = curl_url_set(data->state.uh, CURLUPART_USER, data->state.aptr.user, CURLU_URLENCODE); if(uc) return Curl_uc_to_curlcode(uc); if(!*userp) { *userp = strdup(data->state.aptr.user); if(!*userp) return CURLE_OUT_OF_MEMORY; } } if(*passwdp) { CURLcode result = Curl_setstropt(&data->state.aptr.passwd, *passwdp); if(result) return result; } if(data->state.aptr.passwd) { uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD, data->state.aptr.passwd, CURLU_URLENCODE); if(uc) return Curl_uc_to_curlcode(uc); if(!*passwdp) { *passwdp = strdup(data->state.aptr.passwd); if(!*passwdp) return CURLE_OUT_OF_MEMORY; } } return CURLE_OK; } /* * Set the login details so they're available in the connection */ static CURLcode set_login(struct connectdata *conn) { CURLcode result = CURLE_OK; const char *setuser = CURL_DEFAULT_USER; const char *setpasswd = CURL_DEFAULT_PASSWORD; /* If our protocol needs a password and we have none, use the defaults */ if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) ; else { setuser = ""; setpasswd = ""; } /* Store the default user */ if(!conn->user) { conn->user = strdup(setuser); if(!conn->user) return CURLE_OUT_OF_MEMORY; } /* Store the default password */ if(!conn->passwd) { conn->passwd = strdup(setpasswd); if(!conn->passwd) result = CURLE_OUT_OF_MEMORY; } return result; } /* * Parses a "host:port" string to connect to. * The hostname and the port may be empty; in this case, NULL is returned for * the hostname and -1 for the port. */ static CURLcode parse_connect_to_host_port(struct Curl_easy *data, const char *host, char **hostname_result, int *port_result) { char *host_dup; char *hostptr; char *host_portno; char *portptr; int port = -1; CURLcode result = CURLE_OK; #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) data; #endif *hostname_result = NULL; *port_result = -1; if(!host || !*host) return CURLE_OK; host_dup = strdup(host); if(!host_dup) return CURLE_OUT_OF_MEMORY; hostptr = host_dup; /* start scanning for port number at this point */ portptr = hostptr; /* detect and extract RFC6874-style IPv6-addresses */ if(*hostptr == '[') { #ifdef ENABLE_IPV6 char *ptr = ++hostptr; /* advance beyond the initial bracket */ while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.'))) ptr++; if(*ptr == '%') { /* There might be a zone identifier */ if(strncmp("%25", ptr, 3)) infof(data, "Please URL encode %% as %%25, see RFC 6874."); ptr++; /* Allow unreserved characters as defined in RFC 3986 */ while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') || (*ptr == '.') || (*ptr == '_') || (*ptr == '~'))) ptr++; } if(*ptr == ']') /* yeps, it ended nicely with a bracket as well */ *ptr++ = '\0'; else infof(data, "Invalid IPv6 address format"); portptr = ptr; /* Note that if this didn't end with a bracket, we still advanced the * hostptr first, but I can't see anything wrong with that as no host * name nor a numeric can legally start with a bracket. */ #else failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in!"); result = CURLE_NOT_BUILT_IN; goto error; #endif } /* Get port number off server.com:1080 */ host_portno = strchr(portptr, ':'); if(host_portno) { char *endp = NULL; *host_portno = '\0'; /* cut off number from host name */ host_portno++; if(*host_portno) { long portparse = strtol(host_portno, &endp, 10); if((endp && *endp) || (portparse < 0) || (portparse > 65535)) { failf(data, "No valid port number in connect to host string (%s)", host_portno); result = CURLE_SETOPT_OPTION_SYNTAX; goto error; } else port = (int)portparse; /* we know it will fit */ } } /* now, clone the cleaned host name */ if(hostptr) { *hostname_result = strdup(hostptr); if(!*hostname_result) { result = CURLE_OUT_OF_MEMORY; goto error; } } *port_result = port; error: free(host_dup); return result; } /* * Parses one "connect to" string in the form: * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT". */ static CURLcode parse_connect_to_string(struct Curl_easy *data, struct connectdata *conn, const char *conn_to_host, char **host_result, int *port_result) { CURLcode result = CURLE_OK; const char *ptr = conn_to_host; int host_match = FALSE; int port_match = FALSE; *host_result = NULL; *port_result = -1; if(*ptr == ':') { /* an empty hostname always matches */ host_match = TRUE; ptr++; } else { /* check whether the URL's hostname matches */ size_t hostname_to_match_len; char *hostname_to_match = aprintf("%s%s%s", conn->bits.ipv6_ip ? "[" : "", conn->host.name, conn->bits.ipv6_ip ? "]" : ""); if(!hostname_to_match) return CURLE_OUT_OF_MEMORY; hostname_to_match_len = strlen(hostname_to_match); host_match = strncasecompare(ptr, hostname_to_match, hostname_to_match_len); free(hostname_to_match); ptr += hostname_to_match_len; host_match = host_match && *ptr == ':'; ptr++; } if(host_match) { if(*ptr == ':') { /* an empty port always matches */ port_match = TRUE; ptr++; } else { /* check whether the URL's port matches */ char *ptr_next = strchr(ptr, ':'); if(ptr_next) { char *endp = NULL; long port_to_match = strtol(ptr, &endp, 10); if((endp == ptr_next) && (port_to_match == conn->remote_port)) { port_match = TRUE; ptr = ptr_next + 1; } } } } if(host_match && port_match) { /* parse the hostname and port to connect to */ result = parse_connect_to_host_port(data, ptr, host_result, port_result); } return result; } /* * Processes all strings in the "connect to" slist, and uses the "connect * to host" and "connect to port" of the first string that matches. */ static CURLcode parse_connect_to_slist(struct Curl_easy *data, struct connectdata *conn, struct curl_slist *conn_to_host) { CURLcode result = CURLE_OK; char *host = NULL; int port = -1; while(conn_to_host && !host && port == -1) { result = parse_connect_to_string(data, conn, conn_to_host->data, &host, &port); if(result) return result; if(host && *host) { conn->conn_to_host.rawalloc = host; conn->conn_to_host.name = host; conn->bits.conn_to_host = TRUE; infof(data, "Connecting to hostname: %s", host); } else { /* no "connect to host" */ conn->bits.conn_to_host = FALSE; Curl_safefree(host); } if(port >= 0) { conn->conn_to_port = port; conn->bits.conn_to_port = TRUE; infof(data, "Connecting to port: %d", port); } else { /* no "connect to port" */ conn->bits.conn_to_port = FALSE; port = -1; } conn_to_host = conn_to_host->next; } #ifndef CURL_DISABLE_ALTSVC if(data->asi && !host && (port == -1) && ((conn->handler->protocol == CURLPROTO_HTTPS) || #ifdef CURLDEBUG /* allow debug builds to circumvent the HTTPS restriction */ getenv("CURL_ALTSVC_HTTP") #else 0 #endif )) { /* no connect_to match, try alt-svc! */ enum alpnid srcalpnid; bool hit; struct altsvc *as; const int allowed_versions = ( ALPN_h1 #ifdef USE_NGHTTP2 | ALPN_h2 #endif #ifdef ENABLE_QUIC | ALPN_h3 #endif ) & data->asi->flags; host = conn->host.rawalloc; #ifdef USE_NGHTTP2 /* with h2 support, check that first */ srcalpnid = ALPN_h2; hit = Curl_altsvc_lookup(data->asi, srcalpnid, host, conn->remote_port, /* from */ &as /* to */, allowed_versions); if(!hit) #endif { srcalpnid = ALPN_h1; hit = Curl_altsvc_lookup(data->asi, srcalpnid, host, conn->remote_port, /* from */ &as /* to */, allowed_versions); } if(hit) { char *hostd = strdup((char *)as->dst.host); if(!hostd) return CURLE_OUT_OF_MEMORY; conn->conn_to_host.rawalloc = hostd; conn->conn_to_host.name = hostd; conn->bits.conn_to_host = TRUE; conn->conn_to_port = as->dst.port; conn->bits.conn_to_port = TRUE; conn->bits.altused = TRUE; infof(data, "Alt-svc connecting from [%s]%s:%d to [%s]%s:%d", Curl_alpnid2str(srcalpnid), host, conn->remote_port, Curl_alpnid2str(as->dst.alpnid), hostd, as->dst.port); if(srcalpnid != as->dst.alpnid) { /* protocol version switch */ switch(as->dst.alpnid) { case ALPN_h1: conn->httpversion = 11; break; case ALPN_h2: conn->httpversion = 20; break; case ALPN_h3: conn->transport = TRNSPRT_QUIC; conn->httpversion = 30; break; default: /* shouldn't be possible */ break; } } } } #endif return result; } /************************************************************* * Resolve the address of the server or proxy *************************************************************/ static CURLcode resolve_server(struct Curl_easy *data, struct connectdata *conn, bool *async) { CURLcode result = CURLE_OK; timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE); DEBUGASSERT(conn); DEBUGASSERT(data); /************************************************************* * Resolve the name of the server or proxy *************************************************************/ if(conn->bits.reuse) /* We're reusing the connection - no need to resolve anything, and idnconvert_hostname() was called already in create_conn() for the re-use case. */ *async = FALSE; else { /* this is a fresh connect */ int rc; struct Curl_dns_entry *hostaddr = NULL; #ifdef USE_UNIX_SOCKETS if(conn->unix_domain_socket) { /* Unix domain sockets are local. The host gets ignored, just use the * specified domain socket address. Do not cache "DNS entries". There is * no DNS involved and we already have the filesystem path available */ const char *path = conn->unix_domain_socket; hostaddr = calloc(1, sizeof(struct Curl_dns_entry)); if(!hostaddr) result = CURLE_OUT_OF_MEMORY; else { bool longpath = FALSE; hostaddr->addr = Curl_unix2addr(path, &longpath, conn->bits.abstract_unix_socket); if(hostaddr->addr) hostaddr->inuse++; else { /* Long paths are not supported for now */ if(longpath) { failf(data, "Unix socket path too long: '%s'", path); result = CURLE_COULDNT_RESOLVE_HOST; } else result = CURLE_OUT_OF_MEMORY; free(hostaddr); hostaddr = NULL; } } } else #endif if(!conn->bits.proxy) { struct hostname *connhost; if(conn->bits.conn_to_host) connhost = &conn->conn_to_host; else connhost = &conn->host; /* If not connecting via a proxy, extract the port from the URL, if it is * there, thus overriding any defaults that might have been set above. */ if(conn->bits.conn_to_port) conn->port = conn->conn_to_port; else conn->port = conn->remote_port; /* Resolve target host right on */ conn->hostname_resolve = strdup(connhost->name); if(!conn->hostname_resolve) return CURLE_OUT_OF_MEMORY; rc = Curl_resolv_timeout(data, conn->hostname_resolve, (int)conn->port, &hostaddr, timeout_ms); if(rc == CURLRESOLV_PENDING) *async = TRUE; else if(rc == CURLRESOLV_TIMEDOUT) { failf(data, "Failed to resolve host '%s' with timeout after %ld ms", connhost->dispname, Curl_timediff(Curl_now(), data->progress.t_startsingle)); result = CURLE_OPERATION_TIMEDOUT; } else if(!hostaddr) { failf(data, "Could not resolve host: %s", connhost->dispname); result = CURLE_COULDNT_RESOLVE_HOST; /* don't return yet, we need to clean up the timeout first */ } } #ifndef CURL_DISABLE_PROXY else { /* This is a proxy that hasn't been resolved yet. */ struct hostname * const host = conn->bits.socksproxy ? &conn->socks_proxy.host : &conn->http_proxy.host; /* resolve proxy */ conn->hostname_resolve = strdup(host->name); if(!conn->hostname_resolve) return CURLE_OUT_OF_MEMORY; rc = Curl_resolv_timeout(data, conn->hostname_resolve, (int)conn->port, &hostaddr, timeout_ms); if(rc == CURLRESOLV_PENDING) *async = TRUE; else if(rc == CURLRESOLV_TIMEDOUT) result = CURLE_OPERATION_TIMEDOUT; else if(!hostaddr) { failf(data, "Couldn't resolve proxy '%s'", host->dispname); result = CURLE_COULDNT_RESOLVE_PROXY; /* don't return yet, we need to clean up the timeout first */ } } #endif DEBUGASSERT(conn->dns_entry == NULL); conn->dns_entry = hostaddr; } return result; } /* * Cleanup the connection just allocated before we can move along and use the * previously existing one. All relevant data is copied over and old_conn is * ready for freeing once this function returns. */ static void reuse_conn(struct Curl_easy *data, struct connectdata *old_conn, struct connectdata *conn) { /* 'local_ip' and 'local_port' get filled with local's numerical ip address and port number whenever an outgoing connection is **established** from the primary socket to a remote address. */ char local_ip[MAX_IPADR_LEN] = ""; int local_port = -1; #ifndef CURL_DISABLE_PROXY Curl_free_idnconverted_hostname(&old_conn->http_proxy.host); Curl_free_idnconverted_hostname(&old_conn->socks_proxy.host); free(old_conn->http_proxy.host.rawalloc); free(old_conn->socks_proxy.host.rawalloc); Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config); #endif /* free the SSL config struct from this connection struct as this was allocated in vain and is targeted for destruction */ Curl_free_primary_ssl_config(&old_conn->ssl_config); /* get the user+password information from the old_conn struct since it may * be new for this request even when we re-use an existing connection */ conn->bits.user_passwd = old_conn->bits.user_passwd; if(conn->bits.user_passwd) { /* use the new user name and password though */ Curl_safefree(conn->user); Curl_safefree(conn->passwd); conn->user = old_conn->user; conn->passwd = old_conn->passwd; old_conn->user = NULL; old_conn->passwd = NULL; } #ifndef CURL_DISABLE_PROXY conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd; if(conn->bits.proxy_user_passwd) { /* use the new proxy user name and proxy password though */ Curl_safefree(conn->http_proxy.user); Curl_safefree(conn->socks_proxy.user); Curl_safefree(conn->http_proxy.passwd); Curl_safefree(conn->socks_proxy.passwd); conn->http_proxy.user = old_conn->http_proxy.user; conn->socks_proxy.user = old_conn->socks_proxy.user; conn->http_proxy.passwd = old_conn->http_proxy.passwd; conn->socks_proxy.passwd = old_conn->socks_proxy.passwd; old_conn->http_proxy.user = NULL; old_conn->socks_proxy.user = NULL; old_conn->http_proxy.passwd = NULL; old_conn->socks_proxy.passwd = NULL; } Curl_safefree(old_conn->http_proxy.user); Curl_safefree(old_conn->socks_proxy.user); Curl_safefree(old_conn->http_proxy.passwd); Curl_safefree(old_conn->socks_proxy.passwd); #endif /* host can change, when doing keepalive with a proxy or if the case is different this time etc */ Curl_free_idnconverted_hostname(&conn->host); Curl_free_idnconverted_hostname(&conn->conn_to_host); Curl_safefree(conn->host.rawalloc); Curl_safefree(conn->conn_to_host.rawalloc); conn->host = old_conn->host; conn->conn_to_host = old_conn->conn_to_host; conn->conn_to_port = old_conn->conn_to_port; conn->remote_port = old_conn->remote_port; Curl_safefree(conn->hostname_resolve); conn->hostname_resolve = old_conn->hostname_resolve; old_conn->hostname_resolve = NULL; /* persist connection info in session handle */ if(conn->transport == TRNSPRT_TCP) { Curl_conninfo_local(data, conn->sock[FIRSTSOCKET], local_ip, &local_port); } Curl_persistconninfo(data, conn, local_ip, local_port); conn_reset_all_postponed_data(old_conn); /* free buffers */ /* re-use init */ conn->bits.reuse = TRUE; /* yes, we're re-using here */ Curl_safefree(old_conn->user); Curl_safefree(old_conn->passwd); Curl_safefree(old_conn->options); Curl_safefree(old_conn->localdev); Curl_llist_destroy(&old_conn->easyq, NULL); #ifdef USE_UNIX_SOCKETS Curl_safefree(old_conn->unix_domain_socket); #endif } /** * create_conn() sets up a new connectdata struct, or re-uses an already * existing one, and resolves host name. * * if this function returns CURLE_OK and *async is set to TRUE, the resolve * response will be coming asynchronously. If *async is FALSE, the name is * already resolved. * * @param data The sessionhandle pointer * @param in_connect is set to the next connection data pointer * @param async is set TRUE when an async DNS resolution is pending * @see Curl_setup_conn() * */ static CURLcode create_conn(struct Curl_easy *data, struct connectdata **in_connect, bool *async) { CURLcode result = CURLE_OK; struct connectdata *conn; struct connectdata *conn_temp = NULL; bool reuse; bool connections_available = TRUE; bool force_reuse = FALSE; bool waitpipe = FALSE; size_t max_host_connections = Curl_multi_max_host_connections(data->multi); size_t max_total_connections = Curl_multi_max_total_connections(data->multi); *async = FALSE; *in_connect = NULL; /************************************************************* * Check input data *************************************************************/ if(!data->state.url) { result = CURLE_URL_MALFORMAT; goto out; } /* First, split up the current URL in parts so that we can use the parts for checking against the already present connections. In order to not have to modify everything at once, we allocate a temporary connection data struct and fill in for comparison purposes. */ conn = allocate_conn(data); if(!conn) { result = CURLE_OUT_OF_MEMORY; goto out; } /* We must set the return variable as soon as possible, so that our parent can cleanup any possible allocs we may have done before any failure */ *in_connect = conn; result = parseurlandfillconn(data, conn); if(result) goto out; if(data->set.str[STRING_SASL_AUTHZID]) { conn->sasl_authzid = strdup(data->set.str[STRING_SASL_AUTHZID]); if(!conn->sasl_authzid) { result = CURLE_OUT_OF_MEMORY; goto out; } } #ifdef USE_UNIX_SOCKETS if(data->set.str[STRING_UNIX_SOCKET_PATH]) { conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]); if(!conn->unix_domain_socket) { result = CURLE_OUT_OF_MEMORY; goto out; } conn->bits.abstract_unix_socket = data->set.abstract_unix_socket; } #endif /* After the unix socket init but before the proxy vars are used, parse and initialize the proxy vars */ #ifndef CURL_DISABLE_PROXY result = create_conn_helper_init_proxy(data, conn); if(result) goto out; /************************************************************* * If the protocol is using SSL and HTTP proxy is used, we set * the tunnel_proxy bit. *************************************************************/ if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy) conn->bits.tunnel_proxy = TRUE; #endif /************************************************************* * Figure out the remote port number and fix it in the URL *************************************************************/ result = parse_remote_port(data, conn); if(result) goto out; /* Check for overridden login details and set them accordingly so that they are known when protocol->setup_connection is called! */ result = override_login(data, conn); if(result) goto out; result = set_login(conn); /* default credentials */ if(result) goto out; /************************************************************* * Process the "connect to" linked list of hostname/port mappings. * Do this after the remote port number has been fixed in the URL. *************************************************************/ result = parse_connect_to_slist(data, conn, data->set.connect_to); if(result) goto out; /************************************************************* * IDN-convert the hostnames *************************************************************/ result = Curl_idnconvert_hostname(data, &conn->host); if(result) goto out; if(conn->bits.conn_to_host) { result = Curl_idnconvert_hostname(data, &conn->conn_to_host); if(result) goto out; } #ifndef CURL_DISABLE_PROXY if(conn->bits.httpproxy) { result = Curl_idnconvert_hostname(data, &conn->http_proxy.host); if(result) goto out; } if(conn->bits.socksproxy) { result = Curl_idnconvert_hostname(data, &conn->socks_proxy.host); if(result) goto out; } #endif /************************************************************* * Check whether the host and the "connect to host" are equal. * Do this after the hostnames have been IDN-converted. *************************************************************/ if(conn->bits.conn_to_host && strcasecompare(conn->conn_to_host.name, conn->host.name)) { conn->bits.conn_to_host = FALSE; } /************************************************************* * Check whether the port and the "connect to port" are equal. * Do this after the remote port number has been fixed in the URL. *************************************************************/ if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) { conn->bits.conn_to_port = FALSE; } #ifndef CURL_DISABLE_PROXY /************************************************************* * If the "connect to" feature is used with an HTTP proxy, * we set the tunnel_proxy bit. *************************************************************/ if((conn->bits.conn_to_host || conn->bits.conn_to_port) && conn->bits.httpproxy) conn->bits.tunnel_proxy = TRUE; #endif /************************************************************* * Setup internals depending on protocol. Needs to be done after * we figured out what/if proxy to use. *************************************************************/ result = setup_connection_internals(data, conn); if(result) goto out; conn->recv[FIRSTSOCKET] = Curl_recv_plain; conn->send[FIRSTSOCKET] = Curl_send_plain; conn->recv[SECONDARYSOCKET] = Curl_recv_plain; conn->send[SECONDARYSOCKET] = Curl_send_plain; conn->bits.tcp_fastopen = data->set.tcp_fastopen; /*********************************************************************** * file: is a special case in that it doesn't need a network connection ***********************************************************************/ #ifndef CURL_DISABLE_FILE if(conn->handler->flags & PROTOPT_NONETWORK) { bool done; /* this is supposed to be the connect function so we better at least check that the file is present here! */ DEBUGASSERT(conn->handler->connect_it); Curl_persistconninfo(data, conn, NULL, -1); result = conn->handler->connect_it(data, &done); /* Setup a "faked" transfer that'll do nothing */ if(!result) { conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */ Curl_attach_connnection(data, conn); result = Curl_conncache_add_conn(data); if(result) goto out; /* * Setup whatever necessary for a resumed transfer */ result = setup_range(data); if(result) { DEBUGASSERT(conn->handler->done); /* we ignore the return code for the protocol-specific DONE */ (void)conn->handler->done(data, result, FALSE); goto out; } Curl_setup_transfer(data, -1, -1, FALSE, -1); } /* since we skip do_init() */ Curl_init_do(data, conn); goto out; } #endif /* Get a cloned copy of the SSL config situation stored in the connection struct. But to get this going nicely, we must first make sure that the strings in the master copy are pointing to the correct strings in the session handle strings array! Keep in mind that the pointers in the master copy are pointing to strings that will be freed as part of the Curl_easy struct, but all cloned copies will be separately allocated. */ data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH]; data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE]; data->set.ssl.primary.issuercert = data->set.str[STRING_SSL_ISSUERCERT]; data->set.ssl.primary.issuercert_blob = data->set.blobs[BLOB_SSL_ISSUERCERT]; data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE]; data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; data->set.ssl.primary.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST]; data->set.ssl.primary.cipher_list13 = data->set.str[STRING_SSL_CIPHER13_LIST]; data->set.ssl.primary.pinned_key = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; data->set.ssl.primary.cert_blob = data->set.blobs[BLOB_CERT]; data->set.ssl.primary.ca_info_blob = data->set.blobs[BLOB_CAINFO]; data->set.ssl.primary.curves = data->set.str[STRING_SSL_EC_CURVES]; #ifndef CURL_DISABLE_PROXY data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY]; data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY]; data->set.proxy_ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE]; data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; data->set.proxy_ssl.primary.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST_PROXY]; data->set.proxy_ssl.primary.cipher_list13 = data->set.str[STRING_SSL_CIPHER13_LIST_PROXY]; data->set.proxy_ssl.primary.pinned_key = data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]; data->set.proxy_ssl.primary.cert_blob = data->set.blobs[BLOB_CERT_PROXY]; data->set.proxy_ssl.primary.ca_info_blob = data->set.blobs[BLOB_CAINFO_PROXY]; data->set.proxy_ssl.primary.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY]; data->set.proxy_ssl.primary.issuercert_blob = data->set.blobs[BLOB_SSL_ISSUERCERT_PROXY]; data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY]; data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY]; data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY]; data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY]; data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY]; data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY]; data->set.proxy_ssl.key_blob = data->set.blobs[BLOB_KEY_PROXY]; #endif data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE]; data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE]; data->set.ssl.key = data->set.str[STRING_KEY]; data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE]; data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD]; data->set.ssl.primary.clientcert = data->set.str[STRING_CERT]; #ifdef USE_TLS_SRP data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME]; data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD]; #ifndef CURL_DISABLE_PROXY data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY]; data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY]; #endif #endif data->set.ssl.key_blob = data->set.blobs[BLOB_KEY]; if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary, &conn->ssl_config)) { result = CURLE_OUT_OF_MEMORY; goto out; } #ifndef CURL_DISABLE_PROXY if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary, &conn->proxy_ssl_config)) { result = CURLE_OUT_OF_MEMORY; goto out; } #endif prune_dead_connections(data); /************************************************************* * Check the current list of connections to see if we can * re-use an already existing one or if we have to create a * new one. *************************************************************/ DEBUGASSERT(conn->user); DEBUGASSERT(conn->passwd); /* reuse_fresh is TRUE if we are told to use a new connection by force, but we only acknowledge this option if this is not a re-used connection already (which happens due to follow-location or during a HTTP authentication phase). CONNECT_ONLY transfers also refuse reuse. */ if((data->set.reuse_fresh && !data->state.this_is_a_follow) || data->set.connect_only) reuse = FALSE; else reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe); if(reuse) { /* * We already have a connection for this, we got the former connection in * the conn_temp variable and thus we need to cleanup the one we just * allocated before we can move along and use the previously existing one. */ reuse_conn(data, conn, conn_temp); #ifdef USE_SSL free(conn->ssl_extra); #endif free(conn); /* we don't need this anymore */ conn = conn_temp; *in_connect = conn; #ifndef CURL_DISABLE_PROXY infof(data, "Re-using existing connection! (#%ld) with %s %s", conn->connection_id, conn->bits.proxy?"proxy":"host", conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname : conn->http_proxy.host.name ? conn->http_proxy.host.dispname : conn->host.dispname); #else infof(data, "Re-using existing connection! (#%ld) with host %s", conn->connection_id, conn->host.dispname); #endif } else { /* We have decided that we want a new connection. However, we may not be able to do that if we have reached the limit of how many connections we are allowed to open. */ if(conn->handler->flags & PROTOPT_ALPN_NPN) { /* The protocol wants it, so set the bits if enabled in the easy handle (default) */ if(data->set.ssl_enable_alpn) conn->bits.tls_enable_alpn = TRUE; if(data->set.ssl_enable_npn) conn->bits.tls_enable_npn = TRUE; } if(waitpipe) /* There is a connection that *might* become usable for multiplexing "soon", and we wait for that */ connections_available = FALSE; else { /* this gets a lock on the conncache */ const char *bundlehost; struct connectbundle *bundle = Curl_conncache_find_bundle(data, conn, data->state.conn_cache, &bundlehost); if(max_host_connections > 0 && bundle && (bundle->num_connections >= max_host_connections)) { struct connectdata *conn_candidate; /* The bundle is full. Extract the oldest connection. */ conn_candidate = Curl_conncache_extract_bundle(data, bundle); CONNCACHE_UNLOCK(data); if(conn_candidate) (void)Curl_disconnect(data, conn_candidate, FALSE); else { infof(data, "No more connections allowed to host %s: %zu", bundlehost, max_host_connections); connections_available = FALSE; } } else CONNCACHE_UNLOCK(data); } if(connections_available && (max_total_connections > 0) && (Curl_conncache_size(data) >= max_total_connections)) { struct connectdata *conn_candidate; /* The cache is full. Let's see if we can kill a connection. */ conn_candidate = Curl_conncache_extract_oldest(data); if(conn_candidate) (void)Curl_disconnect(data, conn_candidate, FALSE); else { infof(data, "No connections available in cache"); connections_available = FALSE; } } if(!connections_available) { infof(data, "No connections available."); conn_free(conn); *in_connect = NULL; result = CURLE_NO_CONNECTION_AVAILABLE; goto out; } else { /* * This is a brand new connection, so let's store it in the connection * cache of ours! */ Curl_attach_connnection(data, conn); result = Curl_conncache_add_conn(data); if(result) goto out; } #if defined(USE_NTLM) /* If NTLM is requested in a part of this connection, make sure we don't assume the state is fine as this is a fresh connection and NTLM is connection based. */ if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && data->state.authhost.done) { infof(data, "NTLM picked AND auth done set, clear picked!"); data->state.authhost.picked = CURLAUTH_NONE; data->state.authhost.done = FALSE; } if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && data->state.authproxy.done) { infof(data, "NTLM-proxy picked AND auth done set, clear picked!"); data->state.authproxy.picked = CURLAUTH_NONE; data->state.authproxy.done = FALSE; } #endif } /* Setup and init stuff before DO starts, in preparing for the transfer. */ Curl_init_do(data, conn); /* * Setup whatever necessary for a resumed transfer */ result = setup_range(data); if(result) goto out; /* Continue connectdata initialization here. */ /* * Inherit the proper values from the urldata struct AFTER we have arranged * the persistent connection stuff */ conn->seek_func = data->set.seek_func; conn->seek_client = data->set.seek_client; /************************************************************* * Resolve the address of the server or proxy *************************************************************/ result = resolve_server(data, conn, async); /* Strip trailing dots. resolve_server copied the name. */ strip_trailing_dot(&conn->host); #ifndef CURL_DISABLE_PROXY if(conn->bits.httpproxy) strip_trailing_dot(&conn->http_proxy.host); if(conn->bits.socksproxy) strip_trailing_dot(&conn->socks_proxy.host); #endif if(conn->bits.conn_to_host) strip_trailing_dot(&conn->conn_to_host); out: return result; } /* Curl_setup_conn() is called after the name resolve initiated in * create_conn() is all done. * * Curl_setup_conn() also handles reused connections */ CURLcode Curl_setup_conn(struct Curl_easy *data, bool *protocol_done) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; Curl_pgrsTime(data, TIMER_NAMELOOKUP); if(conn->handler->flags & PROTOPT_NONETWORK) { /* nothing to setup when not using a network */ *protocol_done = TRUE; return result; } *protocol_done = FALSE; /* default to not done */ #ifndef CURL_DISABLE_PROXY /* set proxy_connect_closed to false unconditionally already here since it is used strictly to provide extra information to a parent function in the case of proxy CONNECT failures and we must make sure we don't have it lingering set from a previous invoke */ conn->bits.proxy_connect_closed = FALSE; #endif #ifdef CURL_DO_LINEEND_CONV data->state.crlf_conversions = 0; /* reset CRLF conversion counter */ #endif /* CURL_DO_LINEEND_CONV */ /* set start time here for timeout purposes in the connect procedure, it is later set again for the progress meter purpose */ conn->now = Curl_now(); if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) { conn->bits.tcpconnect[FIRSTSOCKET] = FALSE; result = Curl_connecthost(data, conn, conn->dns_entry); if(result) return result; } else { Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */ if(conn->ssl[FIRSTSOCKET].use || (conn->handler->protocol & PROTO_FAMILY_SSH)) Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */ conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; *protocol_done = TRUE; Curl_updateconninfo(data, conn, conn->sock[FIRSTSOCKET]); Curl_verboseconnect(data, conn); } conn->now = Curl_now(); /* time this *after* the connect is done, we set this here perhaps a second time */ return result; } CURLcode Curl_connect(struct Curl_easy *data, bool *asyncp, bool *protocol_done) { CURLcode result; struct connectdata *conn; *asyncp = FALSE; /* assume synchronous resolves by default */ /* init the single-transfer specific data */ Curl_free_request_state(data); memset(&data->req, 0, sizeof(struct SingleRequest)); data->req.size = data->req.maxdownload = -1; /* call the stuff that needs to be called */ result = create_conn(data, &conn, asyncp); if(!result) { if(CONN_INUSE(conn) > 1) /* multiplexed */ *protocol_done = TRUE; else if(!*asyncp) { /* DNS resolution is done: that's either because this is a reused connection, in which case DNS was unnecessary, or because DNS really did finish already (synch resolver/fast async resolve) */ result = Curl_setup_conn(data, protocol_done); } } if(result == CURLE_NO_CONNECTION_AVAILABLE) { return result; } else if(result && conn) { /* We're not allowed to return failure with memory left allocated in the connectdata struct, free those here */ Curl_detach_connnection(data); Curl_conncache_remove_conn(data, conn, TRUE); Curl_disconnect(data, conn, TRUE); } return result; } /* * Curl_init_do() inits the readwrite session. This is inited each time (in * the DO function before the protocol-specific DO functions are invoked) for * a transfer, sometimes multiple times on the same Curl_easy. Make sure * nothing in here depends on stuff that are setup dynamically for the * transfer. * * Allow this function to get called with 'conn' set to NULL. */ CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn) { struct SingleRequest *k = &data->req; /* if this is a pushed stream, we need this: */ CURLcode result = Curl_preconnect(data); if(result) return result; if(conn) { conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */ /* if the protocol used doesn't support wildcards, switch it off */ if(data->state.wildcardmatch && !(conn->handler->flags & PROTOPT_WILDCARD)) data->state.wildcardmatch = FALSE; } data->state.done = FALSE; /* *_done() is not called yet */ data->state.expect100header = FALSE; if(data->set.opt_no_body) /* in HTTP lingo, no body means using the HEAD request... */ data->state.httpreq = HTTPREQ_HEAD; k->start = Curl_now(); /* start time */ k->now = k->start; /* current time is now */ k->header = TRUE; /* assume header */ k->bytecount = 0; k->ignorebody = FALSE; Curl_speedinit(data); Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); return CURLE_OK; }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/transfer.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "strtoofft.h" #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #elif defined(HAVE_UNISTD_H) #include <unistd.h> #endif #ifndef HAVE_SOCKET #error "We can't compile without socket() support!" #endif #include "urldata.h" #include <curl/curl.h> #include "netrc.h" #include "content_encoding.h" #include "hostip.h" #include "transfer.h" #include "sendf.h" #include "speedcheck.h" #include "progress.h" #include "http.h" #include "url.h" #include "getinfo.h" #include "vtls/vtls.h" #include "select.h" #include "multiif.h" #include "connect.h" #include "non-ascii.h" #include "http2.h" #include "mime.h" #include "strcase.h" #include "urlapi-int.h" #include "hsts.h" #include "setopt.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \ !defined(CURL_DISABLE_IMAP) /* * checkheaders() checks the linked list of custom headers for a * particular header (prefix). Provide the prefix without colon! * * Returns a pointer to the first matching header or NULL if none matched. */ char *Curl_checkheaders(const struct Curl_easy *data, const char *thisheader) { struct curl_slist *head; size_t thislen = strlen(thisheader); DEBUGASSERT(thislen); DEBUGASSERT(thisheader[thislen-1] != ':'); for(head = data->set.headers; head; head = head->next) { if(strncasecompare(head->data, thisheader, thislen) && Curl_headersep(head->data[thislen]) ) return head->data; } return NULL; } #endif CURLcode Curl_get_upload_buffer(struct Curl_easy *data) { if(!data->state.ulbuf) { data->state.ulbuf = malloc(data->set.upload_buffer_size); if(!data->state.ulbuf) return CURLE_OUT_OF_MEMORY; } return CURLE_OK; } #ifndef CURL_DISABLE_HTTP /* * This function will be called to loop through the trailers buffer * until no more data is available for sending. */ static size_t trailers_read(char *buffer, size_t size, size_t nitems, void *raw) { struct Curl_easy *data = (struct Curl_easy *)raw; struct dynbuf *trailers_buf = &data->state.trailers_buf; size_t bytes_left = Curl_dyn_len(trailers_buf) - data->state.trailers_bytes_sent; size_t to_copy = (size*nitems < bytes_left) ? size*nitems : bytes_left; if(to_copy) { memcpy(buffer, Curl_dyn_ptr(trailers_buf) + data->state.trailers_bytes_sent, to_copy); data->state.trailers_bytes_sent += to_copy; } return to_copy; } static size_t trailers_left(void *raw) { struct Curl_easy *data = (struct Curl_easy *)raw; struct dynbuf *trailers_buf = &data->state.trailers_buf; return Curl_dyn_len(trailers_buf) - data->state.trailers_bytes_sent; } #endif /* * This function will call the read callback to fill our buffer with data * to upload. */ CURLcode Curl_fillreadbuffer(struct Curl_easy *data, size_t bytes, size_t *nreadp) { size_t buffersize = bytes; size_t nread; curl_read_callback readfunc = NULL; void *extra_data = NULL; #ifdef CURL_DOES_CONVERSIONS bool sending_http_headers = FALSE; struct connectdata *conn = data->conn; if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) { const struct HTTP *http = data->req.p.http; if(http->sending == HTTPSEND_REQUEST) /* We're sending the HTTP request headers, not the data. Remember that so we don't re-translate them into garbage. */ sending_http_headers = TRUE; } #endif #ifndef CURL_DISABLE_HTTP if(data->state.trailers_state == TRAILERS_INITIALIZED) { struct curl_slist *trailers = NULL; CURLcode result; int trailers_ret_code; /* at this point we already verified that the callback exists so we compile and store the trailers buffer, then proceed */ infof(data, "Moving trailers state machine from initialized to sending."); data->state.trailers_state = TRAILERS_SENDING; Curl_dyn_init(&data->state.trailers_buf, DYN_TRAILERS); data->state.trailers_bytes_sent = 0; Curl_set_in_callback(data, true); trailers_ret_code = data->set.trailer_callback(&trailers, data->set.trailer_data); Curl_set_in_callback(data, false); if(trailers_ret_code == CURL_TRAILERFUNC_OK) { result = Curl_http_compile_trailers(trailers, &data->state.trailers_buf, data); } else { failf(data, "operation aborted by trailing headers callback"); *nreadp = 0; result = CURLE_ABORTED_BY_CALLBACK; } if(result) { Curl_dyn_free(&data->state.trailers_buf); curl_slist_free_all(trailers); return result; } infof(data, "Successfully compiled trailers."); curl_slist_free_all(trailers); } #endif /* if we are transmitting trailing data, we don't need to write a chunk size so we skip this */ if(data->req.upload_chunky && data->state.trailers_state == TRAILERS_NONE) { /* if chunked Transfer-Encoding */ buffersize -= (8 + 2 + 2); /* 32bit hex + CRLF + CRLF */ data->req.upload_fromhere += (8 + 2); /* 32bit hex + CRLF */ } #ifndef CURL_DISABLE_HTTP if(data->state.trailers_state == TRAILERS_SENDING) { /* if we're here then that means that we already sent the last empty chunk but we didn't send a final CR LF, so we sent 0 CR LF. We then start pulling trailing data until we have no more at which point we simply return to the previous point in the state machine as if nothing happened. */ readfunc = trailers_read; extra_data = (void *)data; } else #endif { readfunc = data->state.fread_func; extra_data = data->state.in; } Curl_set_in_callback(data, true); nread = readfunc(data->req.upload_fromhere, 1, buffersize, extra_data); Curl_set_in_callback(data, false); if(nread == CURL_READFUNC_ABORT) { failf(data, "operation aborted by callback"); *nreadp = 0; return CURLE_ABORTED_BY_CALLBACK; } if(nread == CURL_READFUNC_PAUSE) { struct SingleRequest *k = &data->req; if(data->conn->handler->flags & PROTOPT_NONETWORK) { /* protocols that work without network cannot be paused. This is actually only FILE:// just now, and it can't pause since the transfer isn't done using the "normal" procedure. */ failf(data, "Read callback asked for PAUSE when not supported!"); return CURLE_READ_ERROR; } /* CURL_READFUNC_PAUSE pauses read callbacks that feed socket writes */ k->keepon |= KEEP_SEND_PAUSE; /* mark socket send as paused */ if(data->req.upload_chunky) { /* Back out the preallocation done above */ data->req.upload_fromhere -= (8 + 2); } *nreadp = 0; return CURLE_OK; /* nothing was read */ } else if(nread > buffersize) { /* the read function returned a too large value */ *nreadp = 0; failf(data, "read function returned funny value"); return CURLE_READ_ERROR; } if(!data->req.forbidchunk && data->req.upload_chunky) { /* if chunked Transfer-Encoding * build chunk: * * <HEX SIZE> CRLF * <DATA> CRLF */ /* On non-ASCII platforms the <DATA> may or may not be translated based on state.prefer_ascii while the protocol portion must always be translated to the network encoding. To further complicate matters, line end conversion might be done later on, so we need to prevent CRLFs from becoming CRCRLFs if that's the case. To do this we use bare LFs here, knowing they'll become CRLFs later on. */ bool added_crlf = FALSE; int hexlen = 0; const char *endofline_native; const char *endofline_network; if( #ifdef CURL_DO_LINEEND_CONV (data->state.prefer_ascii) || #endif (data->set.crlf)) { /* \n will become \r\n later on */ endofline_native = "\n"; endofline_network = "\x0a"; } else { endofline_native = "\r\n"; endofline_network = "\x0d\x0a"; } /* if we're not handling trailing data, proceed as usual */ if(data->state.trailers_state != TRAILERS_SENDING) { char hexbuffer[11] = ""; hexlen = msnprintf(hexbuffer, sizeof(hexbuffer), "%zx%s", nread, endofline_native); /* move buffer pointer */ data->req.upload_fromhere -= hexlen; nread += hexlen; /* copy the prefix to the buffer, leaving out the NUL */ memcpy(data->req.upload_fromhere, hexbuffer, hexlen); /* always append ASCII CRLF to the data unless we have a valid trailer callback */ #ifndef CURL_DISABLE_HTTP if((nread-hexlen) == 0 && data->set.trailer_callback != NULL && data->state.trailers_state == TRAILERS_NONE) { data->state.trailers_state = TRAILERS_INITIALIZED; } else #endif { memcpy(data->req.upload_fromhere + nread, endofline_network, strlen(endofline_network)); added_crlf = TRUE; } } #ifdef CURL_DOES_CONVERSIONS { CURLcode result; size_t length; if(data->state.prefer_ascii) /* translate the protocol and data */ length = nread; else /* just translate the protocol portion */ length = hexlen; if(length) { result = Curl_convert_to_network(data, data->req.upload_fromhere, length); /* Curl_convert_to_network calls failf if unsuccessful */ if(result) return result; } } #endif /* CURL_DOES_CONVERSIONS */ #ifndef CURL_DISABLE_HTTP if(data->state.trailers_state == TRAILERS_SENDING && !trailers_left(data)) { Curl_dyn_free(&data->state.trailers_buf); data->state.trailers_state = TRAILERS_DONE; data->set.trailer_data = NULL; data->set.trailer_callback = NULL; /* mark the transfer as done */ data->req.upload_done = TRUE; infof(data, "Signaling end of chunked upload after trailers."); } else #endif if((nread - hexlen) == 0 && data->state.trailers_state != TRAILERS_INITIALIZED) { /* mark this as done once this chunk is transferred */ data->req.upload_done = TRUE; infof(data, "Signaling end of chunked upload via terminating chunk."); } if(added_crlf) nread += strlen(endofline_network); /* for the added end of line */ } #ifdef CURL_DOES_CONVERSIONS else if((data->state.prefer_ascii) && (!sending_http_headers)) { CURLcode result; result = Curl_convert_to_network(data, data->req.upload_fromhere, nread); /* Curl_convert_to_network calls failf if unsuccessful */ if(result) return result; } #endif /* CURL_DOES_CONVERSIONS */ *nreadp = nread; return CURLE_OK; } /* * Curl_readrewind() rewinds the read stream. This is typically used for HTTP * POST/PUT with multi-pass authentication when a sending was denied and a * resend is necessary. */ CURLcode Curl_readrewind(struct Curl_easy *data) { struct connectdata *conn = data->conn; curl_mimepart *mimepart = &data->set.mimepost; conn->bits.rewindaftersend = FALSE; /* we rewind now */ /* explicitly switch off sending data on this connection now since we are about to restart a new transfer and thus we want to avoid inadvertently sending more data on the existing connection until the next transfer starts */ data->req.keepon &= ~KEEP_SEND; /* We have sent away data. If not using CURLOPT_POSTFIELDS or CURLOPT_HTTPPOST, call app to rewind */ if(conn->handler->protocol & PROTO_FAMILY_HTTP) { struct HTTP *http = data->req.p.http; if(http->sendit) mimepart = http->sendit; } if(data->set.postfields) ; /* do nothing */ else if(data->state.httpreq == HTTPREQ_POST_MIME || data->state.httpreq == HTTPREQ_POST_FORM) { CURLcode result = Curl_mime_rewind(mimepart); if(result) { failf(data, "Cannot rewind mime/post data"); return result; } } else { if(data->set.seek_func) { int err; Curl_set_in_callback(data, true); err = (data->set.seek_func)(data->set.seek_client, 0, SEEK_SET); Curl_set_in_callback(data, false); if(err) { failf(data, "seek callback returned error %d", (int)err); return CURLE_SEND_FAIL_REWIND; } } else if(data->set.ioctl_func) { curlioerr err; Curl_set_in_callback(data, true); err = (data->set.ioctl_func)(data, CURLIOCMD_RESTARTREAD, data->set.ioctl_client); Curl_set_in_callback(data, false); infof(data, "the ioctl callback returned %d", (int)err); if(err) { failf(data, "ioctl callback returned error %d", (int)err); return CURLE_SEND_FAIL_REWIND; } } else { /* If no CURLOPT_READFUNCTION is used, we know that we operate on a given FILE * stream and we can actually attempt to rewind that ourselves with fseek() */ if(data->state.fread_func == (curl_read_callback)fread) { if(-1 != fseek(data->state.in, 0, SEEK_SET)) /* successful rewind */ return CURLE_OK; } /* no callback set or failure above, makes us fail at once */ failf(data, "necessary data rewind wasn't possible"); return CURLE_SEND_FAIL_REWIND; } } return CURLE_OK; } static int data_pending(const struct Curl_easy *data) { struct connectdata *conn = data->conn; #ifdef ENABLE_QUIC if(conn->transport == TRNSPRT_QUIC) return Curl_quic_data_pending(data); #endif if(conn->handler->protocol&PROTO_FAMILY_FTP) return Curl_ssl_data_pending(conn, SECONDARYSOCKET); /* in the case of libssh2, we can never be really sure that we have emptied its internal buffers so we MUST always try until we get EAGAIN back */ return conn->handler->protocol&(CURLPROTO_SCP|CURLPROTO_SFTP) || #if defined(USE_NGHTTP2) /* For HTTP/2, we may read up everything including response body with header fields in Curl_http_readwrite_headers. If no content-length is provided, curl waits for the connection close, which we emulate it using conn->proto.httpc.closed = TRUE. The thing is if we read everything, then http2_recv won't be called and we cannot signal the HTTP/2 stream has closed. As a workaround, we return nonzero here to call http2_recv. */ ((conn->handler->protocol&PROTO_FAMILY_HTTP) && conn->httpversion >= 20) || #endif Curl_ssl_data_pending(conn, FIRSTSOCKET); } /* * Check to see if CURLOPT_TIMECONDITION was met by comparing the time of the * remote document with the time provided by CURLOPT_TIMEVAL */ bool Curl_meets_timecondition(struct Curl_easy *data, time_t timeofdoc) { if((timeofdoc == 0) || (data->set.timevalue == 0)) return TRUE; switch(data->set.timecondition) { case CURL_TIMECOND_IFMODSINCE: default: if(timeofdoc <= data->set.timevalue) { infof(data, "The requested document is not new enough"); data->info.timecond = TRUE; return FALSE; } break; case CURL_TIMECOND_IFUNMODSINCE: if(timeofdoc >= data->set.timevalue) { infof(data, "The requested document is not old enough"); data->info.timecond = TRUE; return FALSE; } break; } return TRUE; } /* * Go ahead and do a read if we have a readable socket or if * the stream was rewound (in which case we have data in a * buffer) * * return '*comeback' TRUE if we didn't properly drain the socket so this * function should get called again without select() or similar in between! */ static CURLcode readwrite_data(struct Curl_easy *data, struct connectdata *conn, struct SingleRequest *k, int *didwhat, bool *done, bool *comeback) { CURLcode result = CURLE_OK; ssize_t nread; /* number of bytes read */ size_t excess = 0; /* excess bytes read */ bool readmore = FALSE; /* used by RTP to signal for more data */ int maxloops = 100; char *buf = data->state.buffer; DEBUGASSERT(buf); *done = FALSE; *comeback = FALSE; /* This is where we loop until we have read everything there is to read or we get a CURLE_AGAIN */ do { bool is_empty_data = FALSE; size_t buffersize = data->set.buffer_size; size_t bytestoread = buffersize; #ifdef USE_NGHTTP2 bool is_http2 = ((conn->handler->protocol & PROTO_FAMILY_HTTP) && (conn->httpversion == 20)); #endif if( #ifdef USE_NGHTTP2 /* For HTTP/2, read data without caring about the content length. This is safe because body in HTTP/2 is always segmented thanks to its framing layer. Meanwhile, we have to call Curl_read to ensure that http2_handle_stream_close is called when we read all incoming bytes for a particular stream. */ !is_http2 && #endif k->size != -1 && !k->header) { /* make sure we don't read too much */ curl_off_t totalleft = k->size - k->bytecount; if(totalleft < (curl_off_t)bytestoread) bytestoread = (size_t)totalleft; } if(bytestoread) { /* receive data from the network! */ result = Curl_read(data, conn->sockfd, buf, bytestoread, &nread); /* read would've blocked */ if(CURLE_AGAIN == result) break; /* get out of loop */ if(result>0) return result; } else { /* read nothing but since we wanted nothing we consider this an OK situation to proceed from */ DEBUGF(infof(data, "readwrite_data: we're done!")); nread = 0; } if(!k->bytecount) { Curl_pgrsTime(data, TIMER_STARTTRANSFER); if(k->exp100 > EXP100_SEND_DATA) /* set time stamp to compare with when waiting for the 100 */ k->start100 = Curl_now(); } *didwhat |= KEEP_RECV; /* indicates data of zero size, i.e. empty file */ is_empty_data = ((nread == 0) && (k->bodywrites == 0)) ? TRUE : FALSE; if(0 < nread || is_empty_data) { buf[nread] = 0; } else { /* if we receive 0 or less here, either the http2 stream is closed or the server closed the connection and we bail out from this! */ #ifdef USE_NGHTTP2 if(is_http2 && !nread) DEBUGF(infof(data, "nread == 0, stream closed, bailing")); else #endif DEBUGF(infof(data, "nread <= 0, server closed connection, bailing")); k->keepon &= ~KEEP_RECV; break; } /* Default buffer to use when we write the buffer, it may be changed in the flow below before the actual storing is done. */ k->str = buf; if(conn->handler->readwrite) { result = conn->handler->readwrite(data, conn, &nread, &readmore); if(result) return result; if(readmore) break; } #ifndef CURL_DISABLE_HTTP /* Since this is a two-state thing, we check if we are parsing headers at the moment or not. */ if(k->header) { /* we are in parse-the-header-mode */ bool stop_reading = FALSE; result = Curl_http_readwrite_headers(data, conn, &nread, &stop_reading); if(result) return result; if(conn->handler->readwrite && (k->maxdownload <= 0 && nread > 0)) { result = conn->handler->readwrite(data, conn, &nread, &readmore); if(result) return result; if(readmore) break; } if(stop_reading) { /* We've stopped dealing with input, get out of the do-while loop */ if(nread > 0) { infof(data, "Excess found:" " excess = %zd" " url = %s (zero-length body)", nread, data->state.up.path); } break; } } #endif /* CURL_DISABLE_HTTP */ /* This is not an 'else if' since it may be a rest from the header parsing, where the beginning of the buffer is headers and the end is non-headers. */ if(!k->header && (nread > 0 || is_empty_data)) { if(data->set.opt_no_body) { /* data arrives although we want none, bail out */ streamclose(conn, "ignoring body"); *done = TRUE; return CURLE_WEIRD_SERVER_REPLY; } #ifndef CURL_DISABLE_HTTP if(0 == k->bodywrites && !is_empty_data) { /* These checks are only made the first time we are about to write a piece of the body */ if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) { /* HTTP-only checks */ result = Curl_http_firstwrite(data, conn, done); if(result || *done) return result; } } /* this is the first time we write a body part */ #endif /* CURL_DISABLE_HTTP */ k->bodywrites++; /* pass data to the debug function before it gets "dechunked" */ if(data->set.verbose) { if(k->badheader) { Curl_debug(data, CURLINFO_DATA_IN, Curl_dyn_ptr(&data->state.headerb), Curl_dyn_len(&data->state.headerb)); if(k->badheader == HEADER_PARTHEADER) Curl_debug(data, CURLINFO_DATA_IN, k->str, (size_t)nread); } else Curl_debug(data, CURLINFO_DATA_IN, k->str, (size_t)nread); } #ifndef CURL_DISABLE_HTTP if(k->chunk) { /* * Here comes a chunked transfer flying and we need to decode this * properly. While the name says read, this function both reads * and writes away the data. The returned 'nread' holds the number * of actual data it wrote to the client. */ CURLcode extra; CHUNKcode res = Curl_httpchunk_read(data, k->str, nread, &nread, &extra); if(CHUNKE_OK < res) { if(CHUNKE_PASSTHRU_ERROR == res) { failf(data, "Failed reading the chunked-encoded stream"); return extra; } failf(data, "%s in chunked-encoding", Curl_chunked_strerror(res)); return CURLE_RECV_ERROR; } if(CHUNKE_STOP == res) { /* we're done reading chunks! */ k->keepon &= ~KEEP_RECV; /* read no more */ /* N number of bytes at the end of the str buffer that weren't written to the client. */ if(conn->chunk.datasize) { infof(data, "Leftovers after chunking: % " CURL_FORMAT_CURL_OFF_T "u bytes", conn->chunk.datasize); } } /* If it returned OK, we just keep going */ } #endif /* CURL_DISABLE_HTTP */ /* Account for body content stored in the header buffer */ if((k->badheader == HEADER_PARTHEADER) && !k->ignorebody) { size_t headlen = Curl_dyn_len(&data->state.headerb); DEBUGF(infof(data, "Increasing bytecount by %zu", headlen)); k->bytecount += headlen; } if((-1 != k->maxdownload) && (k->bytecount + nread >= k->maxdownload)) { excess = (size_t)(k->bytecount + nread - k->maxdownload); if(excess > 0 && !k->ignorebody) { infof(data, "Excess found in a read:" " excess = %zu" ", size = %" CURL_FORMAT_CURL_OFF_T ", maxdownload = %" CURL_FORMAT_CURL_OFF_T ", bytecount = %" CURL_FORMAT_CURL_OFF_T, excess, k->size, k->maxdownload, k->bytecount); connclose(conn, "excess found in a read"); } nread = (ssize_t) (k->maxdownload - k->bytecount); if(nread < 0) /* this should be unusual */ nread = 0; k->keepon &= ~KEEP_RECV; /* we're done reading */ } k->bytecount += nread; Curl_pgrsSetDownloadCounter(data, k->bytecount); if(!k->chunk && (nread || k->badheader || is_empty_data)) { /* If this is chunky transfer, it was already written */ if(k->badheader && !k->ignorebody) { /* we parsed a piece of data wrongly assuming it was a header and now we output it as body instead */ size_t headlen = Curl_dyn_len(&data->state.headerb); /* Don't let excess data pollute body writes */ if(k->maxdownload == -1 || (curl_off_t)headlen <= k->maxdownload) result = Curl_client_write(data, CLIENTWRITE_BODY, Curl_dyn_ptr(&data->state.headerb), headlen); else result = Curl_client_write(data, CLIENTWRITE_BODY, Curl_dyn_ptr(&data->state.headerb), (size_t)k->maxdownload); if(result) return result; } if(k->badheader < HEADER_ALLBAD) { /* This switch handles various content encodings. If there's an error here, be sure to check over the almost identical code in http_chunks.c. Make sure that ALL_CONTENT_ENCODINGS contains all the encodings handled here. */ if(data->set.http_ce_skip || !k->writer_stack) { if(!k->ignorebody && nread) { #ifndef CURL_DISABLE_POP3 if(conn->handler->protocol & PROTO_FAMILY_POP3) result = Curl_pop3_write(data, k->str, nread); else #endif /* CURL_DISABLE_POP3 */ result = Curl_client_write(data, CLIENTWRITE_BODY, k->str, nread); } } else if(!k->ignorebody && nread) result = Curl_unencode_write(data, k->writer_stack, k->str, nread); } k->badheader = HEADER_NORMAL; /* taken care of now */ if(result) return result; } } /* if(!header and data to read) */ if(conn->handler->readwrite && excess) { /* Parse the excess data */ k->str += nread; if(&k->str[excess] > &buf[data->set.buffer_size]) { /* the excess amount was too excessive(!), make sure it doesn't read out of buffer */ excess = &buf[data->set.buffer_size] - k->str; } nread = (ssize_t)excess; result = conn->handler->readwrite(data, conn, &nread, &readmore); if(result) return result; if(readmore) k->keepon |= KEEP_RECV; /* we're not done reading */ break; } if(is_empty_data) { /* if we received nothing, the server closed the connection and we are done */ k->keepon &= ~KEEP_RECV; } if(k->keepon & KEEP_RECV_PAUSE) { /* this is a paused transfer */ break; } } while(data_pending(data) && maxloops--); if(maxloops <= 0) { /* we mark it as read-again-please */ conn->cselect_bits = CURL_CSELECT_IN; *comeback = TRUE; } if(((k->keepon & (KEEP_RECV|KEEP_SEND)) == KEEP_SEND) && conn->bits.close) { /* When we've read the entire thing and the close bit is set, the server may now close the connection. If there's now any kind of sending going on from our side, we need to stop that immediately. */ infof(data, "we are done reading and this is set to close, stop send"); k->keepon &= ~KEEP_SEND; /* no writing anymore either */ } return CURLE_OK; } CURLcode Curl_done_sending(struct Curl_easy *data, struct SingleRequest *k) { struct connectdata *conn = data->conn; k->keepon &= ~KEEP_SEND; /* we're done writing */ /* These functions should be moved into the handler struct! */ Curl_http2_done_sending(data, conn); Curl_quic_done_sending(data); if(conn->bits.rewindaftersend) { CURLcode result = Curl_readrewind(data); if(result) return result; } return CURLE_OK; } #if defined(WIN32) && defined(USE_WINSOCK) #ifndef SIO_IDEAL_SEND_BACKLOG_QUERY #define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747B #endif static void win_update_buffer_size(curl_socket_t sockfd) { int result; ULONG ideal; DWORD ideallen; result = WSAIoctl(sockfd, SIO_IDEAL_SEND_BACKLOG_QUERY, 0, 0, &ideal, sizeof(ideal), &ideallen, 0, 0); if(result == 0) { setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&ideal, sizeof(ideal)); } } #else #define win_update_buffer_size(x) #endif /* * Send data to upload to the server, when the socket is writable. */ static CURLcode readwrite_upload(struct Curl_easy *data, struct connectdata *conn, int *didwhat) { ssize_t i, si; ssize_t bytes_written; CURLcode result; ssize_t nread; /* number of bytes read */ bool sending_http_headers = FALSE; struct SingleRequest *k = &data->req; if((k->bytecount == 0) && (k->writebytecount == 0)) Curl_pgrsTime(data, TIMER_STARTTRANSFER); *didwhat |= KEEP_SEND; do { curl_off_t nbody; /* only read more data if there's no upload data already present in the upload buffer */ if(0 == k->upload_present) { result = Curl_get_upload_buffer(data); if(result) return result; /* init the "upload from here" pointer */ k->upload_fromhere = data->state.ulbuf; if(!k->upload_done) { /* HTTP pollution, this should be written nicer to become more protocol agnostic. */ size_t fillcount; struct HTTP *http = k->p.http; if((k->exp100 == EXP100_SENDING_REQUEST) && (http->sending == HTTPSEND_BODY)) { /* If this call is to send body data, we must take some action: We have sent off the full HTTP 1.1 request, and we shall now go into the Expect: 100 state and await such a header */ k->exp100 = EXP100_AWAITING_CONTINUE; /* wait for the header */ k->keepon &= ~KEEP_SEND; /* disable writing */ k->start100 = Curl_now(); /* timeout count starts now */ *didwhat &= ~KEEP_SEND; /* we didn't write anything actually */ /* set a timeout for the multi interface */ Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT); break; } if(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP)) { if(http->sending == HTTPSEND_REQUEST) /* We're sending the HTTP request headers, not the data. Remember that so we don't change the line endings. */ sending_http_headers = TRUE; else sending_http_headers = FALSE; } result = Curl_fillreadbuffer(data, data->set.upload_buffer_size, &fillcount); if(result) return result; nread = fillcount; } else nread = 0; /* we're done uploading/reading */ if(!nread && (k->keepon & KEEP_SEND_PAUSE)) { /* this is a paused transfer */ break; } if(nread <= 0) { result = Curl_done_sending(data, k); if(result) return result; break; } /* store number of bytes available for upload */ k->upload_present = nread; /* convert LF to CRLF if so asked */ if((!sending_http_headers) && ( #ifdef CURL_DO_LINEEND_CONV /* always convert if we're FTPing in ASCII mode */ (data->state.prefer_ascii) || #endif (data->set.crlf))) { /* Do we need to allocate a scratch buffer? */ if(!data->state.scratch) { data->state.scratch = malloc(2 * data->set.upload_buffer_size); if(!data->state.scratch) { failf(data, "Failed to alloc scratch buffer!"); return CURLE_OUT_OF_MEMORY; } } /* * ASCII/EBCDIC Note: This is presumably a text (not binary) * transfer so the data should already be in ASCII. * That means the hex values for ASCII CR (0x0d) & LF (0x0a) * must be used instead of the escape sequences \r & \n. */ for(i = 0, si = 0; i < nread; i++, si++) { if(k->upload_fromhere[i] == 0x0a) { data->state.scratch[si++] = 0x0d; data->state.scratch[si] = 0x0a; if(!data->set.crlf) { /* we're here only because FTP is in ASCII mode... bump infilesize for the LF we just added */ if(data->state.infilesize != -1) data->state.infilesize++; } } else data->state.scratch[si] = k->upload_fromhere[i]; } if(si != nread) { /* only perform the special operation if we really did replace anything */ nread = si; /* upload from the new (replaced) buffer instead */ k->upload_fromhere = data->state.scratch; /* set the new amount too */ k->upload_present = nread; } } #ifndef CURL_DISABLE_SMTP if(conn->handler->protocol & PROTO_FAMILY_SMTP) { result = Curl_smtp_escape_eob(data, nread); if(result) return result; } #endif /* CURL_DISABLE_SMTP */ } /* if 0 == k->upload_present */ else { /* We have a partial buffer left from a previous "round". Use that instead of reading more data */ } /* write to socket (send away data) */ result = Curl_write(data, conn->writesockfd, /* socket to send to */ k->upload_fromhere, /* buffer pointer */ k->upload_present, /* buffer size */ &bytes_written); /* actually sent */ if(result) return result; win_update_buffer_size(conn->writesockfd); if(k->pendingheader) { /* parts of what was sent was header */ curl_off_t n = CURLMIN(k->pendingheader, bytes_written); /* show the data before we change the pointer upload_fromhere */ Curl_debug(data, CURLINFO_HEADER_OUT, k->upload_fromhere, (size_t)n); k->pendingheader -= n; nbody = bytes_written - n; /* size of the written body part */ } else nbody = bytes_written; if(nbody) { /* show the data before we change the pointer upload_fromhere */ Curl_debug(data, CURLINFO_DATA_OUT, &k->upload_fromhere[bytes_written - nbody], (size_t)nbody); k->writebytecount += nbody; Curl_pgrsSetUploadCounter(data, k->writebytecount); } if((!k->upload_chunky || k->forbidchunk) && (k->writebytecount == data->state.infilesize)) { /* we have sent all data we were supposed to */ k->upload_done = TRUE; infof(data, "We are completely uploaded and fine"); } if(k->upload_present != bytes_written) { /* we only wrote a part of the buffer (if anything), deal with it! */ /* store the amount of bytes left in the buffer to write */ k->upload_present -= bytes_written; /* advance the pointer where to find the buffer when the next send is to happen */ k->upload_fromhere += bytes_written; } else { /* we've uploaded that buffer now */ result = Curl_get_upload_buffer(data); if(result) return result; k->upload_fromhere = data->state.ulbuf; k->upload_present = 0; /* no more bytes left */ if(k->upload_done) { result = Curl_done_sending(data, k); if(result) return result; } } } while(0); /* just to break out from! */ return CURLE_OK; } /* * Curl_readwrite() is the low-level function to be called when data is to * be read and written to/from the connection. * * return '*comeback' TRUE if we didn't properly drain the socket so this * function should get called again without select() or similar in between! */ CURLcode Curl_readwrite(struct connectdata *conn, struct Curl_easy *data, bool *done, bool *comeback) { struct SingleRequest *k = &data->req; CURLcode result; int didwhat = 0; curl_socket_t fd_read; curl_socket_t fd_write; int select_res = conn->cselect_bits; conn->cselect_bits = 0; /* only use the proper socket if the *_HOLD bit is not set simultaneously as then we are in rate limiting state in that transfer direction */ if((k->keepon & KEEP_RECVBITS) == KEEP_RECV) fd_read = conn->sockfd; else fd_read = CURL_SOCKET_BAD; if((k->keepon & KEEP_SENDBITS) == KEEP_SEND) fd_write = conn->writesockfd; else fd_write = CURL_SOCKET_BAD; if(data->state.drain) { select_res |= CURL_CSELECT_IN; DEBUGF(infof(data, "Curl_readwrite: forcibly told to drain data")); } if(!select_res) /* Call for select()/poll() only, if read/write/error status is not known. */ select_res = Curl_socket_check(fd_read, CURL_SOCKET_BAD, fd_write, 0); if(select_res == CURL_CSELECT_ERR) { failf(data, "select/poll returned error"); return CURLE_SEND_ERROR; } #ifdef USE_HYPER if(conn->datastream) { result = conn->datastream(data, conn, &didwhat, done, select_res); if(result || *done) return result; } else { #endif /* We go ahead and do a read if we have a readable socket or if the stream was rewound (in which case we have data in a buffer) */ if((k->keepon & KEEP_RECV) && (select_res & CURL_CSELECT_IN)) { result = readwrite_data(data, conn, k, &didwhat, done, comeback); if(result || *done) return result; } /* If we still have writing to do, we check if we have a writable socket. */ if((k->keepon & KEEP_SEND) && (select_res & CURL_CSELECT_OUT)) { /* write */ result = readwrite_upload(data, conn, &didwhat); if(result) return result; } #ifdef USE_HYPER } #endif k->now = Curl_now(); if(!didwhat) { /* no read no write, this is a timeout? */ if(k->exp100 == EXP100_AWAITING_CONTINUE) { /* This should allow some time for the header to arrive, but only a very short time as otherwise it'll be too much wasted time too often. */ /* Quoting RFC2616, section "8.2.3 Use of the 100 (Continue) Status": Therefore, when a client sends this header field to an origin server (possibly via a proxy) from which it has never seen a 100 (Continue) status, the client SHOULD NOT wait for an indefinite period before sending the request body. */ timediff_t ms = Curl_timediff(k->now, k->start100); if(ms >= data->set.expect_100_timeout) { /* we've waited long enough, continue anyway */ k->exp100 = EXP100_SEND_DATA; k->keepon |= KEEP_SEND; Curl_expire_done(data, EXPIRE_100_TIMEOUT); infof(data, "Done waiting for 100-continue"); } } } if(Curl_pgrsUpdate(data)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, k->now); if(result) return result; if(k->keepon) { if(0 > Curl_timeleft(data, &k->now, FALSE)) { if(k->size != -1) { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(k->now, data->progress.t_startsingle), k->bytecount, k->size); } else { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(k->now, data->progress.t_startsingle), k->bytecount); } return CURLE_OPERATION_TIMEDOUT; } } else { /* * The transfer has been performed. Just make some general checks before * returning. */ if(!(data->set.opt_no_body) && (k->size != -1) && (k->bytecount != k->size) && #ifdef CURL_DO_LINEEND_CONV /* Most FTP servers don't adjust their file SIZE response for CRLFs, so we'll check to see if the discrepancy can be explained by the number of CRLFs we've changed to LFs. */ (k->bytecount != (k->size + data->state.crlf_conversions)) && #endif /* CURL_DO_LINEEND_CONV */ !k->newurl) { failf(data, "transfer closed with %" CURL_FORMAT_CURL_OFF_T " bytes remaining to read", k->size - k->bytecount); return CURLE_PARTIAL_FILE; } if(!(data->set.opt_no_body) && k->chunk && (conn->chunk.state != CHUNK_STOP)) { /* * In chunked mode, return an error if the connection is closed prior to * the empty (terminating) chunk is read. * * The condition above used to check for * conn->proto.http->chunk.datasize != 0 which is true after reading * *any* chunk, not just the empty chunk. * */ failf(data, "transfer closed with outstanding read data remaining"); return CURLE_PARTIAL_FILE; } if(Curl_pgrsUpdate(data)) return CURLE_ABORTED_BY_CALLBACK; } /* Now update the "done" boolean we return */ *done = (0 == (k->keepon&(KEEP_RECV|KEEP_SEND| KEEP_RECV_PAUSE|KEEP_SEND_PAUSE))) ? TRUE : FALSE; return CURLE_OK; } /* * Curl_single_getsock() gets called by the multi interface code when the app * has requested to get the sockets for the current connection. This function * will then be called once for every connection that the multi interface * keeps track of. This function will only be called for connections that are * in the proper state to have this information available. */ int Curl_single_getsock(struct Curl_easy *data, struct connectdata *conn, curl_socket_t *sock) { int bitmap = GETSOCK_BLANK; unsigned sockindex = 0; if(conn->handler->perform_getsock) return conn->handler->perform_getsock(data, conn, sock); /* don't include HOLD and PAUSE connections */ if((data->req.keepon & KEEP_RECVBITS) == KEEP_RECV) { DEBUGASSERT(conn->sockfd != CURL_SOCKET_BAD); bitmap |= GETSOCK_READSOCK(sockindex); sock[sockindex] = conn->sockfd; } /* don't include HOLD and PAUSE connections */ if((data->req.keepon & KEEP_SENDBITS) == KEEP_SEND) { if((conn->sockfd != conn->writesockfd) || bitmap == GETSOCK_BLANK) { /* only if they are not the same socket and we have a readable one, we increase index */ if(bitmap != GETSOCK_BLANK) sockindex++; /* increase index if we need two entries */ DEBUGASSERT(conn->writesockfd != CURL_SOCKET_BAD); sock[sockindex] = conn->writesockfd; } bitmap |= GETSOCK_WRITESOCK(sockindex); } return bitmap; } /* Curl_init_CONNECT() gets called each time the handle switches to CONNECT which means this gets called once for each subsequent redirect etc */ void Curl_init_CONNECT(struct Curl_easy *data) { data->state.fread_func = data->set.fread_func_set; data->state.in = data->set.in_set; } /* * Curl_pretransfer() is called immediately before a transfer starts, and only * once for one transfer no matter if it has redirects or do multi-pass * authentication etc. */ CURLcode Curl_pretransfer(struct Curl_easy *data) { CURLcode result; if(!data->state.url && !data->set.uh) { /* we can't do anything without URL */ failf(data, "No URL set!"); return CURLE_URL_MALFORMAT; } /* since the URL may have been redirected in a previous use of this handle */ if(data->state.url_alloc) { /* the already set URL is allocated, free it first! */ Curl_safefree(data->state.url); data->state.url_alloc = FALSE; } if(!data->state.url && data->set.uh) { CURLUcode uc; free(data->set.str[STRING_SET_URL]); uc = curl_url_get(data->set.uh, CURLUPART_URL, &data->set.str[STRING_SET_URL], 0); if(uc) { failf(data, "No URL set!"); return CURLE_URL_MALFORMAT; } } data->state.prefer_ascii = data->set.prefer_ascii; data->state.list_only = data->set.list_only; data->state.httpreq = data->set.method; data->state.url = data->set.str[STRING_SET_URL]; /* Init the SSL session ID cache here. We do it here since we want to do it after the *_setopt() calls (that could specify the size of the cache) but before any transfer takes place. */ result = Curl_ssl_initsessions(data, data->set.general_ssl.max_ssl_sessions); if(result) return result; data->state.wildcardmatch = data->set.wildcard_enabled; data->state.followlocation = 0; /* reset the location-follow counter */ data->state.this_is_a_follow = FALSE; /* reset this */ data->state.errorbuf = FALSE; /* no error has occurred */ data->state.httpwant = data->set.httpwant; data->state.httpversion = 0; data->state.authproblem = FALSE; data->state.authhost.want = data->set.httpauth; data->state.authproxy.want = data->set.proxyauth; Curl_safefree(data->info.wouldredirect); if(data->state.httpreq == HTTPREQ_PUT) data->state.infilesize = data->set.filesize; else if((data->state.httpreq != HTTPREQ_GET) && (data->state.httpreq != HTTPREQ_HEAD)) { data->state.infilesize = data->set.postfieldsize; if(data->set.postfields && (data->state.infilesize == -1)) data->state.infilesize = (curl_off_t)strlen(data->set.postfields); } else data->state.infilesize = 0; /* If there is a list of cookie files to read, do it now! */ if(data->state.cookielist) Curl_cookie_loadfiles(data); /* If there is a list of host pairs to deal with */ if(data->state.resolve) result = Curl_loadhostpairs(data); if(!result) { /* Allow data->set.use_port to set which port to use. This needs to be * disabled for example when we follow Location: headers to URLs using * different ports! */ data->state.allow_port = TRUE; #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL) /************************************************************* * Tell signal handler to ignore SIGPIPE *************************************************************/ if(!data->set.no_signal) data->state.prev_signal = signal(SIGPIPE, SIG_IGN); #endif Curl_initinfo(data); /* reset session-specific information "variables" */ Curl_pgrsResetTransferSizes(data); Curl_pgrsStartNow(data); /* In case the handle is re-used and an authentication method was picked in the session we need to make sure we only use the one(s) we now consider to be fine */ data->state.authhost.picked &= data->state.authhost.want; data->state.authproxy.picked &= data->state.authproxy.want; #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch) { struct WildcardData *wc = &data->wildcard; if(wc->state < CURLWC_INIT) { result = Curl_wildcard_init(wc); /* init wildcard structures */ if(result) return CURLE_OUT_OF_MEMORY; } } #endif Curl_http2_init_state(&data->state); result = Curl_hsts_loadcb(data, data->hsts); } /* * Set user-agent. Used for HTTP, but since we can attempt to tunnel * basically anything through a http proxy we can't limit this based on * protocol. */ if(data->set.str[STRING_USERAGENT]) { Curl_safefree(data->state.aptr.uagent); data->state.aptr.uagent = aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]); if(!data->state.aptr.uagent) return CURLE_OUT_OF_MEMORY; } if(!result) result = Curl_setstropt(&data->state.aptr.user, data->set.str[STRING_USERNAME]); if(!result) result = Curl_setstropt(&data->state.aptr.passwd, data->set.str[STRING_PASSWORD]); if(!result) result = Curl_setstropt(&data->state.aptr.proxyuser, data->set.str[STRING_PROXYUSERNAME]); if(!result) result = Curl_setstropt(&data->state.aptr.proxypasswd, data->set.str[STRING_PROXYPASSWORD]); data->req.headerbytecount = 0; return result; } /* * Curl_posttransfer() is called immediately after a transfer ends */ CURLcode Curl_posttransfer(struct Curl_easy *data) { #if defined(HAVE_SIGNAL) && defined(SIGPIPE) && !defined(HAVE_MSG_NOSIGNAL) /* restore the signal handler for SIGPIPE before we get back */ if(!data->set.no_signal) signal(SIGPIPE, data->state.prev_signal); #else (void)data; /* unused parameter */ #endif return CURLE_OK; } /* * Curl_follow() handles the URL redirect magic. Pass in the 'newurl' string * as given by the remote server and set up the new URL to request. * * This function DOES NOT FREE the given url. */ CURLcode Curl_follow(struct Curl_easy *data, char *newurl, /* the Location: string */ followtype type) /* see transfer.h */ { #ifdef CURL_DISABLE_HTTP (void)data; (void)newurl; (void)type; /* Location: following will not happen when HTTP is disabled */ return CURLE_TOO_MANY_REDIRECTS; #else /* Location: redirect */ bool disallowport = FALSE; bool reachedmax = FALSE; CURLUcode uc; DEBUGASSERT(type != FOLLOW_NONE); if(type == FOLLOW_REDIR) { if((data->set.maxredirs != -1) && (data->state.followlocation >= data->set.maxredirs)) { reachedmax = TRUE; type = FOLLOW_FAKE; /* switch to fake to store the would-be-redirected to URL */ } else { /* mark the next request as a followed location: */ data->state.this_is_a_follow = TRUE; data->state.followlocation++; /* count location-followers */ if(data->set.http_auto_referer) { CURLU *u; char *referer = NULL; /* We are asked to automatically set the previous URL as the referer when we get the next URL. We pick the ->url field, which may or may not be 100% correct */ if(data->state.referer_alloc) { Curl_safefree(data->state.referer); data->state.referer_alloc = FALSE; } /* Make a copy of the URL without crenditals and fragment */ u = curl_url(); if(!u) return CURLE_OUT_OF_MEMORY; uc = curl_url_set(u, CURLUPART_URL, data->state.url, 0); if(!uc) uc = curl_url_set(u, CURLUPART_FRAGMENT, NULL, 0); if(!uc) uc = curl_url_set(u, CURLUPART_USER, NULL, 0); if(!uc) uc = curl_url_set(u, CURLUPART_PASSWORD, NULL, 0); if(!uc) uc = curl_url_get(u, CURLUPART_URL, &referer, 0); curl_url_cleanup(u); if(uc || !referer) return CURLE_OUT_OF_MEMORY; data->state.referer = referer; data->state.referer_alloc = TRUE; /* yes, free this later */ } } } if((type != FOLLOW_RETRY) && (data->req.httpcode != 401) && (data->req.httpcode != 407) && Curl_is_absolute_url(newurl, NULL, MAX_SCHEME_LEN)) /* If this is not redirect due to a 401 or 407 response and an absolute URL: don't allow a custom port number */ disallowport = TRUE; DEBUGASSERT(data->state.uh); uc = curl_url_set(data->state.uh, CURLUPART_URL, newurl, (type == FOLLOW_FAKE) ? CURLU_NON_SUPPORT_SCHEME : ((type == FOLLOW_REDIR) ? CURLU_URLENCODE : 0) | CURLU_ALLOW_SPACE); if(uc) { if(type != FOLLOW_FAKE) return Curl_uc_to_curlcode(uc); /* the URL could not be parsed for some reason, but since this is FAKE mode, just duplicate the field as-is */ newurl = strdup(newurl); if(!newurl) return CURLE_OUT_OF_MEMORY; } else { uc = curl_url_get(data->state.uh, CURLUPART_URL, &newurl, 0); if(uc) return Curl_uc_to_curlcode(uc); } if(type == FOLLOW_FAKE) { /* we're only figuring out the new url if we would've followed locations but now we're done so we can get out! */ data->info.wouldredirect = newurl; if(reachedmax) { failf(data, "Maximum (%ld) redirects followed", data->set.maxredirs); return CURLE_TOO_MANY_REDIRECTS; } return CURLE_OK; } if(disallowport) data->state.allow_port = FALSE; if(data->state.url_alloc) Curl_safefree(data->state.url); data->state.url = newurl; data->state.url_alloc = TRUE; infof(data, "Issue another request to this URL: '%s'", data->state.url); /* * We get here when the HTTP code is 300-399 (and 401). We need to perform * differently based on exactly what return code there was. * * News from 7.10.6: we can also get here on a 401 or 407, in case we act on * a HTTP (proxy-) authentication scheme other than Basic. */ switch(data->info.httpcode) { /* 401 - Act on a WWW-Authenticate, we keep on moving and do the Authorization: XXXX header in the HTTP request code snippet */ /* 407 - Act on a Proxy-Authenticate, we keep on moving and do the Proxy-Authorization: XXXX header in the HTTP request code snippet */ /* 300 - Multiple Choices */ /* 306 - Not used */ /* 307 - Temporary Redirect */ default: /* for all above (and the unknown ones) */ /* Some codes are explicitly mentioned since I've checked RFC2616 and they * seem to be OK to POST to. */ break; case 301: /* Moved Permanently */ /* (quote from RFC7231, section 6.4.2) * * Note: For historical reasons, a user agent MAY change the request * method from POST to GET for the subsequent request. If this * behavior is undesired, the 307 (Temporary Redirect) status code * can be used instead. * * ---- * * Many webservers expect this, so these servers often answers to a POST * request with an error page. To be sure that libcurl gets the page that * most user agents would get, libcurl has to force GET. * * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and * can be overridden with CURLOPT_POSTREDIR. */ if((data->state.httpreq == HTTPREQ_POST || data->state.httpreq == HTTPREQ_POST_FORM || data->state.httpreq == HTTPREQ_POST_MIME) && !(data->set.keep_post & CURL_REDIR_POST_301)) { infof(data, "Switch from POST to GET"); data->state.httpreq = HTTPREQ_GET; } break; case 302: /* Found */ /* (quote from RFC7231, section 6.4.3) * * Note: For historical reasons, a user agent MAY change the request * method from POST to GET for the subsequent request. If this * behavior is undesired, the 307 (Temporary Redirect) status code * can be used instead. * * ---- * * Many webservers expect this, so these servers often answers to a POST * request with an error page. To be sure that libcurl gets the page that * most user agents would get, libcurl has to force GET. * * This behavior is forbidden by RFC1945 and the obsolete RFC2616, and * can be overridden with CURLOPT_POSTREDIR. */ if((data->state.httpreq == HTTPREQ_POST || data->state.httpreq == HTTPREQ_POST_FORM || data->state.httpreq == HTTPREQ_POST_MIME) && !(data->set.keep_post & CURL_REDIR_POST_302)) { infof(data, "Switch from POST to GET"); data->state.httpreq = HTTPREQ_GET; } break; case 303: /* See Other */ /* 'See Other' location is not the resource but a substitute for the * resource. In this case we switch the method to GET/HEAD, unless the * method is POST and the user specified to keep it as POST. * https://github.com/curl/curl/issues/5237#issuecomment-614641049 */ if(data->state.httpreq != HTTPREQ_GET && ((data->state.httpreq != HTTPREQ_POST && data->state.httpreq != HTTPREQ_POST_FORM && data->state.httpreq != HTTPREQ_POST_MIME) || !(data->set.keep_post & CURL_REDIR_POST_303))) { data->state.httpreq = HTTPREQ_GET; data->set.upload = false; infof(data, "Switch to %s", data->set.opt_no_body?"HEAD":"GET"); } break; case 304: /* Not Modified */ /* 304 means we did a conditional request and it was "Not modified". * We shouldn't get any Location: header in this response! */ break; case 305: /* Use Proxy */ /* (quote from RFC2616, section 10.3.6): * "The requested resource MUST be accessed through the proxy given * by the Location field. The Location field gives the URI of the * proxy. The recipient is expected to repeat this single request * via the proxy. 305 responses MUST only be generated by origin * servers." */ break; } Curl_pgrsTime(data, TIMER_REDIRECT); Curl_pgrsResetTransferSizes(data); return CURLE_OK; #endif /* CURL_DISABLE_HTTP */ } /* Returns CURLE_OK *and* sets '*url' if a request retry is wanted. NOTE: that the *url is malloc()ed. */ CURLcode Curl_retry_request(struct Curl_easy *data, char **url) { struct connectdata *conn = data->conn; bool retry = FALSE; *url = NULL; /* if we're talking upload, we can't do the checks below, unless the protocol is HTTP as when uploading over HTTP we will still get a response */ if(data->set.upload && !(conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_RTSP))) return CURLE_OK; if((data->req.bytecount + data->req.headerbytecount == 0) && conn->bits.reuse && (!data->set.opt_no_body || (conn->handler->protocol & PROTO_FAMILY_HTTP)) && (data->set.rtspreq != RTSPREQ_RECEIVE)) /* We got no data, we attempted to re-use a connection. For HTTP this can be a retry so we try again regardless if we expected a body. For other protocols we only try again only if we expected a body. This might happen if the connection was left alive when we were done using it before, but that was closed when we wanted to read from it again. Bad luck. Retry the same request on a fresh connect! */ retry = TRUE; else if(data->state.refused_stream && (data->req.bytecount + data->req.headerbytecount == 0) ) { /* This was sent on a refused stream, safe to rerun. A refused stream error can typically only happen on HTTP/2 level if the stream is safe to issue again, but the nghttp2 API can deliver the message to other streams as well, which is why this adds the check the data counters too. */ infof(data, "REFUSED_STREAM, retrying a fresh connect"); data->state.refused_stream = FALSE; /* clear again */ retry = TRUE; } if(retry) { #define CONN_MAX_RETRIES 5 if(data->state.retrycount++ >= CONN_MAX_RETRIES) { failf(data, "Connection died, tried %d times before giving up", CONN_MAX_RETRIES); data->state.retrycount = 0; return CURLE_SEND_ERROR; } infof(data, "Connection died, retrying a fresh connect (retry count: %d)", data->state.retrycount); *url = strdup(data->state.url); if(!*url) return CURLE_OUT_OF_MEMORY; connclose(conn, "retry"); /* close this connection */ conn->bits.retry = TRUE; /* mark this as a connection we're about to retry. Marking it this way should prevent i.e HTTP transfers to return error just because nothing has been transferred! */ if(conn->handler->protocol&PROTO_FAMILY_HTTP) { if(data->req.writebytecount) { CURLcode result = Curl_readrewind(data); if(result) { Curl_safefree(*url); return result; } } } } return CURLE_OK; } /* * Curl_setup_transfer() is called to setup some basic properties for the * upcoming transfer. */ void Curl_setup_transfer( struct Curl_easy *data, /* transfer */ int sockindex, /* socket index to read from or -1 */ curl_off_t size, /* -1 if unknown at this point */ bool getheader, /* TRUE if header parsing is wanted */ int writesockindex /* socket index to write to, it may very well be the same we read from. -1 disables */ ) { struct SingleRequest *k = &data->req; struct connectdata *conn = data->conn; struct HTTP *http = data->req.p.http; bool httpsending = ((conn->handler->protocol&PROTO_FAMILY_HTTP) && (http->sending == HTTPSEND_REQUEST)); DEBUGASSERT(conn != NULL); DEBUGASSERT((sockindex <= 1) && (sockindex >= -1)); if(conn->bits.multiplex || conn->httpversion == 20 || httpsending) { /* when multiplexing, the read/write sockets need to be the same! */ conn->sockfd = sockindex == -1 ? ((writesockindex == -1 ? CURL_SOCKET_BAD : conn->sock[writesockindex])) : conn->sock[sockindex]; conn->writesockfd = conn->sockfd; if(httpsending) /* special and very HTTP-specific */ writesockindex = FIRSTSOCKET; } else { conn->sockfd = sockindex == -1 ? CURL_SOCKET_BAD : conn->sock[sockindex]; conn->writesockfd = writesockindex == -1 ? CURL_SOCKET_BAD:conn->sock[writesockindex]; } k->getheader = getheader; k->size = size; /* The code sequence below is placed in this function just because all necessary input is not always known in do_complete() as this function may be called after that */ if(!k->getheader) { k->header = FALSE; if(size > 0) Curl_pgrsSetDownloadSize(data, size); } /* we want header and/or body, if neither then don't do this! */ if(k->getheader || !data->set.opt_no_body) { if(sockindex != -1) k->keepon |= KEEP_RECV; if(writesockindex != -1) { /* HTTP 1.1 magic: Even if we require a 100-return code before uploading data, we might need to write data before that since the REQUEST may not have been finished sent off just yet. Thus, we must check if the request has been sent before we set the state info where we wait for the 100-return code */ if((data->state.expect100header) && (conn->handler->protocol&PROTO_FAMILY_HTTP) && (http->sending == HTTPSEND_BODY)) { /* wait with write until we either got 100-continue or a timeout */ k->exp100 = EXP100_AWAITING_CONTINUE; k->start100 = Curl_now(); /* Set a timeout for the multi interface. Add the inaccuracy margin so that we don't fire slightly too early and get denied to run. */ Curl_expire(data, data->set.expect_100_timeout, EXPIRE_100_TIMEOUT); } else { if(data->state.expect100header) /* when we've sent off the rest of the headers, we must await a 100-continue but first finish sending the request */ k->exp100 = EXP100_SENDING_REQUEST; /* enable the write bit when we're not waiting for continue */ k->keepon |= KEEP_SEND; } } /* if(writesockindex != -1) */ } /* if(k->getheader || !data->set.opt_no_body) */ }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/dotdot.h
#ifndef HEADER_CURL_DOTDOT_H #define HEADER_CURL_DOTDOT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ char *Curl_dedotdotify(const char *input); #endif /* HEADER_CURL_DOTDOT_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/nonblock.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE)) #include <sys/filio.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #include "nonblock.h" /* * curlx_nonblock() set the given socket to either blocking or non-blocking * mode based on the 'nonblock' boolean argument. This function is highly * portable. */ int curlx_nonblock(curl_socket_t sockfd, /* operate on this */ int nonblock /* TRUE or FALSE */) { #if defined(HAVE_FCNTL_O_NONBLOCK) /* most recent unix versions */ int flags; flags = sfcntl(sockfd, F_GETFL, 0); if(nonblock) return sfcntl(sockfd, F_SETFL, flags | O_NONBLOCK); return sfcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK)); #elif defined(HAVE_IOCTL_FIONBIO) /* older unix versions */ int flags = nonblock ? 1 : 0; return ioctl(sockfd, FIONBIO, &flags); #elif defined(HAVE_IOCTLSOCKET_FIONBIO) /* Windows */ unsigned long flags = nonblock ? 1UL : 0UL; return ioctlsocket(sockfd, FIONBIO, &flags); #elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO) /* Amiga */ long flags = nonblock ? 1L : 0L; return IoctlSocket(sockfd, FIONBIO, (char *)&flags); #elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK) /* BeOS */ long b = nonblock ? 1L : 0L; return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b)); #else # error "no non-blocking method was found/used/set" #endif }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/imap.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * RFC2195 CRAM-MD5 authentication * RFC2595 Using TLS with IMAP, POP3 and ACAP * RFC2831 DIGEST-MD5 authentication * RFC3501 IMAPv4 protocol * RFC4422 Simple Authentication and Security Layer (SASL) * RFC4616 PLAIN authentication * RFC4752 The Kerberos V5 ("GSSAPI") SASL Mechanism * RFC4959 IMAP Extension for SASL Initial Client Response * RFC5092 IMAP URL Scheme * RFC6749 OAuth 2.0 Authorization Framework * RFC8314 Use of TLS for Email Submission and Access * Draft LOGIN SASL Mechanism <draft-murchison-sasl-login-00.txt> * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_IMAP #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif #include <curl/curl.h> #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "progress.h" #include "transfer.h" #include "escape.h" #include "http.h" /* for HTTP proxy tunnel stuff */ #include "socks.h" #include "imap.h" #include "mime.h" #include "strtoofft.h" #include "strcase.h" #include "vtls/vtls.h" #include "connect.h" #include "select.h" #include "multiif.h" #include "url.h" #include "strcase.h" #include "bufref.h" #include "curl_sasl.h" #include "warnless.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* Local API functions */ static CURLcode imap_regular_transfer(struct Curl_easy *data, bool *done); static CURLcode imap_do(struct Curl_easy *data, bool *done); static CURLcode imap_done(struct Curl_easy *data, CURLcode status, bool premature); static CURLcode imap_connect(struct Curl_easy *data, bool *done); static CURLcode imap_disconnect(struct Curl_easy *data, struct connectdata *conn, bool dead); static CURLcode imap_multi_statemach(struct Curl_easy *data, bool *done); static int imap_getsock(struct Curl_easy *data, struct connectdata *conn, curl_socket_t *socks); static CURLcode imap_doing(struct Curl_easy *data, bool *dophase_done); static CURLcode imap_setup_connection(struct Curl_easy *data, struct connectdata *conn); static char *imap_atom(const char *str, bool escape_only); static CURLcode imap_sendf(struct Curl_easy *data, const char *fmt, ...); static CURLcode imap_parse_url_options(struct connectdata *conn); static CURLcode imap_parse_url_path(struct Curl_easy *data); static CURLcode imap_parse_custom_request(struct Curl_easy *data); static CURLcode imap_perform_authenticate(struct Curl_easy *data, const char *mech, const struct bufref *initresp); static CURLcode imap_continue_authenticate(struct Curl_easy *data, const char *mech, const struct bufref *resp); static CURLcode imap_cancel_authenticate(struct Curl_easy *data, const char *mech); static CURLcode imap_get_message(struct Curl_easy *data, struct bufref *out); /* * IMAP protocol handler. */ const struct Curl_handler Curl_handler_imap = { "IMAP", /* scheme */ imap_setup_connection, /* setup_connection */ imap_do, /* do_it */ imap_done, /* done */ ZERO_NULL, /* do_more */ imap_connect, /* connect_it */ imap_multi_statemach, /* connecting */ imap_doing, /* doing */ imap_getsock, /* proto_getsock */ imap_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ imap_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ ZERO_NULL, /* attach connection */ PORT_IMAP, /* defport */ CURLPROTO_IMAP, /* protocol */ CURLPROTO_IMAP, /* family */ PROTOPT_CLOSEACTION| /* flags */ PROTOPT_URLOPTIONS }; #ifdef USE_SSL /* * IMAPS protocol handler. */ const struct Curl_handler Curl_handler_imaps = { "IMAPS", /* scheme */ imap_setup_connection, /* setup_connection */ imap_do, /* do_it */ imap_done, /* done */ ZERO_NULL, /* do_more */ imap_connect, /* connect_it */ imap_multi_statemach, /* connecting */ imap_doing, /* doing */ imap_getsock, /* proto_getsock */ imap_getsock, /* doing_getsock */ ZERO_NULL, /* domore_getsock */ ZERO_NULL, /* perform_getsock */ imap_disconnect, /* disconnect */ ZERO_NULL, /* readwrite */ ZERO_NULL, /* connection_check */ ZERO_NULL, /* attach connection */ PORT_IMAPS, /* defport */ CURLPROTO_IMAPS, /* protocol */ CURLPROTO_IMAP, /* family */ PROTOPT_CLOSEACTION | PROTOPT_SSL | /* flags */ PROTOPT_URLOPTIONS }; #endif #define IMAP_RESP_OK 1 #define IMAP_RESP_NOT_OK 2 #define IMAP_RESP_PREAUTH 3 /* SASL parameters for the imap protocol */ static const struct SASLproto saslimap = { "imap", /* The service name */ imap_perform_authenticate, /* Send authentication command */ imap_continue_authenticate, /* Send authentication continuation */ imap_cancel_authenticate, /* Send authentication cancellation */ imap_get_message, /* Get SASL response message */ 0, /* No maximum initial response length */ '+', /* Code received when continuation is expected */ IMAP_RESP_OK, /* Code to receive upon authentication success */ SASL_AUTH_DEFAULT, /* Default mechanisms */ SASL_FLAG_BASE64 /* Configuration flags */ }; #ifdef USE_SSL static void imap_to_imaps(struct connectdata *conn) { /* Change the connection handler */ conn->handler = &Curl_handler_imaps; /* Set the connection's upgraded to TLS flag */ conn->bits.tls_upgraded = TRUE; } #else #define imap_to_imaps(x) Curl_nop_stmt #endif /*********************************************************************** * * imap_matchresp() * * Determines whether the untagged response is related to the specified * command by checking if it is in format "* <command-name> ..." or * "* <number> <command-name> ...". * * The "* " marker is assumed to have already been checked by the caller. */ static bool imap_matchresp(const char *line, size_t len, const char *cmd) { const char *end = line + len; size_t cmd_len = strlen(cmd); /* Skip the untagged response marker */ line += 2; /* Do we have a number after the marker? */ if(line < end && ISDIGIT(*line)) { /* Skip the number */ do line++; while(line < end && ISDIGIT(*line)); /* Do we have the space character? */ if(line == end || *line != ' ') return FALSE; line++; } /* Does the command name match and is it followed by a space character or at the end of line? */ if(line + cmd_len <= end && strncasecompare(line, cmd, cmd_len) && (line[cmd_len] == ' ' || line + cmd_len + 2 == end)) return TRUE; return FALSE; } /*********************************************************************** * * imap_endofresp() * * Checks whether the given string is a valid tagged, untagged or continuation * response which can be processed by the response handler. */ static bool imap_endofresp(struct Curl_easy *data, struct connectdata *conn, char *line, size_t len, int *resp) { struct IMAP *imap = data->req.p.imap; struct imap_conn *imapc = &conn->proto.imapc; const char *id = imapc->resptag; size_t id_len = strlen(id); /* Do we have a tagged command response? */ if(len >= id_len + 1 && !memcmp(id, line, id_len) && line[id_len] == ' ') { line += id_len + 1; len -= id_len + 1; if(len >= 2 && !memcmp(line, "OK", 2)) *resp = IMAP_RESP_OK; else if(len >= 7 && !memcmp(line, "PREAUTH", 7)) *resp = IMAP_RESP_PREAUTH; else *resp = IMAP_RESP_NOT_OK; return TRUE; } /* Do we have an untagged command response? */ if(len >= 2 && !memcmp("* ", line, 2)) { switch(imapc->state) { /* States which are interested in untagged responses */ case IMAP_CAPABILITY: if(!imap_matchresp(line, len, "CAPABILITY")) return FALSE; break; case IMAP_LIST: if((!imap->custom && !imap_matchresp(line, len, "LIST")) || (imap->custom && !imap_matchresp(line, len, imap->custom) && (!strcasecompare(imap->custom, "STORE") || !imap_matchresp(line, len, "FETCH")) && !strcasecompare(imap->custom, "SELECT") && !strcasecompare(imap->custom, "EXAMINE") && !strcasecompare(imap->custom, "SEARCH") && !strcasecompare(imap->custom, "EXPUNGE") && !strcasecompare(imap->custom, "LSUB") && !strcasecompare(imap->custom, "UID") && !strcasecompare(imap->custom, "GETQUOTAROOT") && !strcasecompare(imap->custom, "NOOP"))) return FALSE; break; case IMAP_SELECT: /* SELECT is special in that its untagged responses do not have a common prefix so accept anything! */ break; case IMAP_FETCH: if(!imap_matchresp(line, len, "FETCH")) return FALSE; break; case IMAP_SEARCH: if(!imap_matchresp(line, len, "SEARCH")) return FALSE; break; /* Ignore other untagged responses */ default: return FALSE; } *resp = '*'; return TRUE; } /* Do we have a continuation response? This should be a + symbol followed by a space and optionally some text as per RFC-3501 for the AUTHENTICATE and APPEND commands and as outlined in Section 4. Examples of RFC-4959 but some e-mail servers ignore this and only send a single + instead. */ if(imap && !imap->custom && ((len == 3 && line[0] == '+') || (len >= 2 && !memcmp("+ ", line, 2)))) { switch(imapc->state) { /* States which are interested in continuation responses */ case IMAP_AUTHENTICATE: case IMAP_APPEND: *resp = '+'; break; default: failf(data, "Unexpected continuation response"); *resp = -1; break; } return TRUE; } return FALSE; /* Nothing for us */ } /*********************************************************************** * * imap_get_message() * * Gets the authentication message from the response buffer. */ static CURLcode imap_get_message(struct Curl_easy *data, struct bufref *out) { char *message = data->state.buffer; size_t len = strlen(message); if(len > 2) { /* Find the start of the message */ len -= 2; for(message += 2; *message == ' ' || *message == '\t'; message++, len--) ; /* Find the end of the message */ while(len--) if(message[len] != '\r' && message[len] != '\n' && message[len] != ' ' && message[len] != '\t') break; /* Terminate the message */ message[++len] = '\0'; Curl_bufref_set(out, message, len, NULL); } else /* junk input => zero length output */ Curl_bufref_set(out, "", 0, NULL); return CURLE_OK; } /*********************************************************************** * * state() * * This is the ONLY way to change IMAP state! */ static void state(struct Curl_easy *data, imapstate newstate) { struct imap_conn *imapc = &data->conn->proto.imapc; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[]={ "STOP", "SERVERGREET", "CAPABILITY", "STARTTLS", "UPGRADETLS", "AUTHENTICATE", "LOGIN", "LIST", "SELECT", "FETCH", "FETCH_FINAL", "APPEND", "APPEND_FINAL", "SEARCH", "LOGOUT", /* LAST */ }; if(imapc->state != newstate) infof(data, "IMAP %p state change from %s to %s", (void *)imapc, names[imapc->state], names[newstate]); #endif imapc->state = newstate; } /*********************************************************************** * * imap_perform_capability() * * Sends the CAPABILITY command in order to obtain a list of server side * supported capabilities. */ static CURLcode imap_perform_capability(struct Curl_easy *data, struct connectdata *conn) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; imapc->sasl.authmechs = SASL_AUTH_NONE; /* No known auth. mechanisms yet */ imapc->sasl.authused = SASL_AUTH_NONE; /* Clear the auth. mechanism used */ imapc->tls_supported = FALSE; /* Clear the TLS capability */ /* Send the CAPABILITY command */ result = imap_sendf(data, "CAPABILITY"); if(!result) state(data, IMAP_CAPABILITY); return result; } /*********************************************************************** * * imap_perform_starttls() * * Sends the STARTTLS command to start the upgrade to TLS. */ static CURLcode imap_perform_starttls(struct Curl_easy *data) { /* Send the STARTTLS command */ CURLcode result = imap_sendf(data, "STARTTLS"); if(!result) state(data, IMAP_STARTTLS); return result; } /*********************************************************************** * * imap_perform_upgrade_tls() * * Performs the upgrade to TLS. */ static CURLcode imap_perform_upgrade_tls(struct Curl_easy *data, struct connectdata *conn) { /* Start the SSL connection */ struct imap_conn *imapc = &conn->proto.imapc; CURLcode result = Curl_ssl_connect_nonblocking(data, conn, FALSE, FIRSTSOCKET, &imapc->ssldone); if(!result) { if(imapc->state != IMAP_UPGRADETLS) state(data, IMAP_UPGRADETLS); if(imapc->ssldone) { imap_to_imaps(conn); result = imap_perform_capability(data, conn); } } return result; } /*********************************************************************** * * imap_perform_login() * * Sends a clear text LOGIN command to authenticate with. */ static CURLcode imap_perform_login(struct Curl_easy *data, struct connectdata *conn) { CURLcode result = CURLE_OK; char *user; char *passwd; /* Check we have a username and password to authenticate with and end the connect phase if we don't */ if(!conn->bits.user_passwd) { state(data, IMAP_STOP); return result; } /* Make sure the username and password are in the correct atom format */ user = imap_atom(conn->user, false); passwd = imap_atom(conn->passwd, false); /* Send the LOGIN command */ result = imap_sendf(data, "LOGIN %s %s", user ? user : "", passwd ? passwd : ""); free(user); free(passwd); if(!result) state(data, IMAP_LOGIN); return result; } /*********************************************************************** * * imap_perform_authenticate() * * Sends an AUTHENTICATE command allowing the client to login with the given * SASL authentication mechanism. */ static CURLcode imap_perform_authenticate(struct Curl_easy *data, const char *mech, const struct bufref *initresp) { CURLcode result = CURLE_OK; const char *ir = (const char *) Curl_bufref_ptr(initresp); if(ir) { /* Send the AUTHENTICATE command with the initial response */ result = imap_sendf(data, "AUTHENTICATE %s %s", mech, ir); } else { /* Send the AUTHENTICATE command */ result = imap_sendf(data, "AUTHENTICATE %s", mech); } return result; } /*********************************************************************** * * imap_continue_authenticate() * * Sends SASL continuation data. */ static CURLcode imap_continue_authenticate(struct Curl_easy *data, const char *mech, const struct bufref *resp) { struct imap_conn *imapc = &data->conn->proto.imapc; (void)mech; return Curl_pp_sendf(data, &imapc->pp, "%s", (const char *) Curl_bufref_ptr(resp)); } /*********************************************************************** * * imap_cancel_authenticate() * * Sends SASL cancellation. */ static CURLcode imap_cancel_authenticate(struct Curl_easy *data, const char *mech) { struct imap_conn *imapc = &data->conn->proto.imapc; (void)mech; return Curl_pp_sendf(data, &imapc->pp, "*"); } /*********************************************************************** * * imap_perform_authentication() * * Initiates the authentication sequence, with the appropriate SASL * authentication mechanism, falling back to clear text should a common * mechanism not be available between the client and server. */ static CURLcode imap_perform_authentication(struct Curl_easy *data, struct connectdata *conn) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; saslprogress progress; /* Check if already authenticated OR if there is enough data to authenticate with and end the connect phase if we don't */ if(imapc->preauth || !Curl_sasl_can_authenticate(&imapc->sasl, conn)) { state(data, IMAP_STOP); return result; } /* Calculate the SASL login details */ result = Curl_sasl_start(&imapc->sasl, data, imapc->ir_supported, &progress); if(!result) { if(progress == SASL_INPROGRESS) state(data, IMAP_AUTHENTICATE); else if(!imapc->login_disabled && (imapc->preftype & IMAP_TYPE_CLEARTEXT)) /* Perform clear text authentication */ result = imap_perform_login(data, conn); else { /* Other mechanisms not supported */ infof(data, "No known authentication mechanisms supported!"); result = CURLE_LOGIN_DENIED; } } return result; } /*********************************************************************** * * imap_perform_list() * * Sends a LIST command or an alternative custom request. */ static CURLcode imap_perform_list(struct Curl_easy *data) { CURLcode result = CURLE_OK; struct IMAP *imap = data->req.p.imap; if(imap->custom) /* Send the custom request */ result = imap_sendf(data, "%s%s", imap->custom, imap->custom_params ? imap->custom_params : ""); else { /* Make sure the mailbox is in the correct atom format if necessary */ char *mailbox = imap->mailbox ? imap_atom(imap->mailbox, true) : strdup(""); if(!mailbox) return CURLE_OUT_OF_MEMORY; /* Send the LIST command */ result = imap_sendf(data, "LIST \"%s\" *", mailbox); free(mailbox); } if(!result) state(data, IMAP_LIST); return result; } /*********************************************************************** * * imap_perform_select() * * Sends a SELECT command to ask the server to change the selected mailbox. */ static CURLcode imap_perform_select(struct Curl_easy *data) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; struct IMAP *imap = data->req.p.imap; struct imap_conn *imapc = &conn->proto.imapc; char *mailbox; /* Invalidate old information as we are switching mailboxes */ Curl_safefree(imapc->mailbox); Curl_safefree(imapc->mailbox_uidvalidity); /* Check we have a mailbox */ if(!imap->mailbox) { failf(data, "Cannot SELECT without a mailbox."); return CURLE_URL_MALFORMAT; } /* Make sure the mailbox is in the correct atom format */ mailbox = imap_atom(imap->mailbox, false); if(!mailbox) return CURLE_OUT_OF_MEMORY; /* Send the SELECT command */ result = imap_sendf(data, "SELECT %s", mailbox); free(mailbox); if(!result) state(data, IMAP_SELECT); return result; } /*********************************************************************** * * imap_perform_fetch() * * Sends a FETCH command to initiate the download of a message. */ static CURLcode imap_perform_fetch(struct Curl_easy *data) { CURLcode result = CURLE_OK; struct IMAP *imap = data->req.p.imap; /* Check we have a UID */ if(imap->uid) { /* Send the FETCH command */ if(imap->partial) result = imap_sendf(data, "UID FETCH %s BODY[%s]<%s>", imap->uid, imap->section ? imap->section : "", imap->partial); else result = imap_sendf(data, "UID FETCH %s BODY[%s]", imap->uid, imap->section ? imap->section : ""); } else if(imap->mindex) { /* Send the FETCH command */ if(imap->partial) result = imap_sendf(data, "FETCH %s BODY[%s]<%s>", imap->mindex, imap->section ? imap->section : "", imap->partial); else result = imap_sendf(data, "FETCH %s BODY[%s]", imap->mindex, imap->section ? imap->section : ""); } else { failf(data, "Cannot FETCH without a UID."); return CURLE_URL_MALFORMAT; } if(!result) state(data, IMAP_FETCH); return result; } /*********************************************************************** * * imap_perform_append() * * Sends an APPEND command to initiate the upload of a message. */ static CURLcode imap_perform_append(struct Curl_easy *data) { CURLcode result = CURLE_OK; struct IMAP *imap = data->req.p.imap; char *mailbox; /* Check we have a mailbox */ if(!imap->mailbox) { failf(data, "Cannot APPEND without a mailbox."); return CURLE_URL_MALFORMAT; } /* Prepare the mime data if some. */ if(data->set.mimepost.kind != MIMEKIND_NONE) { /* Use the whole structure as data. */ data->set.mimepost.flags &= ~MIME_BODY_ONLY; /* Add external headers and mime version. */ curl_mime_headers(&data->set.mimepost, data->set.headers, 0); result = Curl_mime_prepare_headers(&data->set.mimepost, NULL, NULL, MIMESTRATEGY_MAIL); if(!result) if(!Curl_checkheaders(data, "Mime-Version")) result = Curl_mime_add_header(&data->set.mimepost.curlheaders, "Mime-Version: 1.0"); /* Make sure we will read the entire mime structure. */ if(!result) result = Curl_mime_rewind(&data->set.mimepost); if(result) return result; data->state.infilesize = Curl_mime_size(&data->set.mimepost); /* Read from mime structure. */ data->state.fread_func = (curl_read_callback) Curl_mime_read; data->state.in = (void *) &data->set.mimepost; } /* Check we know the size of the upload */ if(data->state.infilesize < 0) { failf(data, "Cannot APPEND with unknown input file size"); return CURLE_UPLOAD_FAILED; } /* Make sure the mailbox is in the correct atom format */ mailbox = imap_atom(imap->mailbox, false); if(!mailbox) return CURLE_OUT_OF_MEMORY; /* Send the APPEND command */ result = imap_sendf(data, "APPEND %s (\\Seen) {%" CURL_FORMAT_CURL_OFF_T "}", mailbox, data->state.infilesize); free(mailbox); if(!result) state(data, IMAP_APPEND); return result; } /*********************************************************************** * * imap_perform_search() * * Sends a SEARCH command. */ static CURLcode imap_perform_search(struct Curl_easy *data) { CURLcode result = CURLE_OK; struct IMAP *imap = data->req.p.imap; /* Check we have a query string */ if(!imap->query) { failf(data, "Cannot SEARCH without a query string."); return CURLE_URL_MALFORMAT; } /* Send the SEARCH command */ result = imap_sendf(data, "SEARCH %s", imap->query); if(!result) state(data, IMAP_SEARCH); return result; } /*********************************************************************** * * imap_perform_logout() * * Performs the logout action prior to sclose() being called. */ static CURLcode imap_perform_logout(struct Curl_easy *data) { /* Send the LOGOUT command */ CURLcode result = imap_sendf(data, "LOGOUT"); if(!result) state(data, IMAP_LOGOUT); return result; } /* For the initial server greeting */ static CURLcode imap_state_servergreet_resp(struct Curl_easy *data, int imapcode, imapstate instate) { struct connectdata *conn = data->conn; (void)instate; /* no use for this yet */ if(imapcode == IMAP_RESP_PREAUTH) { /* PREAUTH */ struct imap_conn *imapc = &conn->proto.imapc; imapc->preauth = TRUE; infof(data, "PREAUTH connection, already authenticated!"); } else if(imapcode != IMAP_RESP_OK) { failf(data, "Got unexpected imap-server response"); return CURLE_WEIRD_SERVER_REPLY; } return imap_perform_capability(data, conn); } /* For CAPABILITY responses */ static CURLcode imap_state_capability_resp(struct Curl_easy *data, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; struct imap_conn *imapc = &conn->proto.imapc; const char *line = data->state.buffer; (void)instate; /* no use for this yet */ /* Do we have a untagged response? */ if(imapcode == '*') { line += 2; /* Loop through the data line */ for(;;) { size_t wordlen; while(*line && (*line == ' ' || *line == '\t' || *line == '\r' || *line == '\n')) { line++; } if(!*line) break; /* Extract the word */ for(wordlen = 0; line[wordlen] && line[wordlen] != ' ' && line[wordlen] != '\t' && line[wordlen] != '\r' && line[wordlen] != '\n';) wordlen++; /* Does the server support the STARTTLS capability? */ if(wordlen == 8 && !memcmp(line, "STARTTLS", 8)) imapc->tls_supported = TRUE; /* Has the server explicitly disabled clear text authentication? */ else if(wordlen == 13 && !memcmp(line, "LOGINDISABLED", 13)) imapc->login_disabled = TRUE; /* Does the server support the SASL-IR capability? */ else if(wordlen == 7 && !memcmp(line, "SASL-IR", 7)) imapc->ir_supported = TRUE; /* Do we have a SASL based authentication mechanism? */ else if(wordlen > 5 && !memcmp(line, "AUTH=", 5)) { size_t llen; unsigned short mechbit; line += 5; wordlen -= 5; /* Test the word for a matching authentication mechanism */ mechbit = Curl_sasl_decode_mech(line, wordlen, &llen); if(mechbit && llen == wordlen) imapc->sasl.authmechs |= mechbit; } line += wordlen; } } else if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) { /* PREAUTH is not compatible with STARTTLS. */ if(imapcode == IMAP_RESP_OK && imapc->tls_supported && !imapc->preauth) { /* Switch to TLS connection now */ result = imap_perform_starttls(data); } else if(data->set.use_ssl <= CURLUSESSL_TRY) result = imap_perform_authentication(data, conn); else { failf(data, "STARTTLS not available."); result = CURLE_USE_SSL_FAILED; } } else result = imap_perform_authentication(data, conn); return result; } /* For STARTTLS responses */ static CURLcode imap_state_starttls_resp(struct Curl_easy *data, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; (void)instate; /* no use for this yet */ /* Pipelining in response is forbidden. */ if(data->conn->proto.imapc.pp.cache_size) return CURLE_WEIRD_SERVER_REPLY; if(imapcode != IMAP_RESP_OK) { if(data->set.use_ssl != CURLUSESSL_TRY) { failf(data, "STARTTLS denied"); result = CURLE_USE_SSL_FAILED; } else result = imap_perform_authentication(data, conn); } else result = imap_perform_upgrade_tls(data, conn); return result; } /* For SASL authentication responses */ static CURLcode imap_state_auth_resp(struct Curl_easy *data, struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; saslprogress progress; (void)instate; /* no use for this yet */ result = Curl_sasl_continue(&imapc->sasl, data, imapcode, &progress); if(!result) switch(progress) { case SASL_DONE: state(data, IMAP_STOP); /* Authenticated */ break; case SASL_IDLE: /* No mechanism left after cancellation */ if((!imapc->login_disabled) && (imapc->preftype & IMAP_TYPE_CLEARTEXT)) /* Perform clear text authentication */ result = imap_perform_login(data, conn); else { failf(data, "Authentication cancelled"); result = CURLE_LOGIN_DENIED; } break; default: break; } return result; } /* For LOGIN responses */ static CURLcode imap_state_login_resp(struct Curl_easy *data, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; (void)instate; /* no use for this yet */ if(imapcode != IMAP_RESP_OK) { failf(data, "Access denied. %c", imapcode); result = CURLE_LOGIN_DENIED; } else /* End of connect phase */ state(data, IMAP_STOP); return result; } /* For LIST and SEARCH responses */ static CURLcode imap_state_listsearch_resp(struct Curl_easy *data, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; char *line = data->state.buffer; size_t len = strlen(line); (void)instate; /* No use for this yet */ if(imapcode == '*') { /* Temporarily add the LF character back and send as body to the client */ line[len] = '\n'; result = Curl_client_write(data, CLIENTWRITE_BODY, line, len + 1); line[len] = '\0'; } else if(imapcode != IMAP_RESP_OK) result = CURLE_QUOTE_ERROR; else /* End of DO phase */ state(data, IMAP_STOP); return result; } /* For SELECT responses */ static CURLcode imap_state_select_resp(struct Curl_easy *data, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; struct IMAP *imap = data->req.p.imap; struct imap_conn *imapc = &conn->proto.imapc; const char *line = data->state.buffer; (void)instate; /* no use for this yet */ if(imapcode == '*') { /* See if this is an UIDVALIDITY response */ char tmp[20]; if(sscanf(line + 2, "OK [UIDVALIDITY %19[0123456789]]", tmp) == 1) { Curl_safefree(imapc->mailbox_uidvalidity); imapc->mailbox_uidvalidity = strdup(tmp); } } else if(imapcode == IMAP_RESP_OK) { /* Check if the UIDVALIDITY has been specified and matches */ if(imap->uidvalidity && imapc->mailbox_uidvalidity && !strcasecompare(imap->uidvalidity, imapc->mailbox_uidvalidity)) { failf(data, "Mailbox UIDVALIDITY has changed"); result = CURLE_REMOTE_FILE_NOT_FOUND; } else { /* Note the currently opened mailbox on this connection */ imapc->mailbox = strdup(imap->mailbox); if(imap->custom) result = imap_perform_list(data); else if(imap->query) result = imap_perform_search(data); else result = imap_perform_fetch(data); } } else { failf(data, "Select failed"); result = CURLE_LOGIN_DENIED; } return result; } /* For the (first line of the) FETCH responses */ static CURLcode imap_state_fetch_resp(struct Curl_easy *data, struct connectdata *conn, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; struct pingpong *pp = &imapc->pp; const char *ptr = data->state.buffer; bool parsed = FALSE; curl_off_t size = 0; (void)instate; /* no use for this yet */ if(imapcode != '*') { Curl_pgrsSetDownloadSize(data, -1); state(data, IMAP_STOP); return CURLE_REMOTE_FILE_NOT_FOUND; } /* Something like this is received "* 1 FETCH (BODY[TEXT] {2021}\r" so parse the continuation data contained within the curly brackets */ while(*ptr && (*ptr != '{')) ptr++; if(*ptr == '{') { char *endptr; if(!curlx_strtoofft(ptr + 1, &endptr, 10, &size)) { if(endptr - ptr > 1 && endptr[0] == '}' && endptr[1] == '\r' && endptr[2] == '\0') parsed = TRUE; } } if(parsed) { infof(data, "Found %" CURL_FORMAT_CURL_OFF_T " bytes to download", size); Curl_pgrsSetDownloadSize(data, size); if(pp->cache) { /* At this point there is a bunch of data in the header "cache" that is actually body content, send it as body and then skip it. Do note that there may even be additional "headers" after the body. */ size_t chunk = pp->cache_size; if(chunk > (size_t)size) /* The conversion from curl_off_t to size_t is always fine here */ chunk = (size_t)size; if(!chunk) { /* no size, we're done with the data */ state(data, IMAP_STOP); return CURLE_OK; } result = Curl_client_write(data, CLIENTWRITE_BODY, pp->cache, chunk); if(result) return result; data->req.bytecount += chunk; infof(data, "Written %zu bytes, %" CURL_FORMAT_CURL_OFF_TU " bytes are left for transfer", chunk, size - chunk); /* Have we used the entire cache or just part of it?*/ if(pp->cache_size > chunk) { /* Only part of it so shrink the cache to fit the trailing data */ memmove(pp->cache, pp->cache + chunk, pp->cache_size - chunk); pp->cache_size -= chunk; } else { /* Free the cache */ Curl_safefree(pp->cache); /* Reset the cache size */ pp->cache_size = 0; } } if(data->req.bytecount == size) /* The entire data is already transferred! */ Curl_setup_transfer(data, -1, -1, FALSE, -1); else { /* IMAP download */ data->req.maxdownload = size; /* force a recv/send check of this connection, as the data might've been read off the socket already */ data->conn->cselect_bits = CURL_CSELECT_IN; Curl_setup_transfer(data, FIRSTSOCKET, size, FALSE, -1); } } else { /* We don't know how to parse this line */ failf(data, "Failed to parse FETCH response."); result = CURLE_WEIRD_SERVER_REPLY; } /* End of DO phase */ state(data, IMAP_STOP); return result; } /* For final FETCH responses performed after the download */ static CURLcode imap_state_fetch_final_resp(struct Curl_easy *data, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; (void)instate; /* No use for this yet */ if(imapcode != IMAP_RESP_OK) result = CURLE_WEIRD_SERVER_REPLY; else /* End of DONE phase */ state(data, IMAP_STOP); return result; } /* For APPEND responses */ static CURLcode imap_state_append_resp(struct Curl_easy *data, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; (void)instate; /* No use for this yet */ if(imapcode != '+') { result = CURLE_UPLOAD_FAILED; } else { /* Set the progress upload size */ Curl_pgrsSetUploadSize(data, data->state.infilesize); /* IMAP upload */ Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET); /* End of DO phase */ state(data, IMAP_STOP); } return result; } /* For final APPEND responses performed after the upload */ static CURLcode imap_state_append_final_resp(struct Curl_easy *data, int imapcode, imapstate instate) { CURLcode result = CURLE_OK; (void)instate; /* No use for this yet */ if(imapcode != IMAP_RESP_OK) result = CURLE_UPLOAD_FAILED; else /* End of DONE phase */ state(data, IMAP_STOP); return result; } static CURLcode imap_statemachine(struct Curl_easy *data, struct connectdata *conn) { CURLcode result = CURLE_OK; curl_socket_t sock = conn->sock[FIRSTSOCKET]; int imapcode; struct imap_conn *imapc = &conn->proto.imapc; struct pingpong *pp = &imapc->pp; size_t nread = 0; (void)data; /* Busy upgrading the connection; right now all I/O is SSL/TLS, not IMAP */ if(imapc->state == IMAP_UPGRADETLS) return imap_perform_upgrade_tls(data, conn); /* Flush any data that needs to be sent */ if(pp->sendleft) return Curl_pp_flushsend(data, pp); do { /* Read the response from the server */ result = Curl_pp_readresp(data, sock, pp, &imapcode, &nread); if(result) return result; /* Was there an error parsing the response line? */ if(imapcode == -1) return CURLE_WEIRD_SERVER_REPLY; if(!imapcode) break; /* We have now received a full IMAP server response */ switch(imapc->state) { case IMAP_SERVERGREET: result = imap_state_servergreet_resp(data, imapcode, imapc->state); break; case IMAP_CAPABILITY: result = imap_state_capability_resp(data, imapcode, imapc->state); break; case IMAP_STARTTLS: result = imap_state_starttls_resp(data, imapcode, imapc->state); break; case IMAP_AUTHENTICATE: result = imap_state_auth_resp(data, conn, imapcode, imapc->state); break; case IMAP_LOGIN: result = imap_state_login_resp(data, imapcode, imapc->state); break; case IMAP_LIST: case IMAP_SEARCH: result = imap_state_listsearch_resp(data, imapcode, imapc->state); break; case IMAP_SELECT: result = imap_state_select_resp(data, imapcode, imapc->state); break; case IMAP_FETCH: result = imap_state_fetch_resp(data, conn, imapcode, imapc->state); break; case IMAP_FETCH_FINAL: result = imap_state_fetch_final_resp(data, imapcode, imapc->state); break; case IMAP_APPEND: result = imap_state_append_resp(data, imapcode, imapc->state); break; case IMAP_APPEND_FINAL: result = imap_state_append_final_resp(data, imapcode, imapc->state); break; case IMAP_LOGOUT: /* fallthrough, just stop! */ default: /* internal error */ state(data, IMAP_STOP); break; } } while(!result && imapc->state != IMAP_STOP && Curl_pp_moredata(pp)); return result; } /* Called repeatedly until done from multi.c */ static CURLcode imap_multi_statemach(struct Curl_easy *data, bool *done) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; struct imap_conn *imapc = &conn->proto.imapc; if((conn->handler->flags & PROTOPT_SSL) && !imapc->ssldone) { result = Curl_ssl_connect_nonblocking(data, conn, FALSE, FIRSTSOCKET, &imapc->ssldone); if(result || !imapc->ssldone) return result; } result = Curl_pp_statemach(data, &imapc->pp, FALSE, FALSE); *done = (imapc->state == IMAP_STOP) ? TRUE : FALSE; return result; } static CURLcode imap_block_statemach(struct Curl_easy *data, struct connectdata *conn, bool disconnecting) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; while(imapc->state != IMAP_STOP && !result) result = Curl_pp_statemach(data, &imapc->pp, TRUE, disconnecting); return result; } /* Allocate and initialize the struct IMAP for the current Curl_easy if required */ static CURLcode imap_init(struct Curl_easy *data) { CURLcode result = CURLE_OK; struct IMAP *imap; imap = data->req.p.imap = calloc(sizeof(struct IMAP), 1); if(!imap) result = CURLE_OUT_OF_MEMORY; return result; } /* For the IMAP "protocol connect" and "doing" phases only */ static int imap_getsock(struct Curl_easy *data, struct connectdata *conn, curl_socket_t *socks) { return Curl_pp_getsock(data, &conn->proto.imapc.pp, socks); } /*********************************************************************** * * imap_connect() * * This function should do everything that is to be considered a part of the * connection phase. * * The variable 'done' points to will be TRUE if the protocol-layer connect * phase is done when this function returns, or FALSE if not. */ static CURLcode imap_connect(struct Curl_easy *data, bool *done) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; struct imap_conn *imapc = &conn->proto.imapc; struct pingpong *pp = &imapc->pp; *done = FALSE; /* default to not done yet */ /* We always support persistent connections in IMAP */ connkeep(conn, "IMAP default"); PINGPONG_SETUP(pp, imap_statemachine, imap_endofresp); /* Set the default preferred authentication type and mechanism */ imapc->preftype = IMAP_TYPE_ANY; Curl_sasl_init(&imapc->sasl, data, &saslimap); Curl_dyn_init(&imapc->dyn, DYN_IMAP_CMD); /* Initialise the pingpong layer */ Curl_pp_setup(pp); Curl_pp_init(data, pp); /* Parse the URL options */ result = imap_parse_url_options(conn); if(result) return result; /* Start off waiting for the server greeting response */ state(data, IMAP_SERVERGREET); /* Start off with an response id of '*' */ strcpy(imapc->resptag, "*"); result = imap_multi_statemach(data, done); return result; } /*********************************************************************** * * imap_done() * * The DONE function. This does what needs to be done after a single DO has * performed. * * Input argument is already checked for validity. */ static CURLcode imap_done(struct Curl_easy *data, CURLcode status, bool premature) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; struct IMAP *imap = data->req.p.imap; (void)premature; if(!imap) return CURLE_OK; if(status) { connclose(conn, "IMAP done with bad status"); /* marked for closure */ result = status; /* use the already set error code */ } else if(!data->set.connect_only && !imap->custom && (imap->uid || imap->mindex || data->set.upload || data->set.mimepost.kind != MIMEKIND_NONE)) { /* Handle responses after FETCH or APPEND transfer has finished */ if(!data->set.upload && data->set.mimepost.kind == MIMEKIND_NONE) state(data, IMAP_FETCH_FINAL); else { /* End the APPEND command first by sending an empty line */ result = Curl_pp_sendf(data, &conn->proto.imapc.pp, "%s", ""); if(!result) state(data, IMAP_APPEND_FINAL); } /* Run the state-machine */ if(!result) result = imap_block_statemach(data, conn, FALSE); } /* Cleanup our per-request based variables */ Curl_safefree(imap->mailbox); Curl_safefree(imap->uidvalidity); Curl_safefree(imap->uid); Curl_safefree(imap->mindex); Curl_safefree(imap->section); Curl_safefree(imap->partial); Curl_safefree(imap->query); Curl_safefree(imap->custom); Curl_safefree(imap->custom_params); /* Clear the transfer mode for the next request */ imap->transfer = PPTRANSFER_BODY; return result; } /*********************************************************************** * * imap_perform() * * This is the actual DO function for IMAP. Fetch or append a message, or do * other things according to the options previously setup. */ static CURLcode imap_perform(struct Curl_easy *data, bool *connected, bool *dophase_done) { /* This is IMAP and no proxy */ CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; struct IMAP *imap = data->req.p.imap; struct imap_conn *imapc = &conn->proto.imapc; bool selected = FALSE; DEBUGF(infof(data, "DO phase starts")); if(data->set.opt_no_body) { /* Requested no body means no transfer */ imap->transfer = PPTRANSFER_INFO; } *dophase_done = FALSE; /* not done yet */ /* Determine if the requested mailbox (with the same UIDVALIDITY if set) has already been selected on this connection */ if(imap->mailbox && imapc->mailbox && strcasecompare(imap->mailbox, imapc->mailbox) && (!imap->uidvalidity || !imapc->mailbox_uidvalidity || strcasecompare(imap->uidvalidity, imapc->mailbox_uidvalidity))) selected = TRUE; /* Start the first command in the DO phase */ if(data->set.upload || data->set.mimepost.kind != MIMEKIND_NONE) /* APPEND can be executed directly */ result = imap_perform_append(data); else if(imap->custom && (selected || !imap->mailbox)) /* Custom command using the same mailbox or no mailbox */ result = imap_perform_list(data); else if(!imap->custom && selected && (imap->uid || imap->mindex)) /* FETCH from the same mailbox */ result = imap_perform_fetch(data); else if(!imap->custom && selected && imap->query) /* SEARCH the current mailbox */ result = imap_perform_search(data); else if(imap->mailbox && !selected && (imap->custom || imap->uid || imap->mindex || imap->query)) /* SELECT the mailbox */ result = imap_perform_select(data); else /* LIST */ result = imap_perform_list(data); if(result) return result; /* Run the state-machine */ result = imap_multi_statemach(data, dophase_done); *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) DEBUGF(infof(data, "DO phase is complete")); return result; } /*********************************************************************** * * imap_do() * * This function is registered as 'curl_do' function. It decodes the path * parts etc as a wrapper to the actual DO function (imap_perform). * * The input argument is already checked for validity. */ static CURLcode imap_do(struct Curl_easy *data, bool *done) { CURLcode result = CURLE_OK; *done = FALSE; /* default to false */ /* Parse the URL path */ result = imap_parse_url_path(data); if(result) return result; /* Parse the custom request */ result = imap_parse_custom_request(data); if(result) return result; result = imap_regular_transfer(data, done); return result; } /*********************************************************************** * * imap_disconnect() * * Disconnect from an IMAP server. Cleanup protocol-specific per-connection * resources. BLOCKING. */ static CURLcode imap_disconnect(struct Curl_easy *data, struct connectdata *conn, bool dead_connection) { struct imap_conn *imapc = &conn->proto.imapc; (void)data; /* We cannot send quit unconditionally. If this connection is stale or bad in any way, sending quit and waiting around here will make the disconnect wait in vain and cause more problems than we need to. */ /* The IMAP session may or may not have been allocated/setup at this point! */ if(!dead_connection && conn->bits.protoconnstart) { if(!imap_perform_logout(data)) (void)imap_block_statemach(data, conn, TRUE); /* ignore errors */ } /* Disconnect from the server */ Curl_pp_disconnect(&imapc->pp); Curl_dyn_free(&imapc->dyn); /* Cleanup the SASL module */ Curl_sasl_cleanup(conn, imapc->sasl.authused); /* Cleanup our connection based variables */ Curl_safefree(imapc->mailbox); Curl_safefree(imapc->mailbox_uidvalidity); return CURLE_OK; } /* Call this when the DO phase has completed */ static CURLcode imap_dophase_done(struct Curl_easy *data, bool connected) { struct IMAP *imap = data->req.p.imap; (void)connected; if(imap->transfer != PPTRANSFER_BODY) /* no data to transfer */ Curl_setup_transfer(data, -1, -1, FALSE, -1); return CURLE_OK; } /* Called from multi.c while DOing */ static CURLcode imap_doing(struct Curl_easy *data, bool *dophase_done) { CURLcode result = imap_multi_statemach(data, dophase_done); if(result) DEBUGF(infof(data, "DO phase failed")); else if(*dophase_done) { result = imap_dophase_done(data, FALSE /* not connected */); DEBUGF(infof(data, "DO phase is complete")); } return result; } /*********************************************************************** * * imap_regular_transfer() * * The input argument is already checked for validity. * * Performs all commands done before a regular transfer between a local and a * remote host. */ static CURLcode imap_regular_transfer(struct Curl_easy *data, bool *dophase_done) { CURLcode result = CURLE_OK; bool connected = FALSE; /* Make sure size is unknown at this point */ data->req.size = -1; /* Set the progress data */ Curl_pgrsSetUploadCounter(data, 0); Curl_pgrsSetDownloadCounter(data, 0); Curl_pgrsSetUploadSize(data, -1); Curl_pgrsSetDownloadSize(data, -1); /* Carry out the perform */ result = imap_perform(data, &connected, dophase_done); /* Perform post DO phase operations if necessary */ if(!result && *dophase_done) result = imap_dophase_done(data, connected); return result; } static CURLcode imap_setup_connection(struct Curl_easy *data, struct connectdata *conn) { /* Initialise the IMAP layer */ CURLcode result = imap_init(data); if(result) return result; /* Clear the TLS upgraded flag */ conn->bits.tls_upgraded = FALSE; return CURLE_OK; } /*********************************************************************** * * imap_sendf() * * Sends the formatted string as an IMAP command to the server. * * Designed to never block. */ static CURLcode imap_sendf(struct Curl_easy *data, const char *fmt, ...) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &data->conn->proto.imapc; DEBUGASSERT(fmt); /* Calculate the tag based on the connection ID and command ID */ msnprintf(imapc->resptag, sizeof(imapc->resptag), "%c%03d", 'A' + curlx_sltosi(data->conn->connection_id % 26), (++imapc->cmdid)%1000); /* start with a blank buffer */ Curl_dyn_reset(&imapc->dyn); /* append tag + space + fmt */ result = Curl_dyn_addf(&imapc->dyn, "%s %s", imapc->resptag, fmt); if(!result) { va_list ap; va_start(ap, fmt); result = Curl_pp_vsendf(data, &imapc->pp, Curl_dyn_ptr(&imapc->dyn), ap); va_end(ap); } return result; } /*********************************************************************** * * imap_atom() * * Checks the input string for characters that need escaping and returns an * atom ready for sending to the server. * * The returned string needs to be freed. * */ static char *imap_atom(const char *str, bool escape_only) { /* !checksrc! disable PARENBRACE 1 */ const char atom_specials[] = "(){ %*]"; const char *p1; char *p2; size_t backsp_count = 0; size_t quote_count = 0; bool others_exists = FALSE; size_t newlen = 0; char *newstr = NULL; if(!str) return NULL; /* Look for "atom-specials", counting the backslash and quote characters as these will need escaping */ p1 = str; while(*p1) { if(*p1 == '\\') backsp_count++; else if(*p1 == '"') quote_count++; else if(!escape_only) { const char *p3 = atom_specials; while(*p3 && !others_exists) { if(*p1 == *p3) others_exists = TRUE; p3++; } } p1++; } /* Does the input contain any "atom-special" characters? */ if(!backsp_count && !quote_count && !others_exists) return strdup(str); /* Calculate the new string length */ newlen = strlen(str) + backsp_count + quote_count + (escape_only ? 0 : 2); /* Allocate the new string */ newstr = (char *) malloc((newlen + 1) * sizeof(char)); if(!newstr) return NULL; /* Surround the string in quotes if necessary */ p2 = newstr; if(!escape_only) { newstr[0] = '"'; newstr[newlen - 1] = '"'; p2++; } /* Copy the string, escaping backslash and quote characters along the way */ p1 = str; while(*p1) { if(*p1 == '\\' || *p1 == '"') { *p2 = '\\'; p2++; } *p2 = *p1; p1++; p2++; } /* Terminate the string */ newstr[newlen] = '\0'; return newstr; } /*********************************************************************** * * imap_is_bchar() * * Portable test of whether the specified char is a "bchar" as defined in the * grammar of RFC-5092. */ static bool imap_is_bchar(char ch) { switch(ch) { /* bchar */ case ':': case '@': case '/': /* bchar -> achar */ case '&': case '=': /* bchar -> achar -> uchar -> unreserved */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '-': case '.': case '_': case '~': /* bchar -> achar -> uchar -> sub-delims-sh */ case '!': case '$': case '\'': case '(': case ')': case '*': case '+': case ',': /* bchar -> achar -> uchar -> pct-encoded */ case '%': /* HEXDIG chars are already included above */ return true; default: return false; } } /*********************************************************************** * * imap_parse_url_options() * * Parse the URL login options. */ static CURLcode imap_parse_url_options(struct connectdata *conn) { CURLcode result = CURLE_OK; struct imap_conn *imapc = &conn->proto.imapc; const char *ptr = conn->options; while(!result && ptr && *ptr) { const char *key = ptr; const char *value; while(*ptr && *ptr != '=') ptr++; value = ptr + 1; while(*ptr && *ptr != ';') ptr++; if(strncasecompare(key, "AUTH=", 5)) result = Curl_sasl_parse_url_auth_option(&imapc->sasl, value, ptr - value); else result = CURLE_URL_MALFORMAT; if(*ptr == ';') ptr++; } switch(imapc->sasl.prefmech) { case SASL_AUTH_NONE: imapc->preftype = IMAP_TYPE_NONE; break; case SASL_AUTH_DEFAULT: imapc->preftype = IMAP_TYPE_ANY; break; default: imapc->preftype = IMAP_TYPE_SASL; break; } return result; } /*********************************************************************** * * imap_parse_url_path() * * Parse the URL path into separate path components. * */ static CURLcode imap_parse_url_path(struct Curl_easy *data) { /* The imap struct is already initialised in imap_connect() */ CURLcode result = CURLE_OK; struct IMAP *imap = data->req.p.imap; const char *begin = &data->state.up.path[1]; /* skip leading slash */ const char *ptr = begin; /* See how much of the URL is a valid path and decode it */ while(imap_is_bchar(*ptr)) ptr++; if(ptr != begin) { /* Remove the trailing slash if present */ const char *end = ptr; if(end > begin && end[-1] == '/') end--; result = Curl_urldecode(data, begin, end - begin, &imap->mailbox, NULL, REJECT_CTRL); if(result) return result; } else imap->mailbox = NULL; /* There can be any number of parameters in the form ";NAME=VALUE" */ while(*ptr == ';') { char *name; char *value; size_t valuelen; /* Find the length of the name parameter */ begin = ++ptr; while(*ptr && *ptr != '=') ptr++; if(!*ptr) return CURLE_URL_MALFORMAT; /* Decode the name parameter */ result = Curl_urldecode(data, begin, ptr - begin, &name, NULL, REJECT_CTRL); if(result) return result; /* Find the length of the value parameter */ begin = ++ptr; while(imap_is_bchar(*ptr)) ptr++; /* Decode the value parameter */ result = Curl_urldecode(data, begin, ptr - begin, &value, &valuelen, REJECT_CTRL); if(result) { free(name); return result; } DEBUGF(infof(data, "IMAP URL parameter '%s' = '%s'", name, value)); /* Process the known hierarchical parameters (UIDVALIDITY, UID, SECTION and PARTIAL) stripping of the trailing slash character if it is present. Note: Unknown parameters trigger a URL_MALFORMAT error. */ if(strcasecompare(name, "UIDVALIDITY") && !imap->uidvalidity) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->uidvalidity = value; value = NULL; } else if(strcasecompare(name, "UID") && !imap->uid) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->uid = value; value = NULL; } else if(strcasecompare(name, "MAILINDEX") && !imap->mindex) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->mindex = value; value = NULL; } else if(strcasecompare(name, "SECTION") && !imap->section) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->section = value; value = NULL; } else if(strcasecompare(name, "PARTIAL") && !imap->partial) { if(valuelen > 0 && value[valuelen - 1] == '/') value[valuelen - 1] = '\0'; imap->partial = value; value = NULL; } else { free(name); free(value); return CURLE_URL_MALFORMAT; } free(name); free(value); } /* Does the URL contain a query parameter? Only valid when we have a mailbox and no UID as per RFC-5092 */ if(imap->mailbox && !imap->uid && !imap->mindex) { /* Get the query parameter, URL decoded */ (void)curl_url_get(data->state.uh, CURLUPART_QUERY, &imap->query, CURLU_URLDECODE); } /* Any extra stuff at the end of the URL is an error */ if(*ptr) return CURLE_URL_MALFORMAT; return CURLE_OK; } /*********************************************************************** * * imap_parse_custom_request() * * Parse the custom request. */ static CURLcode imap_parse_custom_request(struct Curl_easy *data) { CURLcode result = CURLE_OK; struct IMAP *imap = data->req.p.imap; const char *custom = data->set.str[STRING_CUSTOMREQUEST]; if(custom) { /* URL decode the custom request */ result = Curl_urldecode(data, custom, 0, &imap->custom, NULL, REJECT_CTRL); /* Extract the parameters if specified */ if(!result) { const char *params = imap->custom; while(*params && *params != ' ') params++; if(*params) { imap->custom_params = strdup(params); imap->custom[params - imap->custom] = '\0'; if(!imap->custom_params) result = CURLE_OUT_OF_MEMORY; } } } return result; } #endif /* CURL_DISABLE_IMAP */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/idn_win32.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * IDN conversions using Windows kernel32 and normaliz libraries. */ #include "curl_setup.h" #ifdef USE_WIN32_IDN #include "curl_multibyte.h" #include "curl_memory.h" #include "warnless.h" /* The last #include file should be: */ #include "memdebug.h" #ifdef WANT_IDN_PROTOTYPES # if defined(_SAL_VERSION) WINNORMALIZEAPI int WINAPI IdnToAscii(_In_ DWORD dwFlags, _In_reads_(cchUnicodeChar) LPCWSTR lpUnicodeCharStr, _In_ int cchUnicodeChar, _Out_writes_opt_(cchASCIIChar) LPWSTR lpASCIICharStr, _In_ int cchASCIIChar); WINNORMALIZEAPI int WINAPI IdnToUnicode(_In_ DWORD dwFlags, _In_reads_(cchASCIIChar) LPCWSTR lpASCIICharStr, _In_ int cchASCIIChar, _Out_writes_opt_(cchUnicodeChar) LPWSTR lpUnicodeCharStr, _In_ int cchUnicodeChar); # else WINBASEAPI int WINAPI IdnToAscii(DWORD dwFlags, const WCHAR *lpUnicodeCharStr, int cchUnicodeChar, WCHAR *lpASCIICharStr, int cchASCIIChar); WINBASEAPI int WINAPI IdnToUnicode(DWORD dwFlags, const WCHAR *lpASCIICharStr, int cchASCIIChar, WCHAR *lpUnicodeCharStr, int cchUnicodeChar); # endif #endif #define IDN_MAX_LENGTH 255 bool curl_win32_idn_to_ascii(const char *in, char **out); bool curl_win32_ascii_to_idn(const char *in, char **out); bool curl_win32_idn_to_ascii(const char *in, char **out) { bool success = FALSE; wchar_t *in_w = curlx_convert_UTF8_to_wchar(in); if(in_w) { wchar_t punycode[IDN_MAX_LENGTH]; int chars = IdnToAscii(0, in_w, -1, punycode, IDN_MAX_LENGTH); free(in_w); if(chars) { *out = curlx_convert_wchar_to_UTF8(punycode); if(*out) success = TRUE; } } return success; } bool curl_win32_ascii_to_idn(const char *in, char **out) { bool success = FALSE; wchar_t *in_w = curlx_convert_UTF8_to_wchar(in); if(in_w) { size_t in_len = wcslen(in_w) + 1; wchar_t unicode[IDN_MAX_LENGTH]; int chars = IdnToUnicode(0, in_w, curlx_uztosi(in_len), unicode, IDN_MAX_LENGTH); free(in_w); if(chars) { *out = curlx_convert_wchar_to_UTF8(unicode); if(*out) success = TRUE; } } return success; } #endif /* USE_WIN32_IDN */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curlx.h
#ifndef HEADER_CURL_CURLX_H #define HEADER_CURL_CURLX_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Defines protos and includes all header files that provide the curlx_* * functions. The curlx_* functions are not part of the libcurl API, but are * stand-alone functions whose sources can be built and linked by apps if need * be. */ #include <curl/mprintf.h> /* this is still a public header file that provides the curl_mprintf() functions while they still are offered publicly. They will be made library- private one day */ #include "strcase.h" /* "strcase.h" provides the strcasecompare protos */ #include "strtoofft.h" /* "strtoofft.h" provides this function: curlx_strtoofft(), returns a curl_off_t number from a given string. */ #include "nonblock.h" /* "nonblock.h" provides curlx_nonblock() */ #include "warnless.h" /* "warnless.h" provides functions: curlx_ultous() curlx_ultouc() curlx_uztosi() */ #include "curl_multibyte.h" /* "curl_multibyte.h" provides these functions and macros: curlx_convert_UTF8_to_wchar() curlx_convert_wchar_to_UTF8() curlx_convert_UTF8_to_tchar() curlx_convert_tchar_to_UTF8() curlx_unicodefree() */ #include "version_win32.h" /* "version_win32.h" provides curlx_verify_windows_version() */ /* Now setup curlx_ * names for the functions that are to become curlx_ and be removed from a future libcurl official API: curlx_getenv curlx_mprintf (and its variations) curlx_strcasecompare curlx_strncasecompare */ #define curlx_getenv curl_getenv #define curlx_mvsnprintf curl_mvsnprintf #define curlx_msnprintf curl_msnprintf #define curlx_maprintf curl_maprintf #define curlx_mvaprintf curl_mvaprintf #define curlx_msprintf curl_msprintf #define curlx_mprintf curl_mprintf #define curlx_mfprintf curl_mfprintf #define curlx_mvsprintf curl_mvsprintf #define curlx_mvprintf curl_mvprintf #define curlx_mvfprintf curl_mvfprintf #ifdef ENABLE_CURLX_PRINTF /* If this define is set, we define all "standard" printf() functions to use the curlx_* version instead. It makes the source code transparent and easier to understand/patch. Undefine them first. */ # undef printf # undef fprintf # undef sprintf # undef msnprintf # undef vprintf # undef vfprintf # undef vsprintf # undef mvsnprintf # undef aprintf # undef vaprintf # define printf curlx_mprintf # define fprintf curlx_mfprintf # define sprintf curlx_msprintf # define msnprintf curlx_msnprintf # define vprintf curlx_mvprintf # define vfprintf curlx_mvfprintf # define mvsnprintf curlx_mvsnprintf # define aprintf curlx_maprintf # define vaprintf curlx_mvaprintf #endif /* ENABLE_CURLX_PRINTF */ #endif /* HEADER_CURL_CURLX_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_gethostname.h
#ifndef HEADER_CURL_GETHOSTNAME_H #define HEADER_CURL_GETHOSTNAME_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* Hostname buffer size */ #define HOSTNAME_MAX 1024 /* This returns the local machine's un-qualified hostname */ int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen); #endif /* HEADER_CURL_GETHOSTNAME_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/c-hyper.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include <hyper.h> #include "urldata.h" #include "sendf.h" #include "transfer.h" #include "multiif.h" #include "progress.h" #include "content_encoding.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" size_t Curl_hyper_recv(void *userp, hyper_context *ctx, uint8_t *buf, size_t buflen) { struct Curl_easy *data = userp; struct connectdata *conn = data->conn; CURLcode result; ssize_t nread; DEBUGASSERT(conn); (void)ctx; result = Curl_read(data, conn->sockfd, (char *)buf, buflen, &nread); if(result == CURLE_AGAIN) { /* would block, register interest */ if(data->hyp.read_waker) hyper_waker_free(data->hyp.read_waker); data->hyp.read_waker = hyper_context_waker(ctx); if(!data->hyp.read_waker) { failf(data, "Couldn't make the read hyper_context_waker"); return HYPER_IO_ERROR; } return HYPER_IO_PENDING; } else if(result) { failf(data, "Curl_read failed"); return HYPER_IO_ERROR; } return (size_t)nread; } size_t Curl_hyper_send(void *userp, hyper_context *ctx, const uint8_t *buf, size_t buflen) { struct Curl_easy *data = userp; struct connectdata *conn = data->conn; CURLcode result; ssize_t nwrote; result = Curl_write(data, conn->sockfd, (void *)buf, buflen, &nwrote); if(result == CURLE_AGAIN) { /* would block, register interest */ if(data->hyp.write_waker) hyper_waker_free(data->hyp.write_waker); data->hyp.write_waker = hyper_context_waker(ctx); if(!data->hyp.write_waker) { failf(data, "Couldn't make the write hyper_context_waker"); return HYPER_IO_ERROR; } return HYPER_IO_PENDING; } else if(result) { failf(data, "Curl_write failed"); return HYPER_IO_ERROR; } return (size_t)nwrote; } static int hyper_each_header(void *userdata, const uint8_t *name, size_t name_len, const uint8_t *value, size_t value_len) { struct Curl_easy *data = (struct Curl_easy *)userdata; size_t len; char *headp; CURLcode result; int writetype; if(name_len + value_len + 2 > CURL_MAX_HTTP_HEADER) { failf(data, "Too long response header"); data->state.hresult = CURLE_OUT_OF_MEMORY; return HYPER_ITER_BREAK; } if(!data->req.bytecount) Curl_pgrsTime(data, TIMER_STARTTRANSFER); Curl_dyn_reset(&data->state.headerb); if(name_len) { if(Curl_dyn_addf(&data->state.headerb, "%.*s: %.*s\r\n", (int) name_len, name, (int) value_len, value)) return HYPER_ITER_BREAK; } else { if(Curl_dyn_add(&data->state.headerb, "\r\n")) return HYPER_ITER_BREAK; } len = Curl_dyn_len(&data->state.headerb); headp = Curl_dyn_ptr(&data->state.headerb); result = Curl_http_header(data, data->conn, headp); if(result) { data->state.hresult = result; return HYPER_ITER_BREAK; } Curl_debug(data, CURLINFO_HEADER_IN, headp, len); if(!data->state.hconnect || !data->set.suppress_connect_headers) { writetype = CLIENTWRITE_HEADER; if(data->set.include_header) writetype |= CLIENTWRITE_BODY; result = Curl_client_write(data, writetype, headp, len); if(result) { data->state.hresult = CURLE_ABORTED_BY_CALLBACK; return HYPER_ITER_BREAK; } } data->info.header_size += (long)len; data->req.headerbytecount += (long)len; return HYPER_ITER_CONTINUE; } static int hyper_body_chunk(void *userdata, const hyper_buf *chunk) { char *buf = (char *)hyper_buf_bytes(chunk); size_t len = hyper_buf_len(chunk); struct Curl_easy *data = (struct Curl_easy *)userdata; struct SingleRequest *k = &data->req; CURLcode result = CURLE_OK; if(0 == k->bodywrites++) { bool done = FALSE; #if defined(USE_NTLM) struct connectdata *conn = data->conn; if(conn->bits.close && (((data->req.httpcode == 401) && (conn->http_ntlm_state == NTLMSTATE_TYPE2)) || ((data->req.httpcode == 407) && (conn->proxy_ntlm_state == NTLMSTATE_TYPE2)))) { infof(data, "Connection closed while negotiating NTLM"); data->state.authproblem = TRUE; Curl_safefree(data->req.newurl); } #endif if(data->state.expect100header) { Curl_expire_done(data, EXPIRE_100_TIMEOUT); if(data->req.httpcode < 400) { k->exp100 = EXP100_SEND_DATA; if(data->hyp.exp100_waker) { hyper_waker_wake(data->hyp.exp100_waker); data->hyp.exp100_waker = NULL; } } else { /* >= 4xx */ k->exp100 = EXP100_FAILED; } } if(data->state.hconnect && (data->req.httpcode/100 != 2) && data->state.authproxy.done) { done = TRUE; result = CURLE_OK; } else result = Curl_http_firstwrite(data, data->conn, &done); if(result || done) { infof(data, "Return early from hyper_body_chunk"); data->state.hresult = result; return HYPER_ITER_BREAK; } } if(k->ignorebody) return HYPER_ITER_CONTINUE; if(0 == len) return HYPER_ITER_CONTINUE; Curl_debug(data, CURLINFO_DATA_IN, buf, len); if(!data->set.http_ce_skip && k->writer_stack) /* content-encoded data */ result = Curl_unencode_write(data, k->writer_stack, buf, len); else result = Curl_client_write(data, CLIENTWRITE_BODY, buf, len); if(result) { data->state.hresult = result; return HYPER_ITER_BREAK; } data->req.bytecount += len; Curl_pgrsSetDownloadCounter(data, data->req.bytecount); return HYPER_ITER_CONTINUE; } /* * Hyper does not consider the status line, the first line in a HTTP/1 * response, to be a header. The libcurl API does. This function sends the * status line in the header callback. */ static CURLcode status_line(struct Curl_easy *data, struct connectdata *conn, uint16_t http_status, int http_version, const uint8_t *reason, size_t rlen) { CURLcode result; size_t len; const char *vstr; int writetype; vstr = http_version == HYPER_HTTP_VERSION_1_1 ? "1.1" : (http_version == HYPER_HTTP_VERSION_2 ? "2" : "1.0"); conn->httpversion = http_version == HYPER_HTTP_VERSION_1_1 ? 11 : (http_version == HYPER_HTTP_VERSION_2 ? 20 : 10); if(http_version == HYPER_HTTP_VERSION_1_0) data->state.httpwant = CURL_HTTP_VERSION_1_0; if(data->state.hconnect) /* CONNECT */ data->info.httpproxycode = http_status; /* We need to set 'httpcodeq' for functions that check the response code in a single place. */ data->req.httpcode = http_status; result = Curl_http_statusline(data, conn); if(result) return result; Curl_dyn_reset(&data->state.headerb); result = Curl_dyn_addf(&data->state.headerb, "HTTP/%s %03d %.*s\r\n", vstr, (int)http_status, (int)rlen, reason); if(result) return result; len = Curl_dyn_len(&data->state.headerb); Curl_debug(data, CURLINFO_HEADER_IN, Curl_dyn_ptr(&data->state.headerb), len); if(!data->state.hconnect || !data->set.suppress_connect_headers) { writetype = CLIENTWRITE_HEADER; if(data->set.include_header) writetype |= CLIENTWRITE_BODY; result = Curl_client_write(data, writetype, Curl_dyn_ptr(&data->state.headerb), len); if(result) { data->state.hresult = CURLE_ABORTED_BY_CALLBACK; return HYPER_ITER_BREAK; } } data->info.header_size += (long)len; data->req.headerbytecount += (long)len; data->req.httpcode = http_status; return CURLE_OK; } /* * Hyper does not pass on the last empty response header. The libcurl API * does. This function sends an empty header in the header callback. */ static CURLcode empty_header(struct Curl_easy *data) { CURLcode result = Curl_http_size(data); if(!result) { result = hyper_each_header(data, NULL, 0, NULL, 0) ? CURLE_WRITE_ERROR : CURLE_OK; if(result) failf(data, "hyperstream: couldn't pass blank header"); } return result; } CURLcode Curl_hyper_stream(struct Curl_easy *data, struct connectdata *conn, int *didwhat, bool *done, int select_res) { hyper_response *resp = NULL; uint16_t http_status; int http_version; hyper_headers *headers = NULL; hyper_body *resp_body = NULL; struct hyptransfer *h = &data->hyp; hyper_task *task; hyper_task *foreach; hyper_error *hypererr = NULL; const uint8_t *reasonp; size_t reason_len; CURLcode result = CURLE_OK; struct SingleRequest *k = &data->req; (void)conn; if(k->exp100 > EXP100_SEND_DATA) { struct curltime now = Curl_now(); timediff_t ms = Curl_timediff(now, k->start100); if(ms >= data->set.expect_100_timeout) { /* we've waited long enough, continue anyway */ k->exp100 = EXP100_SEND_DATA; k->keepon |= KEEP_SEND; Curl_expire_done(data, EXPIRE_100_TIMEOUT); infof(data, "Done waiting for 100-continue"); if(data->hyp.exp100_waker) { hyper_waker_wake(data->hyp.exp100_waker); data->hyp.exp100_waker = NULL; } } } if(select_res & CURL_CSELECT_IN) { if(h->read_waker) hyper_waker_wake(h->read_waker); h->read_waker = NULL; } if(select_res & CURL_CSELECT_OUT) { if(h->write_waker) hyper_waker_wake(h->write_waker); h->write_waker = NULL; } *done = FALSE; do { hyper_task_return_type t; task = hyper_executor_poll(h->exec); if(!task) { *didwhat = KEEP_RECV; break; } t = hyper_task_type(task); switch(t) { case HYPER_TASK_ERROR: hypererr = hyper_task_value(task); break; case HYPER_TASK_RESPONSE: resp = hyper_task_value(task); break; default: break; } hyper_task_free(task); if(t == HYPER_TASK_ERROR) { if(data->state.hresult) { /* override Hyper's view, might not even be an error */ result = data->state.hresult; infof(data, "hyperstream is done (by early callback)"); } else { uint8_t errbuf[256]; size_t errlen = hyper_error_print(hypererr, errbuf, sizeof(errbuf)); hyper_code code = hyper_error_code(hypererr); failf(data, "Hyper: [%d] %.*s", (int)code, (int)errlen, errbuf); if(code == HYPERE_ABORTED_BY_CALLBACK) result = CURLE_OK; else if((code == HYPERE_UNEXPECTED_EOF) && !data->req.bytecount) result = CURLE_GOT_NOTHING; else if(code == HYPERE_INVALID_PEER_MESSAGE) result = CURLE_UNSUPPORTED_PROTOCOL; /* maybe */ else result = CURLE_RECV_ERROR; } *done = TRUE; hyper_error_free(hypererr); break; } else if(h->endtask == task) { /* end of transfer */ *done = TRUE; infof(data, "hyperstream is done!"); if(!k->bodywrites) { /* hyper doesn't always call the body write callback */ bool stilldone; result = Curl_http_firstwrite(data, data->conn, &stilldone); } break; } else if(t != HYPER_TASK_RESPONSE) { *didwhat = KEEP_RECV; break; } /* HYPER_TASK_RESPONSE */ *didwhat = KEEP_RECV; if(!resp) { failf(data, "hyperstream: couldn't get response"); return CURLE_RECV_ERROR; } http_status = hyper_response_status(resp); http_version = hyper_response_version(resp); reasonp = hyper_response_reason_phrase(resp); reason_len = hyper_response_reason_phrase_len(resp); result = status_line(data, conn, http_status, http_version, reasonp, reason_len); if(result) break; headers = hyper_response_headers(resp); if(!headers) { failf(data, "hyperstream: couldn't get response headers"); result = CURLE_RECV_ERROR; break; } /* the headers are already received */ hyper_headers_foreach(headers, hyper_each_header, data); if(data->state.hresult) { result = data->state.hresult; break; } result = empty_header(data); if(result) break; /* Curl_http_auth_act() checks what authentication methods that are * available and decides which one (if any) to use. It will set 'newurl' * if an auth method was picked. */ result = Curl_http_auth_act(data); if(result) break; resp_body = hyper_response_body(resp); if(!resp_body) { failf(data, "hyperstream: couldn't get response body"); result = CURLE_RECV_ERROR; break; } foreach = hyper_body_foreach(resp_body, hyper_body_chunk, data); if(!foreach) { failf(data, "hyperstream: body foreach failed"); result = CURLE_OUT_OF_MEMORY; break; } DEBUGASSERT(hyper_task_type(foreach) == HYPER_TASK_EMPTY); if(HYPERE_OK != hyper_executor_push(h->exec, foreach)) { failf(data, "Couldn't hyper_executor_push the body-foreach"); result = CURLE_OUT_OF_MEMORY; break; } h->endtask = foreach; hyper_response_free(resp); resp = NULL; } while(1); if(resp) hyper_response_free(resp); return result; } static CURLcode debug_request(struct Curl_easy *data, const char *method, const char *path, bool h2) { char *req = aprintf("%s %s HTTP/%s\r\n", method, path, h2?"2":"1.1"); if(!req) return CURLE_OUT_OF_MEMORY; Curl_debug(data, CURLINFO_HEADER_OUT, req, strlen(req)); free(req); return CURLE_OK; } /* * Given a full header line "name: value" (optional CRLF in the input, should * be in the output), add to Hyper and send to the debug callback. * * Supports multiple headers. */ CURLcode Curl_hyper_header(struct Curl_easy *data, hyper_headers *headers, const char *line) { const char *p; const char *n; size_t nlen; const char *v; size_t vlen; bool newline = TRUE; int numh = 0; if(!line) return CURLE_OK; n = line; do { size_t linelen = 0; p = strchr(n, ':'); if(!p) /* this is fine if we already added at least one header */ return numh ? CURLE_OK : CURLE_BAD_FUNCTION_ARGUMENT; nlen = p - n; p++; /* move past the colon */ while(*p == ' ') p++; v = p; p = strchr(v, '\r'); if(!p) { p = strchr(v, '\n'); if(p) linelen = 1; /* LF only */ else { p = strchr(v, '\0'); newline = FALSE; /* no newline */ } } else linelen = 2; /* CRLF ending */ linelen += (p - n); vlen = p - v; if(HYPERE_OK != hyper_headers_add(headers, (uint8_t *)n, nlen, (uint8_t *)v, vlen)) { failf(data, "hyper refused to add header '%s'", line); return CURLE_OUT_OF_MEMORY; } if(data->set.verbose) { char *ptr = NULL; if(!newline) { ptr = aprintf("%.*s\r\n", (int)linelen, line); if(!ptr) return CURLE_OUT_OF_MEMORY; Curl_debug(data, CURLINFO_HEADER_OUT, ptr, linelen + 2); free(ptr); } else Curl_debug(data, CURLINFO_HEADER_OUT, (char *)n, linelen); } numh++; n += linelen; } while(newline); return CURLE_OK; } static CURLcode request_target(struct Curl_easy *data, struct connectdata *conn, const char *method, bool h2, hyper_request *req) { CURLcode result; struct dynbuf r; Curl_dyn_init(&r, DYN_HTTP_REQUEST); result = Curl_http_target(data, conn, &r); if(result) return result; if(h2 && hyper_request_set_uri_parts(req, /* scheme */ (uint8_t *)data->state.up.scheme, strlen(data->state.up.scheme), /* authority */ (uint8_t *)conn->host.name, strlen(conn->host.name), /* path_and_query */ (uint8_t *)Curl_dyn_uptr(&r), Curl_dyn_len(&r))) { failf(data, "error setting uri parts to hyper"); result = CURLE_OUT_OF_MEMORY; } else if(!h2 && hyper_request_set_uri(req, (uint8_t *)Curl_dyn_uptr(&r), Curl_dyn_len(&r))) { failf(data, "error setting uri to hyper"); result = CURLE_OUT_OF_MEMORY; } else result = debug_request(data, method, Curl_dyn_ptr(&r), h2); Curl_dyn_free(&r); return result; } static int uploadpostfields(void *userdata, hyper_context *ctx, hyper_buf **chunk) { struct Curl_easy *data = (struct Curl_easy *)userdata; (void)ctx; if(data->req.exp100 > EXP100_SEND_DATA) { if(data->req.exp100 == EXP100_FAILED) return HYPER_POLL_ERROR; /* still waiting confirmation */ if(data->hyp.exp100_waker) hyper_waker_free(data->hyp.exp100_waker); data->hyp.exp100_waker = hyper_context_waker(ctx); return HYPER_POLL_PENDING; } if(data->req.upload_done) *chunk = NULL; /* nothing more to deliver */ else { /* send everything off in a single go */ hyper_buf *copy = hyper_buf_copy(data->set.postfields, (size_t)data->req.p.http->postsize); if(copy) *chunk = copy; else { data->state.hresult = CURLE_OUT_OF_MEMORY; return HYPER_POLL_ERROR; } /* increasing the writebytecount here is a little premature but we don't know exactly when the body is sent*/ data->req.writebytecount += (size_t)data->req.p.http->postsize; Curl_pgrsSetUploadCounter(data, data->req.writebytecount); data->req.upload_done = TRUE; } return HYPER_POLL_READY; } static int uploadstreamed(void *userdata, hyper_context *ctx, hyper_buf **chunk) { size_t fillcount; struct Curl_easy *data = (struct Curl_easy *)userdata; CURLcode result; (void)ctx; if(data->req.exp100 > EXP100_SEND_DATA) { if(data->req.exp100 == EXP100_FAILED) return HYPER_POLL_ERROR; /* still waiting confirmation */ if(data->hyp.exp100_waker) hyper_waker_free(data->hyp.exp100_waker); data->hyp.exp100_waker = hyper_context_waker(ctx); return HYPER_POLL_PENDING; } result = Curl_fillreadbuffer(data, data->set.upload_buffer_size, &fillcount); if(result) { data->state.hresult = result; return HYPER_POLL_ERROR; } if(!fillcount) /* done! */ *chunk = NULL; else { hyper_buf *copy = hyper_buf_copy((uint8_t *)data->state.ulbuf, fillcount); if(copy) *chunk = copy; else { data->state.hresult = CURLE_OUT_OF_MEMORY; return HYPER_POLL_ERROR; } /* increasing the writebytecount here is a little premature but we don't know exactly when the body is sent*/ data->req.writebytecount += fillcount; Curl_pgrsSetUploadCounter(data, fillcount); } return HYPER_POLL_READY; } /* * bodysend() sets up headers in the outgoing request for a HTTP transfer that * sends a body */ static CURLcode bodysend(struct Curl_easy *data, struct connectdata *conn, hyper_headers *headers, hyper_request *hyperreq, Curl_HttpReq httpreq) { struct HTTP *http = data->req.p.http; CURLcode result = CURLE_OK; struct dynbuf req; if((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) Curl_pgrsSetUploadSize(data, 0); /* no request body */ else { hyper_body *body; Curl_dyn_init(&req, DYN_HTTP_REQUEST); result = Curl_http_bodysend(data, conn, &req, httpreq); if(!result) result = Curl_hyper_header(data, headers, Curl_dyn_ptr(&req)); Curl_dyn_free(&req); body = hyper_body_new(); hyper_body_set_userdata(body, data); if(data->set.postfields) hyper_body_set_data_func(body, uploadpostfields); else { result = Curl_get_upload_buffer(data); if(result) return result; /* init the "upload from here" pointer */ data->req.upload_fromhere = data->state.ulbuf; hyper_body_set_data_func(body, uploadstreamed); } if(HYPERE_OK != hyper_request_set_body(hyperreq, body)) { /* fail */ hyper_body_free(body); result = CURLE_OUT_OF_MEMORY; } } http->sending = HTTPSEND_BODY; return result; } static CURLcode cookies(struct Curl_easy *data, struct connectdata *conn, hyper_headers *headers) { struct dynbuf req; CURLcode result; Curl_dyn_init(&req, DYN_HTTP_REQUEST); result = Curl_http_cookies(data, conn, &req); if(!result) result = Curl_hyper_header(data, headers, Curl_dyn_ptr(&req)); Curl_dyn_free(&req); return result; } /* called on 1xx responses */ static void http1xx_cb(void *arg, struct hyper_response *resp) { struct Curl_easy *data = (struct Curl_easy *)arg; hyper_headers *headers = NULL; CURLcode result = CURLE_OK; uint16_t http_status; int http_version; const uint8_t *reasonp; size_t reason_len; infof(data, "Got HTTP 1xx informational"); http_status = hyper_response_status(resp); http_version = hyper_response_version(resp); reasonp = hyper_response_reason_phrase(resp); reason_len = hyper_response_reason_phrase_len(resp); result = status_line(data, data->conn, http_status, http_version, reasonp, reason_len); if(!result) { headers = hyper_response_headers(resp); if(!headers) { failf(data, "hyperstream: couldn't get 1xx response headers"); result = CURLE_RECV_ERROR; } } data->state.hresult = result; if(!result) { /* the headers are already received */ hyper_headers_foreach(headers, hyper_each_header, data); /* this callback also sets data->state.hresult on error */ if(empty_header(data)) result = CURLE_OUT_OF_MEMORY; } if(data->state.hresult) infof(data, "ERROR in 1xx, bail out!"); } /* * Curl_http() gets called from the generic multi_do() function when a HTTP * request is to be performed. This creates and sends a properly constructed * HTTP request. */ CURLcode Curl_http(struct Curl_easy *data, bool *done) { struct connectdata *conn = data->conn; struct hyptransfer *h = &data->hyp; hyper_io *io = NULL; hyper_clientconn_options *options = NULL; hyper_task *task = NULL; /* for the handshake */ hyper_task *sendtask = NULL; /* for the send */ hyper_clientconn *client = NULL; hyper_request *req = NULL; hyper_headers *headers = NULL; hyper_task *handshake = NULL; CURLcode result; const char *p_accept; /* Accept: string */ const char *method; Curl_HttpReq httpreq; bool h2 = FALSE; const char *te = NULL; /* transfer-encoding */ hyper_code rc; /* Always consider the DO phase done after this function call, even if there may be parts of the request that is not yet sent, since we can deal with the rest of the request in the PERFORM phase. */ *done = TRUE; infof(data, "Time for the Hyper dance"); memset(h, 0, sizeof(struct hyptransfer)); result = Curl_http_host(data, conn); if(result) return result; Curl_http_method(data, conn, &method, &httpreq); /* setup the authentication headers */ { char *pq = NULL; if(data->state.up.query) { pq = aprintf("%s?%s", data->state.up.path, data->state.up.query); if(!pq) return CURLE_OUT_OF_MEMORY; } result = Curl_http_output_auth(data, conn, method, httpreq, (pq ? pq : data->state.up.path), FALSE); free(pq); if(result) return result; } result = Curl_http_resume(data, conn, httpreq); if(result) return result; result = Curl_http_range(data, httpreq); if(result) return result; result = Curl_http_useragent(data); if(result) return result; io = hyper_io_new(); if(!io) { failf(data, "Couldn't create hyper IO"); result = CURLE_OUT_OF_MEMORY; goto error; } /* tell Hyper how to read/write network data */ hyper_io_set_userdata(io, data); hyper_io_set_read(io, Curl_hyper_recv); hyper_io_set_write(io, Curl_hyper_send); /* create an executor to poll futures */ if(!h->exec) { h->exec = hyper_executor_new(); if(!h->exec) { failf(data, "Couldn't create hyper executor"); result = CURLE_OUT_OF_MEMORY; goto error; } } options = hyper_clientconn_options_new(); if(!options) { failf(data, "Couldn't create hyper client options"); result = CURLE_OUT_OF_MEMORY; goto error; } if(conn->negnpn == CURL_HTTP_VERSION_2) { hyper_clientconn_options_http2(options, 1); h2 = TRUE; } hyper_clientconn_options_exec(options, h->exec); /* "Both the `io` and the `options` are consumed in this function call" */ handshake = hyper_clientconn_handshake(io, options); if(!handshake) { failf(data, "Couldn't create hyper client handshake"); result = CURLE_OUT_OF_MEMORY; goto error; } io = NULL; options = NULL; if(HYPERE_OK != hyper_executor_push(h->exec, handshake)) { failf(data, "Couldn't hyper_executor_push the handshake"); result = CURLE_OUT_OF_MEMORY; goto error; } handshake = NULL; /* ownership passed on */ task = hyper_executor_poll(h->exec); if(!task) { failf(data, "Couldn't hyper_executor_poll the handshake"); result = CURLE_OUT_OF_MEMORY; goto error; } client = hyper_task_value(task); hyper_task_free(task); req = hyper_request_new(); if(!req) { failf(data, "Couldn't hyper_request_new"); result = CURLE_OUT_OF_MEMORY; goto error; } if(!Curl_use_http_1_1plus(data, conn)) { if(HYPERE_OK != hyper_request_set_version(req, HYPER_HTTP_VERSION_1_0)) { failf(data, "error setting HTTP version"); result = CURLE_OUT_OF_MEMORY; goto error; } } if(hyper_request_set_method(req, (uint8_t *)method, strlen(method))) { failf(data, "error setting method"); result = CURLE_OUT_OF_MEMORY; goto error; } result = request_target(data, conn, method, h2, req); if(result) goto error; headers = hyper_request_headers(req); if(!headers) { failf(data, "hyper_request_headers"); result = CURLE_OUT_OF_MEMORY; goto error; } rc = hyper_request_on_informational(req, http1xx_cb, data); if(rc) { result = CURLE_OUT_OF_MEMORY; goto error; } result = Curl_http_body(data, conn, httpreq, &te); if(result) goto error; if(!h2) { if(data->state.aptr.host) { result = Curl_hyper_header(data, headers, data->state.aptr.host); if(result) goto error; } } else { /* For HTTP/2, we show the Host: header as if we sent it, to make it look like for HTTP/1 but it isn't actually sent since :authority is then used. */ result = Curl_debug(data, CURLINFO_HEADER_OUT, data->state.aptr.host, strlen(data->state.aptr.host)); if(result) goto error; } if(data->state.aptr.proxyuserpwd) { result = Curl_hyper_header(data, headers, data->state.aptr.proxyuserpwd); if(result) goto error; } if(data->state.aptr.userpwd) { result = Curl_hyper_header(data, headers, data->state.aptr.userpwd); if(result) goto error; } if((data->state.use_range && data->state.aptr.rangeline)) { result = Curl_hyper_header(data, headers, data->state.aptr.rangeline); if(result) goto error; } if(data->set.str[STRING_USERAGENT] && *data->set.str[STRING_USERAGENT] && data->state.aptr.uagent) { result = Curl_hyper_header(data, headers, data->state.aptr.uagent); if(result) goto error; } p_accept = Curl_checkheaders(data, "Accept")?NULL:"Accept: */*\r\n"; if(p_accept) { result = Curl_hyper_header(data, headers, p_accept); if(result) goto error; } if(te) { result = Curl_hyper_header(data, headers, te); if(result) goto error; } #ifndef CURL_DISABLE_PROXY if(conn->bits.httpproxy && !conn->bits.tunnel_proxy && !Curl_checkheaders(data, "Proxy-Connection") && !Curl_checkProxyheaders(data, conn, "Proxy-Connection")) { result = Curl_hyper_header(data, headers, "Proxy-Connection: Keep-Alive"); if(result) goto error; } #endif Curl_safefree(data->state.aptr.ref); if(data->state.referer && !Curl_checkheaders(data, "Referer")) { data->state.aptr.ref = aprintf("Referer: %s\r\n", data->state.referer); if(!data->state.aptr.ref) result = CURLE_OUT_OF_MEMORY; else result = Curl_hyper_header(data, headers, data->state.aptr.ref); if(result) goto error; } if(!Curl_checkheaders(data, "Accept-Encoding") && data->set.str[STRING_ENCODING]) { Curl_safefree(data->state.aptr.accept_encoding); data->state.aptr.accept_encoding = aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]); if(!data->state.aptr.accept_encoding) result = CURLE_OUT_OF_MEMORY; else result = Curl_hyper_header(data, headers, data->state.aptr.accept_encoding); if(result) goto error; } else Curl_safefree(data->state.aptr.accept_encoding); #ifdef HAVE_LIBZ /* we only consider transfer-encoding magic if libz support is built-in */ result = Curl_transferencode(data); if(result) goto error; result = Curl_hyper_header(data, headers, data->state.aptr.te); if(result) goto error; #endif result = cookies(data, conn, headers); if(result) goto error; result = Curl_add_timecondition(data, headers); if(result) goto error; result = Curl_add_custom_headers(data, FALSE, headers); if(result) goto error; result = bodysend(data, conn, headers, req, httpreq); if(result) goto error; result = Curl_debug(data, CURLINFO_HEADER_OUT, (char *)"\r\n", 2); if(result) goto error; data->req.upload_chunky = FALSE; sendtask = hyper_clientconn_send(client, req); if(!sendtask) { failf(data, "hyper_clientconn_send"); result = CURLE_OUT_OF_MEMORY; goto error; } if(HYPERE_OK != hyper_executor_push(h->exec, sendtask)) { failf(data, "Couldn't hyper_executor_push the send"); result = CURLE_OUT_OF_MEMORY; goto error; } hyper_clientconn_free(client); if((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) { /* HTTP GET/HEAD download */ Curl_pgrsSetUploadSize(data, 0); /* nothing */ Curl_setup_transfer(data, FIRSTSOCKET, -1, TRUE, -1); } conn->datastream = Curl_hyper_stream; if(data->state.expect100header) /* Timeout count starts now since with Hyper we don't know exactly when the full request has been sent. */ data->req.start100 = Curl_now(); /* clear userpwd and proxyuserpwd to avoid re-using old credentials * from re-used connections */ Curl_safefree(data->state.aptr.userpwd); Curl_safefree(data->state.aptr.proxyuserpwd); return CURLE_OK; error: DEBUGASSERT(result); if(io) hyper_io_free(io); if(options) hyper_clientconn_options_free(options); if(handshake) hyper_task_free(handshake); return result; } void Curl_hyper_done(struct Curl_easy *data) { struct hyptransfer *h = &data->hyp; if(h->exec) { hyper_executor_free(h->exec); h->exec = NULL; } if(h->read_waker) { hyper_waker_free(h->read_waker); h->read_waker = NULL; } if(h->write_waker) { hyper_waker_free(h->write_waker); h->write_waker = NULL; } if(h->exp100_waker) { hyper_waker_free(h->exp100_waker); h->exp100_waker = NULL; } } #endif /* !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/hsts.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2020 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * The Strict-Transport-Security header is defined in RFC 6797: * https://tools.ietf.org/html/rfc6797 */ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_HSTS) #include <curl/curl.h> #include "urldata.h" #include "llist.h" #include "hsts.h" #include "curl_get_line.h" #include "strcase.h" #include "sendf.h" #include "strtoofft.h" #include "parsedate.h" #include "rand.h" #include "rename.h" #include "strtoofft.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #define MAX_HSTS_LINE 4095 #define MAX_HSTS_HOSTLEN 256 #define MAX_HSTS_HOSTLENSTR "256" #define MAX_HSTS_DATELEN 64 #define MAX_HSTS_DATELENSTR "64" #define UNLIMITED "unlimited" #ifdef DEBUGBUILD /* to play well with debug builds, we can *set* a fixed time this will return */ time_t deltatime; /* allow for "adjustments" for unit test purposes */ static time_t debugtime(void *unused) { char *timestr = getenv("CURL_TIME"); (void)unused; if(timestr) { curl_off_t val; (void)curlx_strtoofft(timestr, NULL, 10, &val); val += (curl_off_t)deltatime; return (time_t)val; } return time(NULL); } #define time(x) debugtime(x) #endif struct hsts *Curl_hsts_init(void) { struct hsts *h = calloc(sizeof(struct hsts), 1); if(h) { Curl_llist_init(&h->list, NULL); } return h; } static void hsts_free(struct stsentry *e) { free((char *)e->host); free(e); } void Curl_hsts_cleanup(struct hsts **hp) { struct hsts *h = *hp; if(h) { struct Curl_llist_element *e; struct Curl_llist_element *n; for(e = h->list.head; e; e = n) { struct stsentry *sts = e->ptr; n = e->next; hsts_free(sts); } free(h->filename); free(h); *hp = NULL; } } static struct stsentry *hsts_entry(void) { return calloc(sizeof(struct stsentry), 1); } static CURLcode hsts_create(struct hsts *h, const char *hostname, bool subdomains, curl_off_t expires) { struct stsentry *sts = hsts_entry(); if(!sts) return CURLE_OUT_OF_MEMORY; sts->expires = expires; sts->includeSubDomains = subdomains; sts->host = strdup(hostname); if(!sts->host) { free(sts); return CURLE_OUT_OF_MEMORY; } Curl_llist_insert_next(&h->list, h->list.tail, sts, &sts->node); return CURLE_OK; } CURLcode Curl_hsts_parse(struct hsts *h, const char *hostname, const char *header) { const char *p = header; curl_off_t expires = 0; bool gotma = FALSE; bool gotinc = FALSE; bool subdomains = FALSE; struct stsentry *sts; time_t now = time(NULL); if(Curl_host_is_ipnum(hostname)) /* "explicit IP address identification of all forms is excluded." / RFC 6797 */ return CURLE_OK; do { while(*p && ISSPACE(*p)) p++; if(Curl_strncasecompare("max-age=", p, 8)) { bool quoted = FALSE; CURLofft offt; char *endp; if(gotma) return CURLE_BAD_FUNCTION_ARGUMENT; p += 8; while(*p && ISSPACE(*p)) p++; if(*p == '\"') { p++; quoted = TRUE; } offt = curlx_strtoofft(p, &endp, 10, &expires); if(offt == CURL_OFFT_FLOW) expires = CURL_OFF_T_MAX; else if(offt) /* invalid max-age */ return CURLE_BAD_FUNCTION_ARGUMENT; p = endp; if(quoted) { if(*p != '\"') return CURLE_BAD_FUNCTION_ARGUMENT; p++; } gotma = TRUE; } else if(Curl_strncasecompare("includesubdomains", p, 17)) { if(gotinc) return CURLE_BAD_FUNCTION_ARGUMENT; subdomains = TRUE; p += 17; gotinc = TRUE; } else { /* unknown directive, do a lame attempt to skip */ while(*p && (*p != ';')) p++; } while(*p && ISSPACE(*p)) p++; if(*p == ';') p++; } while (*p); if(!gotma) /* max-age is mandatory */ return CURLE_BAD_FUNCTION_ARGUMENT; if(!expires) { /* remove the entry if present verbatim (without subdomain match) */ sts = Curl_hsts(h, hostname, FALSE); if(sts) { Curl_llist_remove(&h->list, &sts->node, NULL); hsts_free(sts); } return CURLE_OK; } if(CURL_OFF_T_MAX - now < expires) /* would overflow, use maximum value */ expires = CURL_OFF_T_MAX; else expires += now; /* check if it already exists */ sts = Curl_hsts(h, hostname, FALSE); if(sts) { /* just update these fields */ sts->expires = expires; sts->includeSubDomains = subdomains; } else return hsts_create(h, hostname, subdomains, expires); return CURLE_OK; } /* * Return TRUE if the given host name is currently an HSTS one. * * The 'subdomain' argument tells the function if subdomain matching should be * attempted. */ struct stsentry *Curl_hsts(struct hsts *h, const char *hostname, bool subdomain) { if(h) { time_t now = time(NULL); size_t hlen = strlen(hostname); struct Curl_llist_element *e; struct Curl_llist_element *n; for(e = h->list.head; e; e = n) { struct stsentry *sts = e->ptr; n = e->next; if(sts->expires <= now) { /* remove expired entries */ Curl_llist_remove(&h->list, &sts->node, NULL); hsts_free(sts); continue; } if(subdomain && sts->includeSubDomains) { size_t ntail = strlen(sts->host); if(ntail < hlen) { size_t offs = hlen - ntail; if((hostname[offs-1] == '.') && Curl_strncasecompare(&hostname[offs], sts->host, ntail)) return sts; } } if(Curl_strcasecompare(hostname, sts->host)) return sts; } } return NULL; /* no match */ } /* * Send this HSTS entry to the write callback. */ static CURLcode hsts_push(struct Curl_easy *data, struct curl_index *i, struct stsentry *sts, bool *stop) { struct curl_hstsentry e; CURLSTScode sc; struct tm stamp; CURLcode result; e.name = (char *)sts->host; e.namelen = strlen(sts->host); e.includeSubDomains = sts->includeSubDomains; if(sts->expires != TIME_T_MAX) { result = Curl_gmtime((time_t)sts->expires, &stamp); if(result) return result; msnprintf(e.expire, sizeof(e.expire), "%d%02d%02d %02d:%02d:%02d", stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday, stamp.tm_hour, stamp.tm_min, stamp.tm_sec); } else strcpy(e.expire, UNLIMITED); sc = data->set.hsts_write(data, &e, i, data->set.hsts_write_userp); *stop = (sc != CURLSTS_OK); return sc == CURLSTS_FAIL ? CURLE_BAD_FUNCTION_ARGUMENT : CURLE_OK; } /* * Write this single hsts entry to a single output line */ static CURLcode hsts_out(struct stsentry *sts, FILE *fp) { struct tm stamp; if(sts->expires != TIME_T_MAX) { CURLcode result = Curl_gmtime((time_t)sts->expires, &stamp); if(result) return result; fprintf(fp, "%s%s \"%d%02d%02d %02d:%02d:%02d\"\n", sts->includeSubDomains ? ".": "", sts->host, stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday, stamp.tm_hour, stamp.tm_min, stamp.tm_sec); } else fprintf(fp, "%s%s \"%s\"\n", sts->includeSubDomains ? ".": "", sts->host, UNLIMITED); return CURLE_OK; } /* * Curl_https_save() writes the HSTS cache to file and callback. */ CURLcode Curl_hsts_save(struct Curl_easy *data, struct hsts *h, const char *file) { struct Curl_llist_element *e; struct Curl_llist_element *n; CURLcode result = CURLE_OK; FILE *out; char *tempstore; unsigned char randsuffix[9]; if(!h) /* no cache activated */ return CURLE_OK; /* if no new name is given, use the one we stored from the load */ if(!file && h->filename) file = h->filename; if((h->flags & CURLHSTS_READONLYFILE) || !file || !file[0]) /* marked as read-only, no file or zero length file name */ goto skipsave; if(Curl_rand_hex(data, randsuffix, sizeof(randsuffix))) return CURLE_FAILED_INIT; tempstore = aprintf("%s.%s.tmp", file, randsuffix); if(!tempstore) return CURLE_OUT_OF_MEMORY; out = fopen(tempstore, FOPEN_WRITETEXT); if(!out) result = CURLE_WRITE_ERROR; else { fputs("# Your HSTS cache. https://curl.se/docs/hsts.html\n" "# This file was generated by libcurl! Edit at your own risk.\n", out); for(e = h->list.head; e; e = n) { struct stsentry *sts = e->ptr; n = e->next; result = hsts_out(sts, out); if(result) break; } fclose(out); if(!result && Curl_rename(tempstore, file)) result = CURLE_WRITE_ERROR; if(result) unlink(tempstore); } free(tempstore); skipsave: if(data->set.hsts_write) { /* if there's a write callback */ struct curl_index i; /* count */ i.total = h->list.size; i.index = 0; for(e = h->list.head; e; e = n) { struct stsentry *sts = e->ptr; bool stop; n = e->next; result = hsts_push(data, &i, sts, &stop); if(result || stop) break; i.index++; } } return result; } /* only returns SERIOUS errors */ static CURLcode hsts_add(struct hsts *h, char *line) { /* Example lines: example.com "20191231 10:00:00" .example.net "20191231 10:00:00" */ char host[MAX_HSTS_HOSTLEN + 1]; char date[MAX_HSTS_DATELEN + 1]; int rc; rc = sscanf(line, "%" MAX_HSTS_HOSTLENSTR "s \"%" MAX_HSTS_DATELENSTR "[^\"]\"", host, date); if(2 == rc) { time_t expires = strcmp(date, UNLIMITED) ? Curl_getdate_capped(date) : TIME_T_MAX; CURLcode result; char *p = host; bool subdomain = FALSE; if(p[0] == '.') { p++; subdomain = TRUE; } result = hsts_create(h, p, subdomain, expires); if(result) return result; } return CURLE_OK; } /* * Load HSTS data from callback. * */ static CURLcode hsts_pull(struct Curl_easy *data, struct hsts *h) { /* if the HSTS read callback is set, use it */ if(data->set.hsts_read) { CURLSTScode sc; DEBUGASSERT(h); do { char buffer[257]; struct curl_hstsentry e; e.name = buffer; e.namelen = sizeof(buffer)-1; e.includeSubDomains = FALSE; /* default */ e.expire[0] = 0; e.name[0] = 0; /* just to make it clean */ sc = data->set.hsts_read(data, &e, data->set.hsts_read_userp); if(sc == CURLSTS_OK) { time_t expires; CURLcode result; if(!e.name[0]) /* bail out if no name was stored */ return CURLE_BAD_FUNCTION_ARGUMENT; if(e.expire[0]) expires = Curl_getdate_capped(e.expire); else expires = TIME_T_MAX; /* the end of time */ result = hsts_create(h, e.name, /* bitfield to bool conversion: */ e.includeSubDomains ? TRUE : FALSE, expires); if(result) return result; } else if(sc == CURLSTS_FAIL) return CURLE_ABORTED_BY_CALLBACK; } while(sc == CURLSTS_OK); } return CURLE_OK; } /* * Load the HSTS cache from the given file. The text based line-oriented file * format is documented here: * https://github.com/curl/curl/wiki/HSTS * * This function only returns error on major problems that prevent hsts * handling to work completely. It will ignore individual syntactical errors * etc. */ static CURLcode hsts_load(struct hsts *h, const char *file) { CURLcode result = CURLE_OK; char *line = NULL; FILE *fp; /* we need a private copy of the file name so that the hsts cache file name survives an easy handle reset */ free(h->filename); h->filename = strdup(file); if(!h->filename) return CURLE_OUT_OF_MEMORY; fp = fopen(file, FOPEN_READTEXT); if(fp) { line = malloc(MAX_HSTS_LINE); if(!line) goto fail; while(Curl_get_line(line, MAX_HSTS_LINE, fp)) { char *lineptr = line; while(*lineptr && ISBLANK(*lineptr)) lineptr++; if(*lineptr == '#') /* skip commented lines */ continue; hsts_add(h, lineptr); } free(line); /* free the line buffer */ fclose(fp); } return result; fail: Curl_safefree(h->filename); fclose(fp); return CURLE_OUT_OF_MEMORY; } /* * Curl_hsts_loadfile() loads HSTS from file */ CURLcode Curl_hsts_loadfile(struct Curl_easy *data, struct hsts *h, const char *file) { DEBUGASSERT(h); (void)data; return hsts_load(h, file); } /* * Curl_hsts_loadcb() loads HSTS from callback */ CURLcode Curl_hsts_loadcb(struct Curl_easy *data, struct hsts *h) { if(h) return hsts_pull(data, h); return CURLE_OK; } #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_HSTS */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/md5.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_CRYPTO_AUTH #include <curl/curl.h> #include "curl_md5.h" #include "curl_hmac.h" #include "warnless.h" #ifdef USE_MBEDTLS #include <mbedtls/version.h> #if(MBEDTLS_VERSION_NUMBER >= 0x02070000) && \ (MBEDTLS_VERSION_NUMBER < 0x03000000) #define HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS #endif #endif /* USE_MBEDTLS */ #if defined(USE_OPENSSL) && !defined(USE_AMISSL) #include <openssl/opensslconf.h> #if !defined(OPENSSL_NO_MD5) && !defined(OPENSSL_NO_DEPRECATED_3_0) #define USE_OPENSSL_MD5 #endif #endif #ifdef USE_WOLFSSL #include <wolfssl/options.h> #ifndef NO_MD5 #define USE_WOLFSSL_MD5 #endif #endif #if defined(USE_GNUTLS) #include <nettle/md5.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" typedef struct md5_ctx MD5_CTX; static void MD5_Init(MD5_CTX *ctx) { md5_init(ctx); } static void MD5_Update(MD5_CTX *ctx, const unsigned char *input, unsigned int inputLen) { md5_update(ctx, inputLen, input); } static void MD5_Final(unsigned char *digest, MD5_CTX *ctx) { md5_digest(ctx, 16, digest); } #elif defined(USE_OPENSSL_MD5) || defined(USE_WOLFSSL_MD5) /* When OpenSSL or wolfSSL is available, we use their MD5 functions. */ #include <openssl/md5.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" #elif defined(USE_MBEDTLS) #include <mbedtls/md5.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" typedef mbedtls_md5_context MD5_CTX; static void MD5_Init(MD5_CTX *ctx) { #if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) (void) mbedtls_md5_starts(ctx); #else (void) mbedtls_md5_starts_ret(ctx); #endif } static void MD5_Update(MD5_CTX *ctx, const unsigned char *data, unsigned int length) { #if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) (void) mbedtls_md5_update(ctx, data, length); #else (void) mbedtls_md5_update_ret(ctx, data, length); #endif } static void MD5_Final(unsigned char *digest, MD5_CTX *ctx) { #if !defined(HAS_MBEDTLS_RESULT_CODE_BASED_FUNCTIONS) (void) mbedtls_md5_finish(ctx, digest); #else (void) mbedtls_md5_finish_ret(ctx, digest); #endif } #elif (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && \ (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1040) && \ defined(__MAC_OS_X_VERSION_MIN_ALLOWED) && \ (__MAC_OS_X_VERSION_MIN_ALLOWED < 101500)) || \ (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && \ (__IPHONE_OS_VERSION_MAX_ALLOWED >= 20000)) /* For Apple operating systems: CommonCrypto has the functions we need. These functions are available on Tiger and later, as well as iOS 2.0 and later. If you're building for an older cat, well, sorry. Declaring the functions as static like this seems to be a bit more reliable than defining COMMON_DIGEST_FOR_OPENSSL on older cats. */ # include <CommonCrypto/CommonDigest.h> # define MD5_CTX CC_MD5_CTX #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" static void MD5_Init(MD5_CTX *ctx) { CC_MD5_Init(ctx); } static void MD5_Update(MD5_CTX *ctx, const unsigned char *input, unsigned int inputLen) { CC_MD5_Update(ctx, input, inputLen); } static void MD5_Final(unsigned char *digest, MD5_CTX *ctx) { CC_MD5_Final(digest, ctx); } #elif defined(USE_WIN32_CRYPTO) #include <wincrypt.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" struct md5_ctx { HCRYPTPROV hCryptProv; HCRYPTHASH hHash; }; typedef struct md5_ctx MD5_CTX; static void MD5_Init(MD5_CTX *ctx) { if(CryptAcquireContext(&ctx->hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { CryptCreateHash(ctx->hCryptProv, CALG_MD5, 0, 0, &ctx->hHash); } } static void MD5_Update(MD5_CTX *ctx, const unsigned char *input, unsigned int inputLen) { CryptHashData(ctx->hHash, (unsigned char *)input, inputLen, 0); } static void MD5_Final(unsigned char *digest, MD5_CTX *ctx) { unsigned long length = 0; CryptGetHashParam(ctx->hHash, HP_HASHVAL, NULL, &length, 0); if(length == 16) CryptGetHashParam(ctx->hHash, HP_HASHVAL, digest, &length, 0); if(ctx->hHash) CryptDestroyHash(ctx->hHash); if(ctx->hCryptProv) CryptReleaseContext(ctx->hCryptProv, 0); } #else /* When no other crypto library is available we use this code segment */ /* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: https://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: * Alexander Peslyak, better known as Solar Designer <solar at openwall.com> * * This software was written by Alexander Peslyak in 2001. No copyright is * claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * This differs from Colin Plumb's older public domain implementation in that * no exactly 32-bit integer data type is required (any 32-bit or wider * unsigned integer data type will do), there's no compile-time endianness * configuration, and the function prototypes match OpenSSL's. No code from * Colin Plumb's implementation has been reused; this comment merely compares * the properties of the two independent implementations. * * The primary goals of this implementation are portability and ease of use. * It is meant to be fast, but not as fast as possible. Some known * optimizations are not included to reduce source code size and avoid * compile-time configuration. */ #include <string.h> /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; struct md5_ctx { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; unsigned char buffer[64]; MD5_u32plus block[16]; }; typedef struct md5_ctx MD5_CTX; static void MD5_Init(MD5_CTX *ctx); static void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); static void MD5_Final(unsigned char *result, MD5_CTX *ctx); /* * The basic MD5 functions. * * F and G are optimized compared to their RFC 1321 definitions for * architectures that lack an AND-NOT instruction, just like in Colin Plumb's * implementation. */ #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) #define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) #define H(x, y, z) (((x) ^ (y)) ^ (z)) #define H2(x, y, z) ((x) ^ ((y) ^ (z))) #define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * The MD5 transformation for all four rounds. */ #define STEP(f, a, b, c, d, x, t, s) \ (a) += f((b), (c), (d)) + (x) + (t); \ (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ (a) += (b); /* * SET reads 4 input bytes in little-endian byte order and stores them * in a properly aligned word in host byte order. * * The check for little-endian architectures that tolerate unaligned * memory accesses is just an optimization. Nothing will break if it * doesn't work. */ #if defined(__i386__) || defined(__x86_64__) || defined(__vax__) #define SET(n) \ (*(MD5_u32plus *)(void *)&ptr[(n) * 4]) #define GET(n) \ SET(n) #else #define SET(n) \ (ctx->block[(n)] = \ (MD5_u32plus)ptr[(n) * 4] | \ ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) #define GET(n) \ (ctx->block[(n)]) #endif /* * This processes one or more 64-byte data blocks, but does NOT update * the bit counters. There are no alignment requirements. */ static const void *body(MD5_CTX *ctx, const void *data, unsigned long size) { const unsigned char *ptr; MD5_u32plus a, b, c, d; ptr = (const unsigned char *)data; a = ctx->a; b = ctx->b; c = ctx->c; d = ctx->d; do { MD5_u32plus saved_a, saved_b, saved_c, saved_d; saved_a = a; saved_b = b; saved_c = c; saved_d = d; /* Round 1 */ STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) STEP(F, c, d, a, b, SET(2), 0x242070db, 17) STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) /* Round 2 */ STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) STEP(G, d, a, b, c, GET(10), 0x02441453, 9) STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) /* Round 3 */ STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11) STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23) STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11) STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23) STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11) STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23) STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11) STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23) /* Round 4 */ STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) a += saved_a; b += saved_b; c += saved_c; d += saved_d; ptr += 64; } while(size -= 64); ctx->a = a; ctx->b = b; ctx->c = c; ctx->d = d; return ptr; } static void MD5_Init(MD5_CTX *ctx) { ctx->a = 0x67452301; ctx->b = 0xefcdab89; ctx->c = 0x98badcfe; ctx->d = 0x10325476; ctx->lo = 0; ctx->hi = 0; } static void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size) { MD5_u32plus saved_lo; unsigned long used; saved_lo = ctx->lo; ctx->lo = (saved_lo + size) & 0x1fffffff; if(ctx->lo < saved_lo) ctx->hi++; ctx->hi += (MD5_u32plus)size >> 29; used = saved_lo & 0x3f; if(used) { unsigned long available = 64 - used; if(size < available) { memcpy(&ctx->buffer[used], data, size); return; } memcpy(&ctx->buffer[used], data, available); data = (const unsigned char *)data + available; size -= available; body(ctx, ctx->buffer, 64); } if(size >= 64) { data = body(ctx, data, size & ~(unsigned long)0x3f); size &= 0x3f; } memcpy(ctx->buffer, data, size); } static void MD5_Final(unsigned char *result, MD5_CTX *ctx) { unsigned long used, available; used = ctx->lo & 0x3f; ctx->buffer[used++] = 0x80; available = 64 - used; if(available < 8) { memset(&ctx->buffer[used], 0, available); body(ctx, ctx->buffer, 64); used = 0; available = 64; } memset(&ctx->buffer[used], 0, available - 8); ctx->lo <<= 3; ctx->buffer[56] = curlx_ultouc((ctx->lo)&0xff); ctx->buffer[57] = curlx_ultouc((ctx->lo >> 8)&0xff); ctx->buffer[58] = curlx_ultouc((ctx->lo >> 16)&0xff); ctx->buffer[59] = curlx_ultouc(ctx->lo >> 24); ctx->buffer[60] = curlx_ultouc((ctx->hi)&0xff); ctx->buffer[61] = curlx_ultouc((ctx->hi >> 8)&0xff); ctx->buffer[62] = curlx_ultouc((ctx->hi >> 16)&0xff); ctx->buffer[63] = curlx_ultouc(ctx->hi >> 24); body(ctx, ctx->buffer, 64); result[0] = curlx_ultouc((ctx->a)&0xff); result[1] = curlx_ultouc((ctx->a >> 8)&0xff); result[2] = curlx_ultouc((ctx->a >> 16)&0xff); result[3] = curlx_ultouc(ctx->a >> 24); result[4] = curlx_ultouc((ctx->b)&0xff); result[5] = curlx_ultouc((ctx->b >> 8)&0xff); result[6] = curlx_ultouc((ctx->b >> 16)&0xff); result[7] = curlx_ultouc(ctx->b >> 24); result[8] = curlx_ultouc((ctx->c)&0xff); result[9] = curlx_ultouc((ctx->c >> 8)&0xff); result[10] = curlx_ultouc((ctx->c >> 16)&0xff); result[11] = curlx_ultouc(ctx->c >> 24); result[12] = curlx_ultouc((ctx->d)&0xff); result[13] = curlx_ultouc((ctx->d >> 8)&0xff); result[14] = curlx_ultouc((ctx->d >> 16)&0xff); result[15] = curlx_ultouc(ctx->d >> 24); memset(ctx, 0, sizeof(*ctx)); } #endif /* CRYPTO LIBS */ const struct HMAC_params Curl_HMAC_MD5[] = { { /* Hash initialization function. */ CURLX_FUNCTION_CAST(HMAC_hinit_func, MD5_Init), /* Hash update function. */ CURLX_FUNCTION_CAST(HMAC_hupdate_func, MD5_Update), /* Hash computation end function. */ CURLX_FUNCTION_CAST(HMAC_hfinal_func, MD5_Final), /* Size of hash context structure. */ sizeof(MD5_CTX), /* Maximum key length. */ 64, /* Result size. */ 16 } }; const struct MD5_params Curl_DIGEST_MD5[] = { { /* Digest initialization function */ CURLX_FUNCTION_CAST(Curl_MD5_init_func, MD5_Init), /* Digest update function */ CURLX_FUNCTION_CAST(Curl_MD5_update_func, MD5_Update), /* Digest computation end function */ CURLX_FUNCTION_CAST(Curl_MD5_final_func, MD5_Final), /* Size of digest context struct */ sizeof(MD5_CTX), /* Result size */ 16 } }; /* * @unittest: 1601 */ void Curl_md5it(unsigned char *outbuffer, const unsigned char *input, const size_t len) { MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, input, curlx_uztoui(len)); MD5_Final(outbuffer, &ctx); } struct MD5_context *Curl_MD5_init(const struct MD5_params *md5params) { struct MD5_context *ctxt; /* Create MD5 context */ ctxt = malloc(sizeof(*ctxt)); if(!ctxt) return ctxt; ctxt->md5_hashctx = malloc(md5params->md5_ctxtsize); if(!ctxt->md5_hashctx) { free(ctxt); return NULL; } ctxt->md5_hash = md5params; (*md5params->md5_init_func)(ctxt->md5_hashctx); return ctxt; } CURLcode Curl_MD5_update(struct MD5_context *context, const unsigned char *data, unsigned int len) { (*context->md5_hash->md5_update_func)(context->md5_hashctx, data, len); return CURLE_OK; } CURLcode Curl_MD5_final(struct MD5_context *context, unsigned char *result) { (*context->md5_hash->md5_final_func)(result, context->md5_hashctx); free(context->md5_hashctx); free(context); return CURLE_OK; } #endif /* CURL_DISABLE_CRYPTO_AUTH */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_sha256.h
#ifndef HEADER_CURL_SHA256_H #define HEADER_CURL_SHA256_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2017, Florin Petriuc, <[email protected]> * Copyright (C) 2018 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_CRYPTO_AUTH #include "curl_hmac.h" extern const struct HMAC_params Curl_HMAC_SHA256[1]; #ifdef USE_WOLFSSL /* SHA256_DIGEST_LENGTH is an enum value in wolfSSL. Need to import it from * sha.h*/ #include <wolfssl/options.h> #include <openssl/sha.h> #else #define SHA256_DIGEST_LENGTH 32 #endif void Curl_sha256it(unsigned char *outbuffer, const unsigned char *input, const size_t len); #endif #endif /* HEADER_CURL_SHA256_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/formdata.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "formdata.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_MIME) #if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME) #include <libgen.h> #endif #include "urldata.h" /* for struct Curl_easy */ #include "mime.h" #include "non-ascii.h" #include "vtls/vtls.h" #include "strcase.h" #include "sendf.h" #include "strdup.h" #include "rand.h" #include "warnless.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" #define HTTPPOST_PTRNAME CURL_HTTPPOST_PTRNAME #define HTTPPOST_FILENAME CURL_HTTPPOST_FILENAME #define HTTPPOST_PTRCONTENTS CURL_HTTPPOST_PTRCONTENTS #define HTTPPOST_READFILE CURL_HTTPPOST_READFILE #define HTTPPOST_PTRBUFFER CURL_HTTPPOST_PTRBUFFER #define HTTPPOST_CALLBACK CURL_HTTPPOST_CALLBACK #define HTTPPOST_BUFFER CURL_HTTPPOST_BUFFER /*************************************************************************** * * AddHttpPost() * * Adds a HttpPost structure to the list, if parent_post is given becomes * a subpost of parent_post instead of a direct list element. * * Returns newly allocated HttpPost on success and NULL if malloc failed. * ***************************************************************************/ static struct curl_httppost * AddHttpPost(char *name, size_t namelength, char *value, curl_off_t contentslength, char *buffer, size_t bufferlength, char *contenttype, long flags, struct curl_slist *contentHeader, char *showfilename, char *userp, struct curl_httppost *parent_post, struct curl_httppost **httppost, struct curl_httppost **last_post) { struct curl_httppost *post; post = calloc(1, sizeof(struct curl_httppost)); if(post) { post->name = name; post->namelength = (long)(name?(namelength?namelength:strlen(name)):0); post->contents = value; post->contentlen = contentslength; post->buffer = buffer; post->bufferlength = (long)bufferlength; post->contenttype = contenttype; post->contentheader = contentHeader; post->showfilename = showfilename; post->userp = userp; post->flags = flags | CURL_HTTPPOST_LARGE; } else return NULL; if(parent_post) { /* now, point our 'more' to the original 'more' */ post->more = parent_post->more; /* then move the original 'more' to point to ourselves */ parent_post->more = post; } else { /* make the previous point to this */ if(*last_post) (*last_post)->next = post; else (*httppost) = post; (*last_post) = post; } return post; } /*************************************************************************** * * AddFormInfo() * * Adds a FormInfo structure to the list presented by parent_form_info. * * Returns newly allocated FormInfo on success and NULL if malloc failed/ * parent_form_info is NULL. * ***************************************************************************/ static struct FormInfo *AddFormInfo(char *value, char *contenttype, struct FormInfo *parent_form_info) { struct FormInfo *form_info; form_info = calloc(1, sizeof(struct FormInfo)); if(form_info) { if(value) form_info->value = value; if(contenttype) form_info->contenttype = contenttype; form_info->flags = HTTPPOST_FILENAME; } else return NULL; if(parent_form_info) { /* now, point our 'more' to the original 'more' */ form_info->more = parent_form_info->more; /* then move the original 'more' to point to ourselves */ parent_form_info->more = form_info; } return form_info; } /*************************************************************************** * * FormAdd() * * Stores a formpost parameter and builds the appropriate linked list. * * Has two principal functionalities: using files and byte arrays as * post parts. Byte arrays are either copied or just the pointer is stored * (as the user requests) while for files only the filename and not the * content is stored. * * While you may have only one byte array for each name, multiple filenames * are allowed (and because of this feature CURLFORM_END is needed after * using CURLFORM_FILE). * * Examples: * * Simple name/value pair with copied contents: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_COPYCONTENTS, "value", CURLFORM_END); * * name/value pair where only the content pointer is remembered: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_PTRCONTENTS, ptr, CURLFORM_CONTENTSLENGTH, 10, CURLFORM_END); * (if CURLFORM_CONTENTSLENGTH is missing strlen () is used) * * storing a filename (CONTENTTYPE is optional!): * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_FILE, "filename1", CURLFORM_CONTENTTYPE, "plain/text", * CURLFORM_END); * * storing multiple filenames: * curl_formadd (&post, &last, CURLFORM_COPYNAME, "name", * CURLFORM_FILE, "filename1", CURLFORM_FILE, "filename2", CURLFORM_END); * * Returns: * CURL_FORMADD_OK on success * CURL_FORMADD_MEMORY if the FormInfo allocation fails * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form * CURL_FORMADD_NULL if a null pointer was given for a char * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) * CURL_FORMADD_MEMORY if a HttpPost struct cannot be allocated * CURL_FORMADD_MEMORY if some allocation for string copying failed. * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array * ***************************************************************************/ static CURLFORMcode FormAdd(struct curl_httppost **httppost, struct curl_httppost **last_post, va_list params) { struct FormInfo *first_form, *current_form, *form = NULL; CURLFORMcode return_value = CURL_FORMADD_OK; const char *prevtype = NULL; struct curl_httppost *post = NULL; CURLformoption option; struct curl_forms *forms = NULL; char *array_value = NULL; /* value read from an array */ /* This is a state variable, that if TRUE means that we're parsing an array that we got passed to us. If FALSE we're parsing the input va_list arguments. */ bool array_state = FALSE; /* * We need to allocate the first struct to fill in. */ first_form = calloc(1, sizeof(struct FormInfo)); if(!first_form) return CURL_FORMADD_MEMORY; current_form = first_form; /* * Loop through all the options set. Break if we have an error to report. */ while(return_value == CURL_FORMADD_OK) { /* first see if we have more parts of the array param */ if(array_state && forms) { /* get the upcoming option from the given array */ option = forms->option; array_value = (char *)forms->value; forms++; /* advance this to next entry */ if(CURLFORM_END == option) { /* end of array state */ array_state = FALSE; continue; } } else { /* This is not array-state, get next option */ option = va_arg(params, CURLformoption); if(CURLFORM_END == option) break; } switch(option) { case CURLFORM_ARRAY: if(array_state) /* we don't support an array from within an array */ return_value = CURL_FORMADD_ILLEGAL_ARRAY; else { forms = va_arg(params, struct curl_forms *); if(forms) array_state = TRUE; else return_value = CURL_FORMADD_NULL; } break; /* * Set the Name property. */ case CURLFORM_PTRNAME: #ifdef CURL_DOES_CONVERSIONS /* Treat CURLFORM_PTR like CURLFORM_COPYNAME so that libcurl will copy * the data in all cases so that we'll have safe memory for the eventual * conversion. */ #else current_form->flags |= HTTPPOST_PTRNAME; /* fall through */ #endif /* FALLTHROUGH */ case CURLFORM_COPYNAME: if(current_form->name) return_value = CURL_FORMADD_OPTION_TWICE; else { char *name = array_state? array_value:va_arg(params, char *); if(name) current_form->name = name; /* store for the moment */ else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_NAMELENGTH: if(current_form->namelength) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->namelength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; /* * Set the contents property. */ case CURLFORM_PTRCONTENTS: current_form->flags |= HTTPPOST_PTRCONTENTS; /* FALLTHROUGH */ case CURLFORM_COPYCONTENTS: if(current_form->value) return_value = CURL_FORMADD_OPTION_TWICE; else { char *value = array_state?array_value:va_arg(params, char *); if(value) current_form->value = value; /* store for the moment */ else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_CONTENTSLENGTH: current_form->contentslength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; case CURLFORM_CONTENTLEN: current_form->flags |= CURL_HTTPPOST_LARGE; current_form->contentslength = array_state?(curl_off_t)(size_t)array_value:va_arg(params, curl_off_t); break; /* Get contents from a given file name */ case CURLFORM_FILECONTENT: if(current_form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_READFILE)) return_value = CURL_FORMADD_OPTION_TWICE; else { const char *filename = array_state? array_value:va_arg(params, char *); if(filename) { current_form->value = strdup(filename); if(!current_form->value) return_value = CURL_FORMADD_MEMORY; else { current_form->flags |= HTTPPOST_READFILE; current_form->value_alloc = TRUE; } } else return_value = CURL_FORMADD_NULL; } break; /* We upload a file */ case CURLFORM_FILE: { const char *filename = array_state?array_value: va_arg(params, char *); if(current_form->value) { if(current_form->flags & HTTPPOST_FILENAME) { if(filename) { char *fname = strdup(filename); if(!fname) return_value = CURL_FORMADD_MEMORY; else { form = AddFormInfo(fname, NULL, current_form); if(!form) { free(fname); return_value = CURL_FORMADD_MEMORY; } else { form->value_alloc = TRUE; current_form = form; form = NULL; } } } else return_value = CURL_FORMADD_NULL; } else return_value = CURL_FORMADD_OPTION_TWICE; } else { if(filename) { current_form->value = strdup(filename); if(!current_form->value) return_value = CURL_FORMADD_MEMORY; else { current_form->flags |= HTTPPOST_FILENAME; current_form->value_alloc = TRUE; } } else return_value = CURL_FORMADD_NULL; } break; } case CURLFORM_BUFFERPTR: current_form->flags |= HTTPPOST_PTRBUFFER|HTTPPOST_BUFFER; if(current_form->buffer) return_value = CURL_FORMADD_OPTION_TWICE; else { char *buffer = array_state?array_value:va_arg(params, char *); if(buffer) { current_form->buffer = buffer; /* store for the moment */ current_form->value = buffer; /* make it non-NULL to be accepted as fine */ } else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_BUFFERLENGTH: if(current_form->bufferlength) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->bufferlength = array_state?(size_t)array_value:(size_t)va_arg(params, long); break; case CURLFORM_STREAM: current_form->flags |= HTTPPOST_CALLBACK; if(current_form->userp) return_value = CURL_FORMADD_OPTION_TWICE; else { char *userp = array_state?array_value:va_arg(params, char *); if(userp) { current_form->userp = userp; current_form->value = userp; /* this isn't strictly true but we derive a value from this later on and we need this non-NULL to be accepted as a fine form part */ } else return_value = CURL_FORMADD_NULL; } break; case CURLFORM_CONTENTTYPE: { const char *contenttype = array_state?array_value:va_arg(params, char *); if(current_form->contenttype) { if(current_form->flags & HTTPPOST_FILENAME) { if(contenttype) { char *type = strdup(contenttype); if(!type) return_value = CURL_FORMADD_MEMORY; else { form = AddFormInfo(NULL, type, current_form); if(!form) { free(type); return_value = CURL_FORMADD_MEMORY; } else { form->contenttype_alloc = TRUE; current_form = form; form = NULL; } } } else return_value = CURL_FORMADD_NULL; } else return_value = CURL_FORMADD_OPTION_TWICE; } else { if(contenttype) { current_form->contenttype = strdup(contenttype); if(!current_form->contenttype) return_value = CURL_FORMADD_MEMORY; else current_form->contenttype_alloc = TRUE; } else return_value = CURL_FORMADD_NULL; } break; } case CURLFORM_CONTENTHEADER: { /* this "cast increases required alignment of target type" but we consider it OK anyway */ struct curl_slist *list = array_state? (struct curl_slist *)(void *)array_value: va_arg(params, struct curl_slist *); if(current_form->contentheader) return_value = CURL_FORMADD_OPTION_TWICE; else current_form->contentheader = list; break; } case CURLFORM_FILENAME: case CURLFORM_BUFFER: { const char *filename = array_state?array_value: va_arg(params, char *); if(current_form->showfilename) return_value = CURL_FORMADD_OPTION_TWICE; else { current_form->showfilename = strdup(filename); if(!current_form->showfilename) return_value = CURL_FORMADD_MEMORY; else current_form->showfilename_alloc = TRUE; } break; } default: return_value = CURL_FORMADD_UNKNOWN_OPTION; break; } } if(CURL_FORMADD_OK != return_value) { /* On error, free allocated fields for all nodes of the FormInfo linked list without deallocating nodes. List nodes are deallocated later on */ struct FormInfo *ptr; for(ptr = first_form; ptr != NULL; ptr = ptr->more) { if(ptr->name_alloc) { Curl_safefree(ptr->name); ptr->name_alloc = FALSE; } if(ptr->value_alloc) { Curl_safefree(ptr->value); ptr->value_alloc = FALSE; } if(ptr->contenttype_alloc) { Curl_safefree(ptr->contenttype); ptr->contenttype_alloc = FALSE; } if(ptr->showfilename_alloc) { Curl_safefree(ptr->showfilename); ptr->showfilename_alloc = FALSE; } } } if(CURL_FORMADD_OK == return_value) { /* go through the list, check for completeness and if everything is * alright add the HttpPost item otherwise set return_value accordingly */ post = NULL; for(form = first_form; form != NULL; form = form->more) { if(((!form->name || !form->value) && !post) || ( (form->contentslength) && (form->flags & HTTPPOST_FILENAME) ) || ( (form->flags & HTTPPOST_FILENAME) && (form->flags & HTTPPOST_PTRCONTENTS) ) || ( (!form->buffer) && (form->flags & HTTPPOST_BUFFER) && (form->flags & HTTPPOST_PTRBUFFER) ) || ( (form->flags & HTTPPOST_READFILE) && (form->flags & HTTPPOST_PTRCONTENTS) ) ) { return_value = CURL_FORMADD_INCOMPLETE; break; } if(((form->flags & HTTPPOST_FILENAME) || (form->flags & HTTPPOST_BUFFER)) && !form->contenttype) { char *f = (form->flags & HTTPPOST_BUFFER)? form->showfilename : form->value; char const *type; type = Curl_mime_contenttype(f); if(!type) type = prevtype; if(!type) type = FILE_CONTENTTYPE_DEFAULT; /* our contenttype is missing */ form->contenttype = strdup(type); if(!form->contenttype) { return_value = CURL_FORMADD_MEMORY; break; } form->contenttype_alloc = TRUE; } if(form->name && form->namelength) { /* Name should not contain nul bytes. */ size_t i; for(i = 0; i < form->namelength; i++) if(!form->name[i]) { return_value = CURL_FORMADD_NULL; break; } if(return_value != CURL_FORMADD_OK) break; } if(!(form->flags & HTTPPOST_PTRNAME) && (form == first_form) ) { /* Note that there's small risk that form->name is NULL here if the app passed in a bad combo, so we better check for that first. */ if(form->name) { /* copy name (without strdup; possibly not null-terminated) */ form->name = Curl_memdup(form->name, form->namelength? form->namelength: strlen(form->name) + 1); } if(!form->name) { return_value = CURL_FORMADD_MEMORY; break; } form->name_alloc = TRUE; } if(!(form->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE | HTTPPOST_PTRCONTENTS | HTTPPOST_PTRBUFFER | HTTPPOST_CALLBACK)) && form->value) { /* copy value (without strdup; possibly contains null characters) */ size_t clen = (size_t) form->contentslength; if(!clen) clen = strlen(form->value) + 1; form->value = Curl_memdup(form->value, clen); if(!form->value) { return_value = CURL_FORMADD_MEMORY; break; } form->value_alloc = TRUE; } post = AddHttpPost(form->name, form->namelength, form->value, form->contentslength, form->buffer, form->bufferlength, form->contenttype, form->flags, form->contentheader, form->showfilename, form->userp, post, httppost, last_post); if(!post) { return_value = CURL_FORMADD_MEMORY; break; } if(form->contenttype) prevtype = form->contenttype; } if(CURL_FORMADD_OK != return_value) { /* On error, free allocated fields for nodes of the FormInfo linked list which are not already owned by the httppost linked list without deallocating nodes. List nodes are deallocated later on */ struct FormInfo *ptr; for(ptr = form; ptr != NULL; ptr = ptr->more) { if(ptr->name_alloc) { Curl_safefree(ptr->name); ptr->name_alloc = FALSE; } if(ptr->value_alloc) { Curl_safefree(ptr->value); ptr->value_alloc = FALSE; } if(ptr->contenttype_alloc) { Curl_safefree(ptr->contenttype); ptr->contenttype_alloc = FALSE; } if(ptr->showfilename_alloc) { Curl_safefree(ptr->showfilename); ptr->showfilename_alloc = FALSE; } } } } /* Always deallocate FormInfo linked list nodes without touching node fields given that these have either been deallocated or are owned now by the httppost linked list */ while(first_form) { struct FormInfo *ptr = first_form->more; free(first_form); first_form = ptr; } return return_value; } /* * curl_formadd() is a public API to add a section to the multipart formpost. * * @unittest: 1308 */ CURLFORMcode curl_formadd(struct curl_httppost **httppost, struct curl_httppost **last_post, ...) { va_list arg; CURLFORMcode result; va_start(arg, last_post); result = FormAdd(httppost, last_post, arg); va_end(arg); return result; } /* * curl_formget() * Serialize a curl_httppost struct. * Returns 0 on success. * * @unittest: 1308 */ int curl_formget(struct curl_httppost *form, void *arg, curl_formget_callback append) { CURLcode result; curl_mimepart toppart; Curl_mime_initpart(&toppart, NULL); /* default form is empty */ result = Curl_getformdata(NULL, &toppart, form, NULL); if(!result) result = Curl_mime_prepare_headers(&toppart, "multipart/form-data", NULL, MIMESTRATEGY_FORM); while(!result) { char buffer[8192]; size_t nread = Curl_mime_read(buffer, 1, sizeof(buffer), &toppart); if(!nread) break; if(nread > sizeof(buffer) || append(arg, buffer, nread) != nread) { result = CURLE_READ_ERROR; if(nread == CURL_READFUNC_ABORT) result = CURLE_ABORTED_BY_CALLBACK; } } Curl_mime_cleanpart(&toppart); return (int) result; } /* * curl_formfree() is an external function to free up a whole form post * chain */ void curl_formfree(struct curl_httppost *form) { struct curl_httppost *next; if(!form) /* no form to free, just get out of this */ return; do { next = form->next; /* the following form line */ /* recurse to sub-contents */ curl_formfree(form->more); if(!(form->flags & HTTPPOST_PTRNAME)) free(form->name); /* free the name */ if(!(form->flags & (HTTPPOST_PTRCONTENTS|HTTPPOST_BUFFER|HTTPPOST_CALLBACK)) ) free(form->contents); /* free the contents */ free(form->contenttype); /* free the content type */ free(form->showfilename); /* free the faked file name */ free(form); /* free the struct */ form = next; } while(form); /* continue */ } /* Set mime part name, taking care of non null-terminated name string. */ static CURLcode setname(curl_mimepart *part, const char *name, size_t len) { char *zname; CURLcode res; if(!name || !len) return curl_mime_name(part, name); zname = malloc(len + 1); if(!zname) return CURLE_OUT_OF_MEMORY; memcpy(zname, name, len); zname[len] = '\0'; res = curl_mime_name(part, zname); free(zname); return res; } /* * Curl_getformdata() converts a linked list of "meta data" into a mime * structure. The input list is in 'post', while the output is stored in * mime part at '*finalform'. * * This function will not do a failf() for the potential memory failures but * should for all other errors it spots. Just note that this function MAY get * a NULL pointer in the 'data' argument. */ CURLcode Curl_getformdata(struct Curl_easy *data, curl_mimepart *finalform, struct curl_httppost *post, curl_read_callback fread_func) { CURLcode result = CURLE_OK; curl_mime *form = NULL; curl_mimepart *part; struct curl_httppost *file; Curl_mime_cleanpart(finalform); /* default form is empty */ if(!post) return result; /* no input => no output! */ form = curl_mime_init(data); if(!form) result = CURLE_OUT_OF_MEMORY; if(!result) result = curl_mime_subparts(finalform, form); /* Process each top part. */ for(; !result && post; post = post->next) { /* If we have more than a file here, create a mime subpart and fill it. */ curl_mime *multipart = form; if(post->more) { part = curl_mime_addpart(form); if(!part) result = CURLE_OUT_OF_MEMORY; if(!result) result = setname(part, post->name, post->namelength); if(!result) { multipart = curl_mime_init(data); if(!multipart) result = CURLE_OUT_OF_MEMORY; } if(!result) result = curl_mime_subparts(part, multipart); } /* Generate all the part contents. */ for(file = post; !result && file; file = file->more) { /* Create the part. */ part = curl_mime_addpart(multipart); if(!part) result = CURLE_OUT_OF_MEMORY; /* Set the headers. */ if(!result) result = curl_mime_headers(part, file->contentheader, 0); /* Set the content type. */ if(!result && file->contenttype) result = curl_mime_type(part, file->contenttype); /* Set field name. */ if(!result && !post->more) result = setname(part, post->name, post->namelength); /* Process contents. */ if(!result) { curl_off_t clen = post->contentslength; if(post->flags & CURL_HTTPPOST_LARGE) clen = post->contentlen; if(post->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE)) { if(!strcmp(file->contents, "-")) { /* There are a few cases where the code below won't work; in particular, freopen(stdin) by the caller is not guaranteed to result as expected. This feature has been kept for backward compatibility: use of "-" pseudo file name should be avoided. */ result = curl_mime_data_cb(part, (curl_off_t) -1, (curl_read_callback) fread, CURLX_FUNCTION_CAST(curl_seek_callback, fseek), NULL, (void *) stdin); } else result = curl_mime_filedata(part, file->contents); if(!result && (post->flags & HTTPPOST_READFILE)) result = curl_mime_filename(part, NULL); } else if(post->flags & HTTPPOST_BUFFER) result = curl_mime_data(part, post->buffer, post->bufferlength? post->bufferlength: -1); else if(post->flags & HTTPPOST_CALLBACK) { /* the contents should be read with the callback and the size is set with the contentslength */ if(!clen) clen = -1; result = curl_mime_data_cb(part, clen, fread_func, NULL, NULL, post->userp); } else { size_t uclen; if(!clen) uclen = CURL_ZERO_TERMINATED; else uclen = (size_t)clen; result = curl_mime_data(part, post->contents, uclen); #ifdef CURL_DOES_CONVERSIONS /* Convert textual contents now. */ if(!result && data && part->datasize) result = Curl_convert_to_network(data, part->data, part->datasize); #endif } } /* Set fake file name. */ if(!result && post->showfilename) if(post->more || (post->flags & (HTTPPOST_FILENAME | HTTPPOST_BUFFER | HTTPPOST_CALLBACK))) result = curl_mime_filename(part, post->showfilename); } } if(result) Curl_mime_cleanpart(finalform); return result; } #else /* if disabled */ CURLFORMcode curl_formadd(struct curl_httppost **httppost, struct curl_httppost **last_post, ...) { (void)httppost; (void)last_post; return CURL_FORMADD_DISABLED; } int curl_formget(struct curl_httppost *form, void *arg, curl_formget_callback append) { (void) form; (void) arg; (void) append; return CURL_FORMADD_DISABLED; } void curl_formfree(struct curl_httppost *form) { (void)form; /* does nothing HTTP is disabled */ } #endif /* if disabled */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/c-hyper.h
#ifndef HEADER_CURL_HYPER_H #define HEADER_CURL_HYPER_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) #include <hyper.h> /* per-transfer data for the Hyper backend */ struct hyptransfer { hyper_waker *write_waker; hyper_waker *read_waker; const hyper_executor *exec; hyper_task *endtask; hyper_waker *exp100_waker; }; size_t Curl_hyper_recv(void *userp, hyper_context *ctx, uint8_t *buf, size_t buflen); size_t Curl_hyper_send(void *userp, hyper_context *ctx, const uint8_t *buf, size_t buflen); CURLcode Curl_hyper_stream(struct Curl_easy *data, struct connectdata *conn, int *didwhat, bool *done, int select_res); CURLcode Curl_hyper_header(struct Curl_easy *data, hyper_headers *headers, const char *line); void Curl_hyper_done(struct Curl_easy *); #else #define Curl_hyper_done(x) #endif /* !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) */ #endif /* HEADER_CURL_HYPER_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/config-plan9.h
#ifndef HEADER_CURL_CONFIG_PLAN9_H #define HEADER_CURL_CONFIG_PLAN9_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #define BUILDING_LIBCURL 1 #define CURL_CA_BUNDLE "/sys/lib/tls/ca.pem" #define CURL_CA_PATH "/sys/lib/tls" #define CURL_STATICLIB 1 #define ENABLE_IPV6 1 #define CURL_DISABLE_LDAP 1 #define NEED_REENTRANT 1 #define OS "plan9" #define PACKAGE "curl" #define PACKAGE_NAME "curl" #define PACKAGE_BUGREPORT "a suitable mailing list: https://curl.se/mail/" #define PACKAGE_STRING "curl -" #define PACKAGE_TARNAME "curl" #define PACKAGE_VERSION "-" #define RANDOM_FILE "/dev/random" #define VERSION "0.0.0" /* TODO */ #define STDC_HEADERS 1 #ifdef _BITS64 #error not implement #else #define SIZEOF_INT 4 #define SIZEOF_SHORT 2 #define SIZEOF_LONG 4 #define SIZEOF_OFF_T 8 #define SIZEOF_CURL_OFF_T 4 /* curl_off_t = timediff_t = int */ #define SIZEOF_SIZE_T 4 #define SIZEOF_TIME_T 4 #endif #define HAVE_RECV 1 #define RECV_TYPE_ARG1 int #define RECV_TYPE_ARG2 void * #define RECV_TYPE_ARG3 int #define RECV_TYPE_ARG4 int #define RECV_TYPE_RETV int #define HAVE_RECVFROM 1 #define RECVFROM_TYPE_ARG1 int #define RECVFROM_TYPE_ARG2 void #define RECVFROM_TYPE_ARG2_IS_VOID 1 #define RECVFROM_TYPE_ARG3 int #define RECVFROM_TYPE_ARG4 int #define RECVFROM_TYPE_ARG5 void #define RECVFROM_TYPE_ARG5_IS_VOID 1 #define RECVFROM_TYPE_ARG6 int #define RECVFROM_TYPE_ARG6_IS_VOID 1 #define RECVFROM_TYPE_RETV int #define HAVE_SELECT 1 #define SELECT_TYPE_ARG1 int #define SELECT_TYPE_ARG234 fd_set * #define SELECT_TYPE_ARG5 struct timeval * #define SELECT_TYPE_RETV int #define HAVE_SEND 1 #define SEND_TYPE_ARG1 int #define SEND_TYPE_ARG2 void * #define SEND_QUAL_ARG2 #define SEND_TYPE_ARG3 int #define SEND_TYPE_ARG4 int #define SEND_TYPE_RETV int #define HAVE_ALARM 1 #define HAVE_ARPA_INET_H 1 #define HAVE_ASSERT_H 1 #define HAVE_BASENAME 1 #define HAVE_BOOL_T 1 #define HAVE_CRYPTO_CLEANUP_ALL_EX_DATA 1 #define HAVE_ERRNO_H 1 #define HAVE_FCNTL 1 #define HAVE_FCNTL_H 1 #define HAVE_FREEADDRINFO 1 #define HAVE_FTRUNCATE 1 #define HAVE_GETADDRINFO 1 #define HAVE_GETEUID 1 #define HAVE_GETHOSTBYNAME 1 #define HAVE_GETHOSTNAME 1 #define HAVE_GETPPID 1 #define HAVE_GETPROTOBYNAME 1 #define HAVE_GETPWUID 1 #define HAVE_GETTIMEOFDAY 1 #define HAVE_GMTIME_R 1 #define HAVE_INET_ADDR 1 #define HAVE_INET_NTOP 1 #define HAVE_INET_PTON 1 #define HAVE_INTTYPES_H 1 #define HAVE_IOCTL 1 #define HAVE_LIBGEN_H 1 #define HAVE_LIBZ 1 #define HAVE_LL 1 #define HAVE_LOCALE_H 1 #define HAVE_LOCALTIME_R 1 #define HAVE_LONGLONG 1 #define HAVE_NETDB_H 1 #define HAVE_NETINET_IN_H 1 #define HAVE_NETINET_TCP_H 1 #define HAVE_PWD_H 1 #define HAVE_SYS_SELECT_H 1 #define USE_OPENSSL 1 #define HAVE_OPENSSL_CRYPTO_H 1 #define HAVE_OPENSSL_ERR_H 1 #define HAVE_OPENSSL_PEM_H 1 #define HAVE_OPENSSL_PKCS12_H 1 #define HAVE_OPENSSL_RSA_H 1 #define HAVE_OPENSSL_SSL_H 1 #define HAVE_OPENSSL_X509_H 1 #define HAVE_PIPE 1 #define HAVE_POLL 1 #define HAVE_POLL_FINE 1 #define HAVE_POLL_H 1 #define HAVE_PTHREAD_H 1 #define HAVE_RAND_STATUS 1 #define HAVE_SETJMP_H 1 #define HAVE_SETLOCALE 1 #define HAVE_SETSOCKOPT 1 #define HAVE_SOCK_OPTS 1 /* for /sys/include/ape/sys/socket.h */ #define HAVE_SIGACTION 1 #define HAVE_SIGNAL 1 #define HAVE_SIGNAL_H 1 #define HAVE_SIGSETJMP 1 #define HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID 1 #define HAVE_SOCKET 1 #define HAVE_SSL_GET_SHUTDOWN 1 #define HAVE_STDBOOL_H 1 #define HAVE_STDINT_H 1 #define HAVE_STDIO_H 1 #define HAVE_STDLIB_H 1 #define HAVE_STRCASECMP 1 #define HAVE_STRDUP 1 #define HAVE_STRING_H 1 #define HAVE_STRSTR 1 #define HAVE_STRTOK_R 1 #define HAVE_STRTOLL 1 #define HAVE_STRUCT_TIMEVAL 1 #define HAVE_SYS_IOCTL_H 1 #define HAVE_SYS_PARAM_H 1 #define HAVE_SYS_RESOURCE_H 1 #define HAVE_SYS_SOCKET_H 1 #define HAVE_SYS_STAT_H 1 #define HAVE_SYS_TIME_H 1 #define HAVE_SYS_TYPES_H 1 #define HAVE_SYS_UIO_H 1 #define HAVE_SYS_UN_H 1 #define HAVE_TERMIOS_H 1 #define HAVE_TIME_H 1 #define HAVE_UNAME 1 #define HAVE_UNISTD_H 1 #define HAVE_UTIME 1 #define HAVE_UTIME_H 1 #define HAVE_WRITEV 1 #define HAVE_ZLIB_H 1 #define HAVE_POSIX_STRERROR_R 1 #define HAVE_STRERROR_R 1 #define STRERROR_R_TYPE_ARG3 int #define TIME_WITH_SYS_TIME 1 #define USE_MANUAL 1 #define __attribute__(x) #ifndef __cplusplus #undef inline #endif #endif /* HEADER_CURL_CONFIG_PLAN9_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/http_negotiate.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && defined(USE_SPNEGO) #include "urldata.h" #include "sendf.h" #include "http_negotiate.h" #include "vauth/vauth.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" CURLcode Curl_input_negotiate(struct Curl_easy *data, struct connectdata *conn, bool proxy, const char *header) { CURLcode result; size_t len; /* Point to the username, password, service and host */ const char *userp; const char *passwdp; const char *service; const char *host; /* Point to the correct struct with this */ struct negotiatedata *neg_ctx; curlnegotiate state; if(proxy) { #ifndef CURL_DISABLE_PROXY userp = conn->http_proxy.user; passwdp = conn->http_proxy.passwd; service = data->set.str[STRING_PROXY_SERVICE_NAME] ? data->set.str[STRING_PROXY_SERVICE_NAME] : "HTTP"; host = conn->http_proxy.host.name; neg_ctx = &conn->proxyneg; state = conn->proxy_negotiate_state; #else return CURLE_NOT_BUILT_IN; #endif } else { userp = conn->user; passwdp = conn->passwd; service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : "HTTP"; host = conn->host.name; neg_ctx = &conn->negotiate; state = conn->http_negotiate_state; } /* Not set means empty */ if(!userp) userp = ""; if(!passwdp) passwdp = ""; /* Obtain the input token, if any */ header += strlen("Negotiate"); while(*header && ISSPACE(*header)) header++; len = strlen(header); neg_ctx->havenegdata = len != 0; if(!len) { if(state == GSS_AUTHSUCC) { infof(data, "Negotiate auth restarted"); Curl_http_auth_cleanup_negotiate(conn); } else if(state != GSS_AUTHNONE) { /* The server rejected our authentication and hasn't supplied any more negotiation mechanisms */ Curl_http_auth_cleanup_negotiate(conn); return CURLE_LOGIN_DENIED; } } /* Supports SSL channel binding for Windows ISS extended protection */ #if defined(USE_WINDOWS_SSPI) && defined(SECPKG_ATTR_ENDPOINT_BINDINGS) neg_ctx->sslContext = conn->sslContext; #endif /* Initialize the security context and decode our challenge */ result = Curl_auth_decode_spnego_message(data, userp, passwdp, service, host, header, neg_ctx); if(result) Curl_http_auth_cleanup_negotiate(conn); return result; } CURLcode Curl_output_negotiate(struct Curl_easy *data, struct connectdata *conn, bool proxy) { struct negotiatedata *neg_ctx = proxy ? &conn->proxyneg : &conn->negotiate; struct auth *authp = proxy ? &data->state.authproxy : &data->state.authhost; curlnegotiate *state = proxy ? &conn->proxy_negotiate_state : &conn->http_negotiate_state; char *base64 = NULL; size_t len = 0; char *userp; CURLcode result; authp->done = FALSE; if(*state == GSS_AUTHRECV) { if(neg_ctx->havenegdata) { neg_ctx->havemultiplerequests = TRUE; } } else if(*state == GSS_AUTHSUCC) { if(!neg_ctx->havenoauthpersist) { neg_ctx->noauthpersist = !neg_ctx->havemultiplerequests; } } if(neg_ctx->noauthpersist || (*state != GSS_AUTHDONE && *state != GSS_AUTHSUCC)) { if(neg_ctx->noauthpersist && *state == GSS_AUTHSUCC) { infof(data, "Curl_output_negotiate, " "no persistent authentication: cleanup existing context"); Curl_http_auth_cleanup_negotiate(conn); } if(!neg_ctx->context) { result = Curl_input_negotiate(data, conn, proxy, "Negotiate"); if(result == CURLE_AUTH_ERROR) { /* negotiate auth failed, let's continue unauthenticated to stay * compatible with the behavior before curl-7_64_0-158-g6c6035532 */ authp->done = TRUE; return CURLE_OK; } else if(result) return result; } result = Curl_auth_create_spnego_message(data, neg_ctx, &base64, &len); if(result) return result; userp = aprintf("%sAuthorization: Negotiate %s\r\n", proxy ? "Proxy-" : "", base64); if(proxy) { Curl_safefree(data->state.aptr.proxyuserpwd); data->state.aptr.proxyuserpwd = userp; } else { Curl_safefree(data->state.aptr.userpwd); data->state.aptr.userpwd = userp; } free(base64); if(!userp) { return CURLE_OUT_OF_MEMORY; } *state = GSS_AUTHSENT; #ifdef HAVE_GSSAPI if(neg_ctx->status == GSS_S_COMPLETE || neg_ctx->status == GSS_S_CONTINUE_NEEDED) { *state = GSS_AUTHDONE; } #else #ifdef USE_WINDOWS_SSPI if(neg_ctx->status == SEC_E_OK || neg_ctx->status == SEC_I_CONTINUE_NEEDED) { *state = GSS_AUTHDONE; } #endif #endif } if(*state == GSS_AUTHDONE || *state == GSS_AUTHSUCC) { /* connection is already authenticated, * don't send a header in future requests */ authp->done = TRUE; } neg_ctx->havenegdata = FALSE; return CURLE_OK; } void Curl_http_auth_cleanup_negotiate(struct connectdata *conn) { conn->http_negotiate_state = GSS_AUTHNONE; conn->proxy_negotiate_state = GSS_AUTHNONE; Curl_auth_cleanup_spnego(&conn->negotiate); Curl_auth_cleanup_spnego(&conn->proxyneg); } #endif /* !CURL_DISABLE_HTTP && USE_SPNEGO */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_gethostname.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include "curl_gethostname.h" /* * Curl_gethostname() is a wrapper around gethostname() which allows * overriding the host name that the function would normally return. * This capability is used by the test suite to verify exact matching * of NTLM authentication, which exercises libcurl's MD4 and DES code * as well as by the SMTP module when a hostname is not provided. * * For libcurl debug enabled builds host name overriding takes place * when environment variable CURL_GETHOSTNAME is set, using the value * held by the variable to override returned host name. * * Note: The function always returns the un-qualified hostname rather * than being provider dependent. * * For libcurl shared library release builds the test suite preloads * another shared library named libhostname using the LD_PRELOAD * mechanism which intercepts, and might override, the gethostname() * function call. In this case a given platform must support the * LD_PRELOAD mechanism and additionally have environment variable * CURL_GETHOSTNAME set in order to override the returned host name. * * For libcurl static library release builds no overriding takes place. */ int Curl_gethostname(char * const name, GETHOSTNAME_TYPE_ARG2 namelen) { #ifndef HAVE_GETHOSTNAME /* Allow compilation and return failure when unavailable */ (void) name; (void) namelen; return -1; #else int err; char *dot; #ifdef DEBUGBUILD /* Override host name when environment variable CURL_GETHOSTNAME is set */ const char *force_hostname = getenv("CURL_GETHOSTNAME"); if(force_hostname) { strncpy(name, force_hostname, namelen); err = 0; } else { name[0] = '\0'; err = gethostname(name, namelen); } #else /* DEBUGBUILD */ /* The call to system's gethostname() might get intercepted by the libhostname library when libcurl is built as a non-debug shared library when running the test suite. */ name[0] = '\0'; err = gethostname(name, namelen); #endif name[namelen - 1] = '\0'; if(err) return err; /* Truncate domain, leave only machine name */ dot = strchr(name, '.'); if(dot) *dot = '\0'; return 0; #endif }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/llist.h
#ifndef HEADER_CURL_LLIST_H #define HEADER_CURL_LLIST_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <stddef.h> typedef void (*Curl_llist_dtor)(void *, void *); struct Curl_llist_element { void *ptr; struct Curl_llist_element *prev; struct Curl_llist_element *next; }; struct Curl_llist { struct Curl_llist_element *head; struct Curl_llist_element *tail; Curl_llist_dtor dtor; size_t size; }; void Curl_llist_init(struct Curl_llist *, Curl_llist_dtor); void Curl_llist_insert_next(struct Curl_llist *, struct Curl_llist_element *, const void *, struct Curl_llist_element *node); void Curl_llist_remove(struct Curl_llist *, struct Curl_llist_element *, void *); size_t Curl_llist_count(struct Curl_llist *); void Curl_llist_destroy(struct Curl_llist *, void *); #endif /* HEADER_CURL_LLIST_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/slist.h
#ifndef HEADER_CURL_SLIST_H #define HEADER_CURL_SLIST_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /* * Curl_slist_duplicate() duplicates a linked list. It always returns the * address of the first record of the cloned list or NULL in case of an * error (or if the input list was NULL). */ struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist); /* * Curl_slist_append_nodup() takes ownership of the given string and appends * it to the list. */ struct curl_slist *Curl_slist_append_nodup(struct curl_slist *list, char *data); #endif /* HEADER_CURL_SLIST_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_threads.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #if defined(USE_THREADS_POSIX) # ifdef HAVE_PTHREAD_H # include <pthread.h> # endif #elif defined(USE_THREADS_WIN32) # ifdef HAVE_PROCESS_H # include <process.h> # endif #endif #include "curl_threads.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" #if defined(USE_THREADS_POSIX) struct Curl_actual_call { unsigned int (*func)(void *); void *arg; }; static void *curl_thread_create_thunk(void *arg) { struct Curl_actual_call *ac = arg; unsigned int (*func)(void *) = ac->func; void *real_arg = ac->arg; free(ac); (*func)(real_arg); return 0; } curl_thread_t Curl_thread_create(unsigned int (*func) (void *), void *arg) { curl_thread_t t = malloc(sizeof(pthread_t)); struct Curl_actual_call *ac = malloc(sizeof(struct Curl_actual_call)); if(!(ac && t)) goto err; ac->func = func; ac->arg = arg; if(pthread_create(t, NULL, curl_thread_create_thunk, ac) != 0) goto err; return t; err: free(t); free(ac); return curl_thread_t_null; } void Curl_thread_destroy(curl_thread_t hnd) { if(hnd != curl_thread_t_null) { pthread_detach(*hnd); free(hnd); } } int Curl_thread_join(curl_thread_t *hnd) { int ret = (pthread_join(**hnd, NULL) == 0); free(*hnd); *hnd = curl_thread_t_null; return ret; } #elif defined(USE_THREADS_WIN32) /* !checksrc! disable SPACEBEFOREPAREN 1 */ curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *), void *arg) { #ifdef _WIN32_WCE typedef HANDLE curl_win_thread_handle_t; #elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) typedef unsigned long curl_win_thread_handle_t; #else typedef uintptr_t curl_win_thread_handle_t; #endif curl_thread_t t; curl_win_thread_handle_t thread_handle; #ifdef _WIN32_WCE thread_handle = CreateThread(NULL, 0, func, arg, 0, NULL); #else thread_handle = _beginthreadex(NULL, 0, func, arg, 0, NULL); #endif t = (curl_thread_t)thread_handle; if((t == 0) || (t == LongToHandle(-1L))) { #ifdef _WIN32_WCE DWORD gle = GetLastError(); errno = ((gle == ERROR_ACCESS_DENIED || gle == ERROR_NOT_ENOUGH_MEMORY) ? EACCES : EINVAL); #endif return curl_thread_t_null; } return t; } void Curl_thread_destroy(curl_thread_t hnd) { CloseHandle(hnd); } int Curl_thread_join(curl_thread_t *hnd) { #if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \ (_WIN32_WINNT < _WIN32_WINNT_VISTA) int ret = (WaitForSingleObject(*hnd, INFINITE) == WAIT_OBJECT_0); #else int ret = (WaitForSingleObjectEx(*hnd, INFINITE, FALSE) == WAIT_OBJECT_0); #endif Curl_thread_destroy(*hnd); *hnd = curl_thread_t_null; return ret; } #endif /* USE_THREADS_* */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/setopt.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <limits.h> #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_LINUX_TCP_H #include <linux/tcp.h> #elif defined(HAVE_NETINET_TCP_H) #include <netinet/tcp.h> #endif #include "urldata.h" #include "url.h" #include "progress.h" #include "content_encoding.h" #include "strcase.h" #include "share.h" #include "vtls/vtls.h" #include "warnless.h" #include "sendf.h" #include "http2.h" #include "setopt.h" #include "multiif.h" #include "altsvc.h" #include "hsts.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" CURLcode Curl_setstropt(char **charp, const char *s) { /* Release the previous storage at `charp' and replace by a dynamic storage copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */ Curl_safefree(*charp); if(s) { char *str = strdup(s); if(str) { size_t len = strlen(str); if(len > CURL_MAX_INPUT_LENGTH) { free(str); return CURLE_BAD_FUNCTION_ARGUMENT; } } if(!str) return CURLE_OUT_OF_MEMORY; *charp = str; } return CURLE_OK; } CURLcode Curl_setblobopt(struct curl_blob **blobp, const struct curl_blob *blob) { /* free the previous storage at `blobp' and replace by a dynamic storage copy of blob. If CURL_BLOB_COPY is set, the data is copied. */ Curl_safefree(*blobp); if(blob) { struct curl_blob *nblob; if(blob->len > CURL_MAX_INPUT_LENGTH) return CURLE_BAD_FUNCTION_ARGUMENT; nblob = (struct curl_blob *) malloc(sizeof(struct curl_blob) + ((blob->flags & CURL_BLOB_COPY) ? blob->len : 0)); if(!nblob) return CURLE_OUT_OF_MEMORY; *nblob = *blob; if(blob->flags & CURL_BLOB_COPY) { /* put the data after the blob struct in memory */ nblob->data = (char *)nblob + sizeof(struct curl_blob); memcpy(nblob->data, blob->data, blob->len); } *blobp = nblob; return CURLE_OK; } return CURLE_OK; } static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp) { CURLcode result = CURLE_OK; char *user = NULL; char *passwd = NULL; /* Parse the login details if specified. It not then we treat NULL as a hint to clear the existing data */ if(option) { result = Curl_parse_login_details(option, strlen(option), (userp ? &user : NULL), (passwdp ? &passwd : NULL), NULL); } if(!result) { /* Store the username part of option if required */ if(userp) { if(!user && option && option[0] == ':') { /* Allocate an empty string instead of returning NULL as user name */ user = strdup(""); if(!user) result = CURLE_OUT_OF_MEMORY; } Curl_safefree(*userp); *userp = user; } /* Store the password part of option if required */ if(passwdp) { Curl_safefree(*passwdp); *passwdp = passwd; } } return result; } #define C_SSLVERSION_VALUE(x) (x & 0xffff) #define C_SSLVERSION_MAX_VALUE(x) (x & 0xffff0000) /* * Do not make Curl_vsetopt() static: it is called from * packages/OS400/ccsidcurl.c. */ CURLcode Curl_vsetopt(struct Curl_easy *data, CURLoption option, va_list param) { char *argptr; CURLcode result = CURLE_OK; long arg; unsigned long uarg; curl_off_t bigsize; switch(option) { case CURLOPT_DNS_CACHE_TIMEOUT: arg = va_arg(param, long); if(arg < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.dns_cache_timeout = arg; break; case CURLOPT_DNS_USE_GLOBAL_CACHE: /* deprecated */ break; case CURLOPT_SSL_CIPHER_LIST: /* set a list of cipher we want to use in the SSL connection */ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER_LIST], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSL_CIPHER_LIST: /* set a list of cipher we want to use in the SSL connection for proxy */ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER_LIST_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_TLS13_CIPHERS: if(Curl_ssl_tls13_ciphersuites()) { /* set preferred list of TLS 1.3 cipher suites */ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER13_LIST], va_arg(param, char *)); } else return CURLE_NOT_BUILT_IN; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_TLS13_CIPHERS: if(Curl_ssl_tls13_ciphersuites()) { /* set preferred list of TLS 1.3 cipher suites for proxy */ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER13_LIST_PROXY], va_arg(param, char *)); } else return CURLE_NOT_BUILT_IN; break; #endif case CURLOPT_RANDOM_FILE: /* * This is the path name to a file that contains random data to seed * the random SSL stuff with. The file is only used for reading. */ result = Curl_setstropt(&data->set.str[STRING_SSL_RANDOM_FILE], va_arg(param, char *)); break; case CURLOPT_EGDSOCKET: /* * The Entropy Gathering Daemon socket pathname */ result = Curl_setstropt(&data->set.str[STRING_SSL_EGDSOCKET], va_arg(param, char *)); break; case CURLOPT_MAXCONNECTS: /* * Set the absolute number of maximum simultaneous alive connection that * libcurl is allowed to have. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.maxconnects = arg; break; case CURLOPT_FORBID_REUSE: /* * When this transfer is done, it must not be left to be reused by a * subsequent transfer but shall be closed immediately. */ data->set.reuse_forbid = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FRESH_CONNECT: /* * This transfer shall not use a previously cached connection but * should be made with a fresh new connect! */ data->set.reuse_fresh = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_VERBOSE: /* * Verbose means infof() calls that give a lot of information about * the connection and transfer procedures as well as internal choices. */ data->set.verbose = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_HEADER: /* * Set to include the header in the general data output stream. */ data->set.include_header = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_NOPROGRESS: /* * Shut off the internal supported progress meter */ data->set.hide_progress = (0 != va_arg(param, long)) ? TRUE : FALSE; if(data->set.hide_progress) data->progress.flags |= PGRS_HIDE; else data->progress.flags &= ~PGRS_HIDE; break; case CURLOPT_NOBODY: /* * Do not include the body part in the output data stream. */ data->set.opt_no_body = (0 != va_arg(param, long)) ? TRUE : FALSE; #ifndef CURL_DISABLE_HTTP if(data->set.opt_no_body) /* in HTTP lingo, no body means using the HEAD request... */ data->set.method = HTTPREQ_HEAD; else if(data->set.method == HTTPREQ_HEAD) data->set.method = HTTPREQ_GET; #endif break; case CURLOPT_FAILONERROR: /* * Don't output the >=400 error code HTML-page, but instead only * return error. */ data->set.http_fail_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_KEEP_SENDING_ON_ERROR: data->set.http_keep_sending_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_UPLOAD: case CURLOPT_PUT: /* * We want to sent data to the remote host. If this is HTTP, that equals * using the PUT request. */ data->set.upload = (0 != va_arg(param, long)) ? TRUE : FALSE; if(data->set.upload) { /* If this is HTTP, PUT is what's needed to "upload" */ data->set.method = HTTPREQ_PUT; data->set.opt_no_body = FALSE; /* this is implied */ } else /* In HTTP, the opposite of upload is GET (unless NOBODY is true as then this can be changed to HEAD later on) */ data->set.method = HTTPREQ_GET; break; case CURLOPT_REQUEST_TARGET: result = Curl_setstropt(&data->set.str[STRING_TARGET], va_arg(param, char *)); break; case CURLOPT_FILETIME: /* * Try to get the file time of the remote document. The time will * later (possibly) become available using curl_easy_getinfo(). */ data->set.get_filetime = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SERVER_RESPONSE_TIMEOUT: /* * Option that specifies how quickly an server response must be obtained * before it is considered failure. For pingpong protocols. */ arg = va_arg(param, long); if((arg >= 0) && (arg <= (INT_MAX/1000))) data->set.server_response_timeout = arg * 1000; else return CURLE_BAD_FUNCTION_ARGUMENT; break; #ifndef CURL_DISABLE_TFTP case CURLOPT_TFTP_NO_OPTIONS: /* * Option that prevents libcurl from sending TFTP option requests to the * server. */ data->set.tftp_no_options = va_arg(param, long) != 0; break; case CURLOPT_TFTP_BLKSIZE: /* * TFTP option that specifies the block size to use for data transmission. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.tftp_blksize = arg; break; #endif #ifndef CURL_DISABLE_NETRC case CURLOPT_NETRC: /* * Parse the $HOME/.netrc file */ arg = va_arg(param, long); if((arg < CURL_NETRC_IGNORED) || (arg >= CURL_NETRC_LAST)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.use_netrc = (enum CURL_NETRC_OPTION)arg; break; case CURLOPT_NETRC_FILE: /* * Use this file instead of the $HOME/.netrc file */ result = Curl_setstropt(&data->set.str[STRING_NETRC_FILE], va_arg(param, char *)); break; #endif case CURLOPT_TRANSFERTEXT: /* * This option was previously named 'FTPASCII'. Renamed to work with * more protocols than merely FTP. * * Transfer using ASCII (instead of BINARY). */ data->set.prefer_ascii = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_TIMECONDITION: /* * Set HTTP time condition. This must be one of the defines in the * curl/curl.h header file. */ arg = va_arg(param, long); if((arg < CURL_TIMECOND_NONE) || (arg >= CURL_TIMECOND_LAST)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.timecondition = (curl_TimeCond)arg; break; case CURLOPT_TIMEVALUE: /* * This is the value to compare with the remote document with the * method set with CURLOPT_TIMECONDITION */ data->set.timevalue = (time_t)va_arg(param, long); break; case CURLOPT_TIMEVALUE_LARGE: /* * This is the value to compare with the remote document with the * method set with CURLOPT_TIMECONDITION */ data->set.timevalue = (time_t)va_arg(param, curl_off_t); break; case CURLOPT_SSLVERSION: #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLVERSION: #endif /* * Set explicit SSL version to try to connect with, as some SSL * implementations are lame. */ #ifdef USE_SSL { long version, version_max; struct ssl_primary_config *primary = &data->set.ssl.primary; #ifndef CURL_DISABLE_PROXY if(option != CURLOPT_SSLVERSION) primary = &data->set.proxy_ssl.primary; #endif arg = va_arg(param, long); version = C_SSLVERSION_VALUE(arg); version_max = C_SSLVERSION_MAX_VALUE(arg); if(version < CURL_SSLVERSION_DEFAULT || version == CURL_SSLVERSION_SSLv2 || version == CURL_SSLVERSION_SSLv3 || version >= CURL_SSLVERSION_LAST || version_max < CURL_SSLVERSION_MAX_NONE || version_max >= CURL_SSLVERSION_MAX_LAST) return CURLE_BAD_FUNCTION_ARGUMENT; primary->version = version; primary->version_max = version_max; } #else result = CURLE_NOT_BUILT_IN; #endif break; /* MQTT "borrows" some of the HTTP options */ #if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_MQTT) case CURLOPT_COPYPOSTFIELDS: /* * A string with POST data. Makes curl HTTP POST. Even if it is NULL. * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to * CURLOPT_COPYPOSTFIELDS and not altered later. */ argptr = va_arg(param, char *); if(!argptr || data->set.postfieldsize == -1) result = Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr); else { /* * Check that requested length does not overflow the size_t type. */ if((data->set.postfieldsize < 0) || ((sizeof(curl_off_t) != sizeof(size_t)) && (data->set.postfieldsize > (curl_off_t)((size_t)-1)))) result = CURLE_OUT_OF_MEMORY; else { char *p; (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); /* Allocate even when size == 0. This satisfies the need of possible later address compare to detect the COPYPOSTFIELDS mode, and to mark that postfields is used rather than read function or form data. */ p = malloc((size_t)(data->set.postfieldsize? data->set.postfieldsize:1)); if(!p) result = CURLE_OUT_OF_MEMORY; else { if(data->set.postfieldsize) memcpy(p, argptr, (size_t)data->set.postfieldsize); data->set.str[STRING_COPYPOSTFIELDS] = p; } } } data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS]; data->set.method = HTTPREQ_POST; break; case CURLOPT_POSTFIELDS: /* * Like above, but use static data instead of copying it. */ data->set.postfields = va_arg(param, void *); /* Release old copied data. */ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.method = HTTPREQ_POST; break; case CURLOPT_POSTFIELDSIZE: /* * The size of the POSTFIELD data to prevent libcurl to do strlen() to * figure it out. Enables binary posts. */ bigsize = va_arg(param, long); if(bigsize < -1) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->set.postfieldsize < bigsize && data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) { /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.postfields = NULL; } data->set.postfieldsize = bigsize; break; case CURLOPT_POSTFIELDSIZE_LARGE: /* * The size of the POSTFIELD data to prevent libcurl to do strlen() to * figure it out. Enables binary posts. */ bigsize = va_arg(param, curl_off_t); if(bigsize < -1) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->set.postfieldsize < bigsize && data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) { /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL); data->set.postfields = NULL; } data->set.postfieldsize = bigsize; break; #endif #ifndef CURL_DISABLE_HTTP case CURLOPT_AUTOREFERER: /* * Switch on automatic referer that gets set if curl follows locations. */ data->set.http_auto_referer = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_ACCEPT_ENCODING: /* * String to use at the value of Accept-Encoding header. * * If the encoding is set to "" we use an Accept-Encoding header that * encompasses all the encodings we support. * If the encoding is set to NULL we don't send an Accept-Encoding header * and ignore an received Content-Encoding header. * */ argptr = va_arg(param, char *); if(argptr && !*argptr) { argptr = Curl_all_content_encodings(); if(!argptr) result = CURLE_OUT_OF_MEMORY; else { result = Curl_setstropt(&data->set.str[STRING_ENCODING], argptr); free(argptr); } } else result = Curl_setstropt(&data->set.str[STRING_ENCODING], argptr); break; case CURLOPT_TRANSFER_ENCODING: data->set.http_transfer_encoding = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FOLLOWLOCATION: /* * Follow Location: header hints on a HTTP-server. */ data->set.http_follow_location = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_UNRESTRICTED_AUTH: /* * Send authentication (user+password) when following locations, even when * hostname changed. */ data->set.allow_auth_to_other_hosts = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_MAXREDIRS: /* * The maximum amount of hops you allow curl to follow Location: * headers. This should mostly be used to detect never-ending loops. */ arg = va_arg(param, long); if(arg < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.maxredirs = arg; break; case CURLOPT_POSTREDIR: /* * Set the behavior of POST when redirecting * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302 * CURL_REDIR_POST_301 - POST is kept as POST after 301 * CURL_REDIR_POST_302 - POST is kept as POST after 302 * CURL_REDIR_POST_303 - POST is kept as POST after 303 * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303 * other - POST is kept as POST after 301 and 302 */ arg = va_arg(param, long); if(arg < CURL_REDIR_GET_ALL) /* no return error on too high numbers since the bitmask could be extended in a future */ return CURLE_BAD_FUNCTION_ARGUMENT; data->set.keep_post = arg & CURL_REDIR_POST_ALL; break; case CURLOPT_POST: /* Does this option serve a purpose anymore? Yes it does, when CURLOPT_POSTFIELDS isn't used and the POST data is read off the callback! */ if(va_arg(param, long)) { data->set.method = HTTPREQ_POST; data->set.opt_no_body = FALSE; /* this is implied */ } else data->set.method = HTTPREQ_GET; break; case CURLOPT_HTTPPOST: /* * Set to make us do HTTP POST */ data->set.httppost = va_arg(param, struct curl_httppost *); data->set.method = HTTPREQ_POST_FORM; data->set.opt_no_body = FALSE; /* this is implied */ break; case CURLOPT_AWS_SIGV4: /* * String that is merged to some authentication * parameters are used by the algorithm. */ result = Curl_setstropt(&data->set.str[STRING_AWS_SIGV4], va_arg(param, char *)); /* * Basic been set by default it need to be unset here */ if(data->set.str[STRING_AWS_SIGV4]) data->set.httpauth = CURLAUTH_AWS_SIGV4; break; case CURLOPT_MIMEPOST: /* * Set to make us do MIME/form POST */ result = Curl_mime_set_subparts(&data->set.mimepost, va_arg(param, curl_mime *), FALSE); if(!result) { data->set.method = HTTPREQ_POST_MIME; data->set.opt_no_body = FALSE; /* this is implied */ } break; case CURLOPT_REFERER: /* * String to set in the HTTP Referer: field. */ if(data->state.referer_alloc) { Curl_safefree(data->state.referer); data->state.referer_alloc = FALSE; } result = Curl_setstropt(&data->set.str[STRING_SET_REFERER], va_arg(param, char *)); data->state.referer = data->set.str[STRING_SET_REFERER]; break; case CURLOPT_USERAGENT: /* * String to use in the HTTP User-Agent field */ result = Curl_setstropt(&data->set.str[STRING_USERAGENT], va_arg(param, char *)); break; case CURLOPT_HTTPHEADER: /* * Set a list with HTTP headers to use (or replace internals with) */ data->set.headers = va_arg(param, struct curl_slist *); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXYHEADER: /* * Set a list with proxy headers to use (or replace internals with) * * Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a * long time we remain doing it this way until CURLOPT_PROXYHEADER is * used. As soon as this option has been used, if set to anything but * NULL, custom headers for proxies are only picked from this list. * * Set this option to NULL to restore the previous behavior. */ data->set.proxyheaders = va_arg(param, struct curl_slist *); break; #endif case CURLOPT_HEADEROPT: /* * Set header option. */ arg = va_arg(param, long); data->set.sep_headers = (bool)((arg & CURLHEADER_SEPARATE)? TRUE: FALSE); break; case CURLOPT_HTTP200ALIASES: /* * Set a list of aliases for HTTP 200 in response header */ data->set.http200aliases = va_arg(param, struct curl_slist *); break; #if !defined(CURL_DISABLE_COOKIES) case CURLOPT_COOKIE: /* * Cookie string to send to the remote server in the request. */ result = Curl_setstropt(&data->set.str[STRING_COOKIE], va_arg(param, char *)); break; case CURLOPT_COOKIEFILE: /* * Set cookie file to read and parse. Can be used multiple times. */ argptr = (char *)va_arg(param, void *); if(argptr) { struct curl_slist *cl; /* general protection against mistakes and abuse */ if(strlen(argptr) > CURL_MAX_INPUT_LENGTH) return CURLE_BAD_FUNCTION_ARGUMENT; /* append the cookie file name to the list of file names, and deal with them later */ cl = curl_slist_append(data->state.cookielist, argptr); if(!cl) { curl_slist_free_all(data->state.cookielist); data->state.cookielist = NULL; return CURLE_OUT_OF_MEMORY; } data->state.cookielist = cl; /* store the list for later use */ } else { /* clear the list of cookie files */ curl_slist_free_all(data->state.cookielist); data->state.cookielist = NULL; if(!data->share || !data->share->cookies) { /* throw away all existing cookies if this isn't a shared cookie container */ Curl_cookie_clearall(data->cookies); Curl_cookie_cleanup(data->cookies); } /* disable the cookie engine */ data->cookies = NULL; } break; case CURLOPT_COOKIEJAR: /* * Set cookie file name to dump all cookies to when we're done. */ { struct CookieInfo *newcookies; result = Curl_setstropt(&data->set.str[STRING_COOKIEJAR], va_arg(param, char *)); /* * Activate the cookie parser. This may or may not already * have been made. */ newcookies = Curl_cookie_init(data, NULL, data->cookies, data->set.cookiesession); if(!newcookies) result = CURLE_OUT_OF_MEMORY; data->cookies = newcookies; } break; case CURLOPT_COOKIESESSION: /* * Set this option to TRUE to start a new "cookie session". It will * prevent the forthcoming read-cookies-from-file actions to accept * cookies that are marked as being session cookies, as they belong to a * previous session. * * In the original Netscape cookie spec, "session cookies" are cookies * with no expire date set. RFC2109 describes the same action if no * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds * a 'Discard' action that can enforce the discard even for cookies that * have a Max-Age. * * We run mostly with the original cookie spec, as hardly anyone implements * anything else. */ data->set.cookiesession = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_COOKIELIST: argptr = va_arg(param, char *); if(!argptr) break; if(strcasecompare(argptr, "ALL")) { /* clear all cookies */ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); Curl_cookie_clearall(data->cookies); Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); } else if(strcasecompare(argptr, "SESS")) { /* clear session cookies */ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); Curl_cookie_clearsess(data->cookies); Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); } else if(strcasecompare(argptr, "FLUSH")) { /* flush cookies to file, takes care of the locking */ Curl_flush_cookies(data, FALSE); } else if(strcasecompare(argptr, "RELOAD")) { /* reload cookies from file */ Curl_cookie_loadfiles(data); break; } else { if(!data->cookies) /* if cookie engine was not running, activate it */ data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE); /* general protection against mistakes and abuse */ if(strlen(argptr) > CURL_MAX_INPUT_LENGTH) return CURLE_BAD_FUNCTION_ARGUMENT; argptr = strdup(argptr); if(!argptr || !data->cookies) { result = CURLE_OUT_OF_MEMORY; free(argptr); } else { Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); if(checkprefix("Set-Cookie:", argptr)) /* HTTP Header format line */ Curl_cookie_add(data, data->cookies, TRUE, FALSE, argptr + 11, NULL, NULL, TRUE); else /* Netscape format line */ Curl_cookie_add(data, data->cookies, FALSE, FALSE, argptr, NULL, NULL, TRUE); Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); free(argptr); } } break; #endif /* !CURL_DISABLE_COOKIES */ case CURLOPT_HTTPGET: /* * Set to force us do HTTP GET */ if(va_arg(param, long)) { data->set.method = HTTPREQ_GET; data->set.upload = FALSE; /* switch off upload */ data->set.opt_no_body = FALSE; /* this is implied */ } break; case CURLOPT_HTTP_VERSION: /* * This sets a requested HTTP version to be used. The value is one of * the listed enums in curl/curl.h. */ arg = va_arg(param, long); if(arg < CURL_HTTP_VERSION_NONE) return CURLE_BAD_FUNCTION_ARGUMENT; #ifdef ENABLE_QUIC if(arg == CURL_HTTP_VERSION_3) ; else #endif #if !defined(USE_NGHTTP2) && !defined(USE_HYPER) if(arg >= CURL_HTTP_VERSION_2) return CURLE_UNSUPPORTED_PROTOCOL; #else if(arg >= CURL_HTTP_VERSION_LAST) return CURLE_UNSUPPORTED_PROTOCOL; if(arg == CURL_HTTP_VERSION_NONE) arg = CURL_HTTP_VERSION_2TLS; #endif data->set.httpwant = (unsigned char)arg; break; case CURLOPT_EXPECT_100_TIMEOUT_MS: /* * Time to wait for a response to a HTTP request containing an * Expect: 100-continue header before sending the data anyway. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.expect_100_timeout = arg; break; case CURLOPT_HTTP09_ALLOWED: arg = va_arg(param, unsigned long); if(arg > 1L) return CURLE_BAD_FUNCTION_ARGUMENT; #ifdef USE_HYPER /* Hyper does not support HTTP/0.9 */ if(arg) return CURLE_BAD_FUNCTION_ARGUMENT; #else data->set.http09_allowed = arg ? TRUE : FALSE; #endif break; #endif /* CURL_DISABLE_HTTP */ case CURLOPT_HTTPAUTH: /* * Set HTTP Authentication type BITMASK. */ { int bitcheck; bool authbits; unsigned long auth = va_arg(param, unsigned long); if(auth == CURLAUTH_NONE) { data->set.httpauth = auth; break; } /* the DIGEST_IE bit is only used to set a special marker, for all the rest we need to handle it as normal DIGEST */ data->state.authhost.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE); if(auth & CURLAUTH_DIGEST_IE) { auth |= CURLAUTH_DIGEST; /* set standard digest bit */ auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */ } /* switch off bits we can't support */ #ifndef USE_NTLM auth &= ~CURLAUTH_NTLM; /* no NTLM support */ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #elif !defined(NTLM_WB_ENABLED) auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #endif #ifndef USE_SPNEGO auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without GSS-API or SSPI */ #endif /* check if any auth bit lower than CURLAUTH_ONLY is still set */ bitcheck = 0; authbits = FALSE; while(bitcheck < 31) { if(auth & (1UL << bitcheck++)) { authbits = TRUE; break; } } if(!authbits) return CURLE_NOT_BUILT_IN; /* no supported types left! */ data->set.httpauth = auth; } break; case CURLOPT_CUSTOMREQUEST: /* * Set a custom string to use as request */ result = Curl_setstropt(&data->set.str[STRING_CUSTOMREQUEST], va_arg(param, char *)); /* we don't set data->set.method = HTTPREQ_CUSTOM; here, we continue as if we were using the already set type and this just changes the actual request keyword */ break; #ifndef CURL_DISABLE_PROXY case CURLOPT_HTTPPROXYTUNNEL: /* * Tunnel operations through the proxy instead of normal proxy use */ data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_PROXYPORT: /* * Explicitly set HTTP proxy port number. */ arg = va_arg(param, long); if((arg < 0) || (arg > 65535)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.proxyport = arg; break; case CURLOPT_PROXYAUTH: /* * Set HTTP Authentication type BITMASK. */ { int bitcheck; bool authbits; unsigned long auth = va_arg(param, unsigned long); if(auth == CURLAUTH_NONE) { data->set.proxyauth = auth; break; } /* the DIGEST_IE bit is only used to set a special marker, for all the rest we need to handle it as normal DIGEST */ data->state.authproxy.iestyle = (bool)((auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE); if(auth & CURLAUTH_DIGEST_IE) { auth |= CURLAUTH_DIGEST; /* set standard digest bit */ auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */ } /* switch off bits we can't support */ #ifndef USE_NTLM auth &= ~CURLAUTH_NTLM; /* no NTLM support */ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #elif !defined(NTLM_WB_ENABLED) auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */ #endif #ifndef USE_SPNEGO auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without GSS-API or SSPI */ #endif /* check if any auth bit lower than CURLAUTH_ONLY is still set */ bitcheck = 0; authbits = FALSE; while(bitcheck < 31) { if(auth & (1UL << bitcheck++)) { authbits = TRUE; break; } } if(!authbits) return CURLE_NOT_BUILT_IN; /* no supported types left! */ data->set.proxyauth = auth; } break; case CURLOPT_PROXY: /* * Set proxy server:port to use as proxy. * * If the proxy is set to "" (and CURLOPT_SOCKS_PROXY is set to "" or NULL) * we explicitly say that we don't want to use a proxy * (even though there might be environment variables saying so). * * Setting it to NULL, means no proxy but allows the environment variables * to decide for us (if CURLOPT_SOCKS_PROXY setting it to NULL). */ result = Curl_setstropt(&data->set.str[STRING_PROXY], va_arg(param, char *)); break; case CURLOPT_PRE_PROXY: /* * Set proxy server:port to use as SOCKS proxy. * * If the proxy is set to "" or NULL we explicitly say that we don't want * to use the socks proxy. */ result = Curl_setstropt(&data->set.str[STRING_PRE_PROXY], va_arg(param, char *)); break; case CURLOPT_PROXYTYPE: /* * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME */ arg = va_arg(param, long); if((arg < CURLPROXY_HTTP) || (arg > CURLPROXY_SOCKS5_HOSTNAME)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.proxytype = (curl_proxytype)arg; break; case CURLOPT_PROXY_TRANSFER_MODE: /* * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */ switch(va_arg(param, long)) { case 0: data->set.proxy_transfer_mode = FALSE; break; case 1: data->set.proxy_transfer_mode = TRUE; break; default: /* reserve other values for future use */ result = CURLE_BAD_FUNCTION_ARGUMENT; break; } break; #endif /* CURL_DISABLE_PROXY */ case CURLOPT_SOCKS5_AUTH: data->set.socks5auth = va_arg(param, unsigned long); if(data->set.socks5auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI)) result = CURLE_NOT_BUILT_IN; break; #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) case CURLOPT_SOCKS5_GSSAPI_NEC: /* * Set flag for NEC SOCK5 support */ data->set.socks5_gssapi_nec = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #endif #ifndef CURL_DISABLE_PROXY case CURLOPT_SOCKS5_GSSAPI_SERVICE: case CURLOPT_PROXY_SERVICE_NAME: /* * Set proxy authentication service name for Kerberos 5 and SPNEGO */ result = Curl_setstropt(&data->set.str[STRING_PROXY_SERVICE_NAME], va_arg(param, char *)); break; #endif case CURLOPT_SERVICE_NAME: /* * Set authentication service name for DIGEST-MD5, Kerberos 5 and SPNEGO */ result = Curl_setstropt(&data->set.str[STRING_SERVICE_NAME], va_arg(param, char *)); break; case CURLOPT_HEADERDATA: /* * Custom pointer to pass the header write callback function */ data->set.writeheader = (void *)va_arg(param, void *); break; case CURLOPT_ERRORBUFFER: /* * Error buffer provided by the caller to get the human readable * error string in. */ data->set.errorbuffer = va_arg(param, char *); break; case CURLOPT_WRITEDATA: /* * FILE pointer to write to. Or possibly * used as argument to the write callback. */ data->set.out = va_arg(param, void *); break; case CURLOPT_DIRLISTONLY: /* * An option that changes the command to one that asks for a list only, no * file info details. Used for FTP, POP3 and SFTP. */ data->set.list_only = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_APPEND: /* * We want to upload and append to an existing file. Used for FTP and * SFTP. */ data->set.remote_append = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_FTP case CURLOPT_FTP_FILEMETHOD: /* * How do access files over FTP. */ arg = va_arg(param, long); if((arg < CURLFTPMETHOD_DEFAULT) || (arg >= CURLFTPMETHOD_LAST)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.ftp_filemethod = (curl_ftpfile)arg; break; case CURLOPT_FTPPORT: /* * Use FTP PORT, this also specifies which IP address to use */ result = Curl_setstropt(&data->set.str[STRING_FTPPORT], va_arg(param, char *)); data->set.ftp_use_port = (data->set.str[STRING_FTPPORT]) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_EPRT: data->set.ftp_use_eprt = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_EPSV: data->set.ftp_use_epsv = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_USE_PRET: data->set.ftp_use_pret = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_SSL_CCC: arg = va_arg(param, long); if((arg < CURLFTPSSL_CCC_NONE) || (arg >= CURLFTPSSL_CCC_LAST)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.ftp_ccc = (curl_ftpccc)arg; break; case CURLOPT_FTP_SKIP_PASV_IP: /* * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the * bypass of the IP address in PASV responses. */ data->set.ftp_skip_ip = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_FTP_ACCOUNT: result = Curl_setstropt(&data->set.str[STRING_FTP_ACCOUNT], va_arg(param, char *)); break; case CURLOPT_FTP_ALTERNATIVE_TO_USER: result = Curl_setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER], va_arg(param, char *)); break; case CURLOPT_FTPSSLAUTH: /* * Set a specific auth for FTP-SSL transfers. */ arg = va_arg(param, long); if((arg < CURLFTPAUTH_DEFAULT) || (arg >= CURLFTPAUTH_LAST)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.ftpsslauth = (curl_ftpauth)arg; break; case CURLOPT_KRBLEVEL: /* * A string that defines the kerberos security level. */ result = Curl_setstropt(&data->set.str[STRING_KRB_LEVEL], va_arg(param, char *)); data->set.krb = (data->set.str[STRING_KRB_LEVEL]) ? TRUE : FALSE; break; #endif case CURLOPT_FTP_CREATE_MISSING_DIRS: /* * An FTP/SFTP option that modifies an upload to create missing * directories on the server. */ arg = va_arg(param, long); /* reserve other values for future use */ if((arg < CURLFTP_CREATE_DIR_NONE) || (arg > CURLFTP_CREATE_DIR_RETRY)) result = CURLE_BAD_FUNCTION_ARGUMENT; else data->set.ftp_create_missing_dirs = (int)arg; break; case CURLOPT_READDATA: /* * FILE pointer to read the file to be uploaded from. Or possibly * used as argument to the read callback. */ data->set.in_set = va_arg(param, void *); break; case CURLOPT_INFILESIZE: /* * If known, this should inform curl about the file size of the * to-be-uploaded file. */ arg = va_arg(param, long); if(arg < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.filesize = arg; break; case CURLOPT_INFILESIZE_LARGE: /* * If known, this should inform curl about the file size of the * to-be-uploaded file. */ bigsize = va_arg(param, curl_off_t); if(bigsize < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.filesize = bigsize; break; case CURLOPT_LOW_SPEED_LIMIT: /* * The low speed limit that if transfers are below this for * CURLOPT_LOW_SPEED_TIME, the transfer is aborted. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.low_speed_limit = arg; break; case CURLOPT_MAX_SEND_SPEED_LARGE: /* * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE * bytes per second the transfer is throttled.. */ bigsize = va_arg(param, curl_off_t); if(bigsize < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.max_send_speed = bigsize; break; case CURLOPT_MAX_RECV_SPEED_LARGE: /* * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per * second the transfer is throttled.. */ bigsize = va_arg(param, curl_off_t); if(bigsize < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.max_recv_speed = bigsize; break; case CURLOPT_LOW_SPEED_TIME: /* * The low speed time that if transfers are below the set * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.low_speed_time = arg; break; case CURLOPT_CURLU: /* * pass CURLU to set URL */ data->set.uh = va_arg(param, CURLU *); break; case CURLOPT_URL: /* * The URL to fetch. */ if(data->state.url_alloc) { /* the already set URL is allocated, free it first! */ Curl_safefree(data->state.url); data->state.url_alloc = FALSE; } result = Curl_setstropt(&data->set.str[STRING_SET_URL], va_arg(param, char *)); data->state.url = data->set.str[STRING_SET_URL]; break; case CURLOPT_PORT: /* * The port number to use when getting the URL */ arg = va_arg(param, long); if((arg < 0) || (arg > 65535)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.use_port = arg; break; case CURLOPT_TIMEOUT: /* * The maximum time you allow curl to use for a single transfer * operation. */ arg = va_arg(param, long); if((arg >= 0) && (arg <= (INT_MAX/1000))) data->set.timeout = arg * 1000; else return CURLE_BAD_FUNCTION_ARGUMENT; break; case CURLOPT_TIMEOUT_MS: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.timeout = arg; break; case CURLOPT_CONNECTTIMEOUT: /* * The maximum time you allow curl to use to connect. */ arg = va_arg(param, long); if((arg >= 0) && (arg <= (INT_MAX/1000))) data->set.connecttimeout = arg * 1000; else return CURLE_BAD_FUNCTION_ARGUMENT; break; case CURLOPT_CONNECTTIMEOUT_MS: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.connecttimeout = arg; break; case CURLOPT_ACCEPTTIMEOUT_MS: /* * The maximum time you allow curl to wait for server connect */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.accepttimeout = arg; break; case CURLOPT_USERPWD: /* * user:password to use in the operation */ result = setstropt_userpwd(va_arg(param, char *), &data->set.str[STRING_USERNAME], &data->set.str[STRING_PASSWORD]); break; case CURLOPT_USERNAME: /* * authentication user name to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_USERNAME], va_arg(param, char *)); break; case CURLOPT_PASSWORD: /* * authentication password to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_PASSWORD], va_arg(param, char *)); break; case CURLOPT_LOGIN_OPTIONS: /* * authentication options to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_OPTIONS], va_arg(param, char *)); break; case CURLOPT_XOAUTH2_BEARER: /* * OAuth 2.0 bearer token to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_BEARER], va_arg(param, char *)); break; case CURLOPT_POSTQUOTE: /* * List of RAW FTP commands to use after a transfer */ data->set.postquote = va_arg(param, struct curl_slist *); break; case CURLOPT_PREQUOTE: /* * List of RAW FTP commands to use prior to RETR (Wesley Laxton) */ data->set.prequote = va_arg(param, struct curl_slist *); break; case CURLOPT_QUOTE: /* * List of RAW FTP commands to use before a transfer */ data->set.quote = va_arg(param, struct curl_slist *); break; case CURLOPT_RESOLVE: /* * List of HOST:PORT:[addresses] strings to populate the DNS cache with * Entries added this way will remain in the cache until explicitly * removed or the handle is cleaned up. * * Prefix the HOST with plus sign (+) to have the entry expire just like * automatically added entries. * * Prefix the HOST with dash (-) to _remove_ the entry from the cache. * * This API can remove any entry from the DNS cache, but only entries * that aren't actually in use right now will be pruned immediately. */ data->set.resolve = va_arg(param, struct curl_slist *); data->state.resolve = data->set.resolve; break; case CURLOPT_PROGRESSFUNCTION: /* * Progress callback function */ data->set.fprogress = va_arg(param, curl_progress_callback); if(data->set.fprogress) data->progress.callback = TRUE; /* no longer internal */ else data->progress.callback = FALSE; /* NULL enforces internal */ break; case CURLOPT_XFERINFOFUNCTION: /* * Transfer info callback function */ data->set.fxferinfo = va_arg(param, curl_xferinfo_callback); if(data->set.fxferinfo) data->progress.callback = TRUE; /* no longer internal */ else data->progress.callback = FALSE; /* NULL enforces internal */ break; case CURLOPT_PROGRESSDATA: /* * Custom client data to pass to the progress callback */ data->set.progress_client = va_arg(param, void *); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXYUSERPWD: /* * user:password needed to use the proxy */ result = setstropt_userpwd(va_arg(param, char *), &data->set.str[STRING_PROXYUSERNAME], &data->set.str[STRING_PROXYPASSWORD]); break; case CURLOPT_PROXYUSERNAME: /* * authentication user name to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_PROXYUSERNAME], va_arg(param, char *)); break; case CURLOPT_PROXYPASSWORD: /* * authentication password to use in the operation */ result = Curl_setstropt(&data->set.str[STRING_PROXYPASSWORD], va_arg(param, char *)); break; case CURLOPT_NOPROXY: /* * proxy exception list */ result = Curl_setstropt(&data->set.str[STRING_NOPROXY], va_arg(param, char *)); break; #endif case CURLOPT_RANGE: /* * What range of the file you want to transfer */ result = Curl_setstropt(&data->set.str[STRING_SET_RANGE], va_arg(param, char *)); break; case CURLOPT_RESUME_FROM: /* * Resume transfer at the given file position */ arg = va_arg(param, long); if(arg < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.set_resume_from = arg; break; case CURLOPT_RESUME_FROM_LARGE: /* * Resume transfer at the given file position */ bigsize = va_arg(param, curl_off_t); if(bigsize < -1) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.set_resume_from = bigsize; break; case CURLOPT_DEBUGFUNCTION: /* * stderr write callback. */ data->set.fdebug = va_arg(param, curl_debug_callback); /* * if the callback provided is NULL, it'll use the default callback */ break; case CURLOPT_DEBUGDATA: /* * Set to a void * that should receive all error writes. This * defaults to CURLOPT_STDERR for normal operations. */ data->set.debugdata = va_arg(param, void *); break; case CURLOPT_STDERR: /* * Set to a FILE * that should receive all error writes. This * defaults to stderr for normal operations. */ data->set.err = va_arg(param, FILE *); if(!data->set.err) data->set.err = stderr; break; case CURLOPT_HEADERFUNCTION: /* * Set header write callback */ data->set.fwrite_header = va_arg(param, curl_write_callback); break; case CURLOPT_WRITEFUNCTION: /* * Set data write callback */ data->set.fwrite_func = va_arg(param, curl_write_callback); if(!data->set.fwrite_func) { data->set.is_fwrite_set = 0; /* When set to NULL, reset to our internal default function */ data->set.fwrite_func = (curl_write_callback)fwrite; } else data->set.is_fwrite_set = 1; break; case CURLOPT_READFUNCTION: /* * Read data callback */ data->set.fread_func_set = va_arg(param, curl_read_callback); if(!data->set.fread_func_set) { data->set.is_fread_set = 0; /* When set to NULL, reset to our internal default function */ data->set.fread_func_set = (curl_read_callback)fread; } else data->set.is_fread_set = 1; break; case CURLOPT_SEEKFUNCTION: /* * Seek callback. Might be NULL. */ data->set.seek_func = va_arg(param, curl_seek_callback); break; case CURLOPT_SEEKDATA: /* * Seek control callback. Might be NULL. */ data->set.seek_client = va_arg(param, void *); break; case CURLOPT_CONV_FROM_NETWORK_FUNCTION: /* * "Convert from network encoding" callback */ data->set.convfromnetwork = va_arg(param, curl_conv_callback); break; case CURLOPT_CONV_TO_NETWORK_FUNCTION: /* * "Convert to network encoding" callback */ data->set.convtonetwork = va_arg(param, curl_conv_callback); break; case CURLOPT_CONV_FROM_UTF8_FUNCTION: /* * "Convert from UTF-8 encoding" callback */ data->set.convfromutf8 = va_arg(param, curl_conv_callback); break; case CURLOPT_IOCTLFUNCTION: /* * I/O control callback. Might be NULL. */ data->set.ioctl_func = va_arg(param, curl_ioctl_callback); break; case CURLOPT_IOCTLDATA: /* * I/O control data pointer. Might be NULL. */ data->set.ioctl_client = va_arg(param, void *); break; case CURLOPT_SSLCERT: /* * String that holds file name of the SSL certificate to use */ result = Curl_setstropt(&data->set.str[STRING_CERT], va_arg(param, char *)); break; case CURLOPT_SSLCERT_BLOB: /* * Blob that holds file content of the SSL certificate to use */ result = Curl_setblobopt(&data->set.blobs[BLOB_CERT], va_arg(param, struct curl_blob *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLCERT: /* * String that holds file name of the SSL certificate to use for proxy */ result = Curl_setstropt(&data->set.str[STRING_CERT_PROXY], va_arg(param, char *)); break; case CURLOPT_PROXY_SSLCERT_BLOB: /* * Blob that holds file content of the SSL certificate to use for proxy */ result = Curl_setblobopt(&data->set.blobs[BLOB_CERT_PROXY], va_arg(param, struct curl_blob *)); break; #endif case CURLOPT_SSLCERTTYPE: /* * String that holds file type of the SSL certificate to use */ result = Curl_setstropt(&data->set.str[STRING_CERT_TYPE], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLCERTTYPE: /* * String that holds file type of the SSL certificate to use for proxy */ result = Curl_setstropt(&data->set.str[STRING_CERT_TYPE_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_SSLKEY: /* * String that holds file name of the SSL key to use */ result = Curl_setstropt(&data->set.str[STRING_KEY], va_arg(param, char *)); break; case CURLOPT_SSLKEY_BLOB: /* * Blob that holds file content of the SSL key to use */ result = Curl_setblobopt(&data->set.blobs[BLOB_KEY], va_arg(param, struct curl_blob *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLKEY: /* * String that holds file name of the SSL key to use for proxy */ result = Curl_setstropt(&data->set.str[STRING_KEY_PROXY], va_arg(param, char *)); break; case CURLOPT_PROXY_SSLKEY_BLOB: /* * Blob that holds file content of the SSL key to use for proxy */ result = Curl_setblobopt(&data->set.blobs[BLOB_KEY_PROXY], va_arg(param, struct curl_blob *)); break; #endif case CURLOPT_SSLKEYTYPE: /* * String that holds file type of the SSL key to use */ result = Curl_setstropt(&data->set.str[STRING_KEY_TYPE], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSLKEYTYPE: /* * String that holds file type of the SSL key to use for proxy */ result = Curl_setstropt(&data->set.str[STRING_KEY_TYPE_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_KEYPASSWD: /* * String that holds the SSL or SSH private key password. */ result = Curl_setstropt(&data->set.str[STRING_KEY_PASSWD], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_KEYPASSWD: /* * String that holds the SSL private key password for proxy. */ result = Curl_setstropt(&data->set.str[STRING_KEY_PASSWD_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_SSLENGINE: /* * String that holds the SSL crypto engine. */ argptr = va_arg(param, char *); if(argptr && argptr[0]) { result = Curl_setstropt(&data->set.str[STRING_SSL_ENGINE], argptr); if(!result) { result = Curl_ssl_set_engine(data, argptr); } } break; case CURLOPT_SSLENGINE_DEFAULT: /* * flag to set engine as default. */ Curl_setstropt(&data->set.str[STRING_SSL_ENGINE], NULL); result = Curl_ssl_set_engine_default(data); break; case CURLOPT_CRLF: /* * Kludgy option to enable CRLF conversions. Subject for removal. */ data->set.crlf = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_HAPROXYPROTOCOL: /* * Set to send the HAProxy Proxy Protocol header */ data->set.haproxyprotocol = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #endif case CURLOPT_INTERFACE: /* * Set what interface or address/hostname to bind the socket to when * performing an operation and thus what from-IP your connection will use. */ result = Curl_setstropt(&data->set.str[STRING_DEVICE], va_arg(param, char *)); break; case CURLOPT_LOCALPORT: /* * Set what local port to bind the socket to when performing an operation. */ arg = va_arg(param, long); if((arg < 0) || (arg > 65535)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.localport = curlx_sltous(arg); break; case CURLOPT_LOCALPORTRANGE: /* * Set number of local ports to try, starting with CURLOPT_LOCALPORT. */ arg = va_arg(param, long); if((arg < 0) || (arg > 65535)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.localportrange = curlx_sltosi(arg); break; case CURLOPT_GSSAPI_DELEGATION: /* * GSS-API credential delegation bitmask */ arg = va_arg(param, long); if(arg < CURLGSSAPI_DELEGATION_NONE) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.gssapi_delegation = arg; break; case CURLOPT_SSL_VERIFYPEER: /* * Enable peer SSL verifying. */ data->set.ssl.primary.verifypeer = (0 != va_arg(param, long)) ? TRUE : FALSE; /* Update the current connection ssl_config. */ if(data->conn) { data->conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer; } break; case CURLOPT_DOH_SSL_VERIFYPEER: /* * Enable peer SSL verifying for DoH. */ data->set.doh_verifypeer = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSL_VERIFYPEER: /* * Enable peer SSL verifying for proxy. */ data->set.proxy_ssl.primary.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE; /* Update the current connection proxy_ssl_config. */ if(data->conn) { data->conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer; } break; #endif case CURLOPT_SSL_VERIFYHOST: /* * Enable verification of the host name in the peer certificate */ arg = va_arg(param, long); /* Obviously people are not reading documentation and too many thought this argument took a boolean when it wasn't and misused it. Treat 1 and 2 the same */ data->set.ssl.primary.verifyhost = (bool)((arg & 3) ? TRUE : FALSE); /* Update the current connection ssl_config. */ if(data->conn) { data->conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost; } break; case CURLOPT_DOH_SSL_VERIFYHOST: /* * Enable verification of the host name in the peer certificate for DoH */ arg = va_arg(param, long); /* Treat both 1 and 2 as TRUE */ data->set.doh_verifyhost = (bool)((arg & 3) ? TRUE : FALSE); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSL_VERIFYHOST: /* * Enable verification of the host name in the peer certificate for proxy */ arg = va_arg(param, long); /* Treat both 1 and 2 as TRUE */ data->set.proxy_ssl.primary.verifyhost = (bool)((arg & 3)?TRUE:FALSE); /* Update the current connection proxy_ssl_config. */ if(data->conn) { data->conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost; } break; #endif case CURLOPT_SSL_VERIFYSTATUS: /* * Enable certificate status verifying. */ if(!Curl_ssl_cert_status_request()) { result = CURLE_NOT_BUILT_IN; break; } data->set.ssl.primary.verifystatus = (0 != va_arg(param, long)) ? TRUE : FALSE; /* Update the current connection ssl_config. */ if(data->conn) { data->conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus; } break; case CURLOPT_DOH_SSL_VERIFYSTATUS: /* * Enable certificate status verifying for DoH. */ if(!Curl_ssl_cert_status_request()) { result = CURLE_NOT_BUILT_IN; break; } data->set.doh_verifystatus = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SSL_CTX_FUNCTION: /* * Set a SSL_CTX callback */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_SSL_CTX) data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback); else #endif result = CURLE_NOT_BUILT_IN; break; case CURLOPT_SSL_CTX_DATA: /* * Set a SSL_CTX callback parameter pointer */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_SSL_CTX) data->set.ssl.fsslctxp = va_arg(param, void *); else #endif result = CURLE_NOT_BUILT_IN; break; case CURLOPT_SSL_FALSESTART: /* * Enable TLS false start. */ if(!Curl_ssl_false_start()) { result = CURLE_NOT_BUILT_IN; break; } data->set.ssl.falsestart = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CERTINFO: #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_CERTINFO) data->set.ssl.certinfo = (0 != va_arg(param, long)) ? TRUE : FALSE; else #endif result = CURLE_NOT_BUILT_IN; break; case CURLOPT_PINNEDPUBLICKEY: /* * Set pinned public key for SSL connection. * Specify file name of the public key in DER format. */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_PINNEDPUBKEY) result = Curl_setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY], va_arg(param, char *)); else #endif result = CURLE_NOT_BUILT_IN; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_PINNEDPUBLICKEY: /* * Set pinned public key for SSL connection. * Specify file name of the public key in DER format. */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_PINNEDPUBKEY) result = Curl_setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY], va_arg(param, char *)); else #endif result = CURLE_NOT_BUILT_IN; break; #endif case CURLOPT_CAINFO: /* * Set CA info for SSL connection. Specify file name of the CA certificate */ result = Curl_setstropt(&data->set.str[STRING_SSL_CAFILE], va_arg(param, char *)); break; case CURLOPT_CAINFO_BLOB: /* * Blob that holds CA info for SSL connection. * Specify entire PEM of the CA certificate */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_CAINFO_BLOB) result = Curl_setblobopt(&data->set.blobs[BLOB_CAINFO], va_arg(param, struct curl_blob *)); else #endif return CURLE_NOT_BUILT_IN; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_CAINFO: /* * Set CA info SSL connection for proxy. Specify file name of the * CA certificate */ result = Curl_setstropt(&data->set.str[STRING_SSL_CAFILE_PROXY], va_arg(param, char *)); break; case CURLOPT_PROXY_CAINFO_BLOB: /* * Blob that holds CA info for SSL connection proxy. * Specify entire PEM of the CA certificate */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_CAINFO_BLOB) result = Curl_setblobopt(&data->set.blobs[BLOB_CAINFO_PROXY], va_arg(param, struct curl_blob *)); else #endif return CURLE_NOT_BUILT_IN; break; #endif case CURLOPT_CAPATH: /* * Set CA path info for SSL connection. Specify directory name of the CA * certificates which have been prepared using openssl c_rehash utility. */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_CA_PATH) /* This does not work on windows. */ result = Curl_setstropt(&data->set.str[STRING_SSL_CAPATH], va_arg(param, char *)); else #endif result = CURLE_NOT_BUILT_IN; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_CAPATH: /* * Set CA path info for SSL connection proxy. Specify directory name of the * CA certificates which have been prepared using openssl c_rehash utility. */ #ifdef USE_SSL if(Curl_ssl->supports & SSLSUPP_CA_PATH) /* This does not work on windows. */ result = Curl_setstropt(&data->set.str[STRING_SSL_CAPATH_PROXY], va_arg(param, char *)); else #endif result = CURLE_NOT_BUILT_IN; break; #endif case CURLOPT_CRLFILE: /* * Set CRL file info for SSL connection. Specify file name of the CRL * to check certificates revocation */ result = Curl_setstropt(&data->set.str[STRING_SSL_CRLFILE], va_arg(param, char *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_CRLFILE: /* * Set CRL file info for SSL connection for proxy. Specify file name of the * CRL to check certificates revocation */ result = Curl_setstropt(&data->set.str[STRING_SSL_CRLFILE_PROXY], va_arg(param, char *)); break; #endif case CURLOPT_ISSUERCERT: /* * Set Issuer certificate file * to check certificates issuer */ result = Curl_setstropt(&data->set.str[STRING_SSL_ISSUERCERT], va_arg(param, char *)); break; case CURLOPT_ISSUERCERT_BLOB: /* * Blob that holds Issuer certificate to check certificates issuer */ result = Curl_setblobopt(&data->set.blobs[BLOB_SSL_ISSUERCERT], va_arg(param, struct curl_blob *)); break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_ISSUERCERT: /* * Set Issuer certificate file * to check certificates issuer */ result = Curl_setstropt(&data->set.str[STRING_SSL_ISSUERCERT_PROXY], va_arg(param, char *)); break; case CURLOPT_PROXY_ISSUERCERT_BLOB: /* * Blob that holds Issuer certificate to check certificates issuer */ result = Curl_setblobopt(&data->set.blobs[BLOB_SSL_ISSUERCERT_PROXY], va_arg(param, struct curl_blob *)); break; #endif #ifndef CURL_DISABLE_TELNET case CURLOPT_TELNETOPTIONS: /* * Set a linked list of telnet options */ data->set.telnet_options = va_arg(param, struct curl_slist *); break; #endif case CURLOPT_BUFFERSIZE: /* * The application kindly asks for a differently sized receive buffer. * If it seems reasonable, we'll use it. */ if(data->state.buffer) return CURLE_BAD_FUNCTION_ARGUMENT; arg = va_arg(param, long); if(arg > READBUFFER_MAX) arg = READBUFFER_MAX; else if(arg < 1) arg = READBUFFER_SIZE; else if(arg < READBUFFER_MIN) arg = READBUFFER_MIN; data->set.buffer_size = arg; break; case CURLOPT_UPLOAD_BUFFERSIZE: /* * The application kindly asks for a differently sized upload buffer. * Cap it to sensible. */ arg = va_arg(param, long); if(arg > UPLOADBUFFER_MAX) arg = UPLOADBUFFER_MAX; else if(arg < UPLOADBUFFER_MIN) arg = UPLOADBUFFER_MIN; data->set.upload_buffer_size = (unsigned int)arg; Curl_safefree(data->state.ulbuf); /* force a realloc next opportunity */ break; case CURLOPT_NOSIGNAL: /* * The application asks not to set any signal() or alarm() handlers, * even when using a timeout. */ data->set.no_signal = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SHARE: { struct Curl_share *set; set = va_arg(param, struct Curl_share *); /* disconnect from old share, if any */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); if(data->dns.hostcachetype == HCACHE_SHARED) { data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) if(data->share->cookies == data->cookies) data->cookies = NULL; #endif if(data->share->sslsession == data->state.session) data->state.session = NULL; #ifdef USE_LIBPSL if(data->psl == &data->share->psl) data->psl = data->multi? &data->multi->psl: NULL; #endif data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); data->share = NULL; } if(GOOD_SHARE_HANDLE(set)) /* use new share if it set */ data->share = set; if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty++; if(data->share->specifier & (1<< CURL_LOCK_DATA_DNS)) { /* use shared host cache */ data->dns.hostcache = &data->share->hostcache; data->dns.hostcachetype = HCACHE_SHARED; } #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) if(data->share->cookies) { /* use shared cookie list, first free own one if any */ Curl_cookie_cleanup(data->cookies); /* enable cookies since we now use a share that uses cookies! */ data->cookies = data->share->cookies; } #endif /* CURL_DISABLE_HTTP */ if(data->share->sslsession) { data->set.general_ssl.max_ssl_sessions = data->share->max_ssl_sessions; data->state.session = data->share->sslsession; } #ifdef USE_LIBPSL if(data->share->specifier & (1 << CURL_LOCK_DATA_PSL)) data->psl = &data->share->psl; #endif Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } /* check for host cache not needed, * it will be done by curl_easy_perform */ } break; case CURLOPT_PRIVATE: /* * Set private data pointer. */ data->set.private_data = va_arg(param, void *); break; case CURLOPT_MAXFILESIZE: /* * Set the maximum size of a file to download. */ arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.max_filesize = arg; break; #ifdef USE_SSL case CURLOPT_USE_SSL: /* * Make transfers attempt to use SSL/TLS. */ arg = va_arg(param, long); if((arg < CURLUSESSL_NONE) || (arg >= CURLUSESSL_LAST)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.use_ssl = (curl_usessl)arg; break; case CURLOPT_SSL_OPTIONS: arg = va_arg(param, long); data->set.ssl.enable_beast = !!(arg & CURLSSLOPT_ALLOW_BEAST); data->set.ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE); data->set.ssl.no_partialchain = !!(arg & CURLSSLOPT_NO_PARTIALCHAIN); data->set.ssl.revoke_best_effort = !!(arg & CURLSSLOPT_REVOKE_BEST_EFFORT); data->set.ssl.native_ca_store = !!(arg & CURLSSLOPT_NATIVE_CA); data->set.ssl.auto_client_cert = !!(arg & CURLSSLOPT_AUTO_CLIENT_CERT); /* If a setting is added here it should also be added in dohprobe() which sets its own CURLOPT_SSL_OPTIONS based on these settings. */ break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_SSL_OPTIONS: arg = va_arg(param, long); data->set.proxy_ssl.enable_beast = !!(arg & CURLSSLOPT_ALLOW_BEAST); data->set.proxy_ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE); data->set.proxy_ssl.no_partialchain = !!(arg & CURLSSLOPT_NO_PARTIALCHAIN); data->set.proxy_ssl.revoke_best_effort = !!(arg & CURLSSLOPT_REVOKE_BEST_EFFORT); data->set.proxy_ssl.native_ca_store = !!(arg & CURLSSLOPT_NATIVE_CA); data->set.proxy_ssl.auto_client_cert = !!(arg & CURLSSLOPT_AUTO_CLIENT_CERT); break; #endif case CURLOPT_SSL_EC_CURVES: /* * Set accepted curves in SSL connection setup. * Specify colon-delimited list of curve algorithm names. */ result = Curl_setstropt(&data->set.str[STRING_SSL_EC_CURVES], va_arg(param, char *)); break; #endif case CURLOPT_IPRESOLVE: arg = va_arg(param, long); if((arg < CURL_IPRESOLVE_WHATEVER) || (arg > CURL_IPRESOLVE_V6)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.ipver = (unsigned char) arg; break; case CURLOPT_MAXFILESIZE_LARGE: /* * Set the maximum size of a file to download. */ bigsize = va_arg(param, curl_off_t); if(bigsize < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.max_filesize = bigsize; break; case CURLOPT_TCP_NODELAY: /* * Enable or disable TCP_NODELAY, which will disable/enable the Nagle * algorithm */ data->set.tcp_nodelay = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_IGNORE_CONTENT_LENGTH: data->set.ignorecl = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CONNECT_ONLY: /* * No data transfer, set up connection and let application use the socket */ data->set.connect_only = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SOCKOPTFUNCTION: /* * socket callback function: called after socket() but before connect() */ data->set.fsockopt = va_arg(param, curl_sockopt_callback); break; case CURLOPT_SOCKOPTDATA: /* * socket callback data pointer. Might be NULL. */ data->set.sockopt_client = va_arg(param, void *); break; case CURLOPT_OPENSOCKETFUNCTION: /* * open/create socket callback function: called instead of socket(), * before connect() */ data->set.fopensocket = va_arg(param, curl_opensocket_callback); break; case CURLOPT_OPENSOCKETDATA: /* * socket callback data pointer. Might be NULL. */ data->set.opensocket_client = va_arg(param, void *); break; case CURLOPT_CLOSESOCKETFUNCTION: /* * close socket callback function: called instead of close() * when shutting down a connection */ data->set.fclosesocket = va_arg(param, curl_closesocket_callback); break; case CURLOPT_RESOLVER_START_FUNCTION: /* * resolver start callback function: called before a new resolver request * is started */ data->set.resolver_start = va_arg(param, curl_resolver_start_callback); break; case CURLOPT_RESOLVER_START_DATA: /* * resolver start callback data pointer. Might be NULL. */ data->set.resolver_start_client = va_arg(param, void *); break; case CURLOPT_CLOSESOCKETDATA: /* * socket callback data pointer. Might be NULL. */ data->set.closesocket_client = va_arg(param, void *); break; case CURLOPT_SSL_SESSIONID_CACHE: data->set.ssl.primary.sessionid = (0 != va_arg(param, long)) ? TRUE : FALSE; #ifndef CURL_DISABLE_PROXY data->set.proxy_ssl.primary.sessionid = data->set.ssl.primary.sessionid; #endif break; #ifdef USE_SSH /* we only include SSH options if explicitly built to support SSH */ case CURLOPT_SSH_AUTH_TYPES: data->set.ssh_auth_types = va_arg(param, long); break; case CURLOPT_SSH_PUBLIC_KEYFILE: /* * Use this file instead of the $HOME/.ssh/id_dsa.pub file */ result = Curl_setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY], va_arg(param, char *)); break; case CURLOPT_SSH_PRIVATE_KEYFILE: /* * Use this file instead of the $HOME/.ssh/id_dsa file */ result = Curl_setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY], va_arg(param, char *)); break; case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5: /* * Option to allow for the MD5 of the host public key to be checked * for validation purposes. */ result = Curl_setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5], va_arg(param, char *)); break; case CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256: /* * Option to allow for the SHA256 of the host public key to be checked * for validation purposes. */ result = Curl_setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_SHA256], va_arg(param, char *)); break; case CURLOPT_SSH_KNOWNHOSTS: /* * Store the file name to read known hosts from. */ result = Curl_setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS], va_arg(param, char *)); break; case CURLOPT_SSH_KEYFUNCTION: /* setting to NULL is fine since the ssh.c functions themselves will then revert to use the internal default */ data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback); break; case CURLOPT_SSH_KEYDATA: /* * Custom client data to pass to the SSH keyfunc callback */ data->set.ssh_keyfunc_userp = va_arg(param, void *); break; case CURLOPT_SSH_COMPRESSION: data->set.ssh_compression = (0 != va_arg(param, long))?TRUE:FALSE; break; #endif /* USE_SSH */ case CURLOPT_HTTP_TRANSFER_DECODING: /* * disable libcurl transfer encoding is used */ #ifndef USE_HYPER data->set.http_te_skip = (0 == va_arg(param, long)) ? TRUE : FALSE; break; #else return CURLE_NOT_BUILT_IN; /* hyper doesn't support */ #endif case CURLOPT_HTTP_CONTENT_DECODING: /* * raw data passed to the application when content encoding is used */ data->set.http_ce_skip = (0 == va_arg(param, long)) ? TRUE : FALSE; break; #if !defined(CURL_DISABLE_FTP) || defined(USE_SSH) case CURLOPT_NEW_FILE_PERMS: /* * Uses these permissions instead of 0644 */ arg = va_arg(param, long); if((arg < 0) || (arg > 0777)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.new_file_perms = arg; break; case CURLOPT_NEW_DIRECTORY_PERMS: /* * Uses these permissions instead of 0755 */ arg = va_arg(param, long); if((arg < 0) || (arg > 0777)) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.new_directory_perms = arg; break; #endif case CURLOPT_ADDRESS_SCOPE: /* * Use this scope id when using IPv6 * We always get longs when passed plain numericals so we should check * that the value fits into an unsigned 32 bit integer. */ uarg = va_arg(param, unsigned long); #if SIZEOF_LONG > 4 if(uarg > UINT_MAX) return CURLE_BAD_FUNCTION_ARGUMENT; #endif data->set.scope_id = (unsigned int)uarg; break; case CURLOPT_PROTOCOLS: /* set the bitmask for the protocols that are allowed to be used for the transfer, which thus helps the app which takes URLs from users or other external inputs and want to restrict what protocol(s) to deal with. Defaults to CURLPROTO_ALL. */ data->set.allowed_protocols = va_arg(param, long); break; case CURLOPT_REDIR_PROTOCOLS: /* set the bitmask for the protocols that libcurl is allowed to follow to, as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs to be set in both bitmasks to be allowed to get redirected to. */ data->set.redir_protocols = va_arg(param, long); break; case CURLOPT_DEFAULT_PROTOCOL: /* Set the protocol to use when the URL doesn't include any protocol */ result = Curl_setstropt(&data->set.str[STRING_DEFAULT_PROTOCOL], va_arg(param, char *)); break; #ifndef CURL_DISABLE_SMTP case CURLOPT_MAIL_FROM: /* Set the SMTP mail originator */ result = Curl_setstropt(&data->set.str[STRING_MAIL_FROM], va_arg(param, char *)); break; case CURLOPT_MAIL_AUTH: /* Set the SMTP auth originator */ result = Curl_setstropt(&data->set.str[STRING_MAIL_AUTH], va_arg(param, char *)); break; case CURLOPT_MAIL_RCPT: /* Set the list of mail recipients */ data->set.mail_rcpt = va_arg(param, struct curl_slist *); break; case CURLOPT_MAIL_RCPT_ALLLOWFAILS: /* allow RCPT TO command to fail for some recipients */ data->set.mail_rcpt_allowfails = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #endif case CURLOPT_SASL_AUTHZID: /* Authorisation identity (identity to act as) */ result = Curl_setstropt(&data->set.str[STRING_SASL_AUTHZID], va_arg(param, char *)); break; case CURLOPT_SASL_IR: /* Enable/disable SASL initial response */ data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_RTSP case CURLOPT_RTSP_REQUEST: { /* * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...) * Would this be better if the RTSPREQ_* were just moved into here? */ long in_rtspreq = va_arg(param, long); Curl_RtspReq rtspreq = RTSPREQ_NONE; switch(in_rtspreq) { case CURL_RTSPREQ_OPTIONS: rtspreq = RTSPREQ_OPTIONS; break; case CURL_RTSPREQ_DESCRIBE: rtspreq = RTSPREQ_DESCRIBE; break; case CURL_RTSPREQ_ANNOUNCE: rtspreq = RTSPREQ_ANNOUNCE; break; case CURL_RTSPREQ_SETUP: rtspreq = RTSPREQ_SETUP; break; case CURL_RTSPREQ_PLAY: rtspreq = RTSPREQ_PLAY; break; case CURL_RTSPREQ_PAUSE: rtspreq = RTSPREQ_PAUSE; break; case CURL_RTSPREQ_TEARDOWN: rtspreq = RTSPREQ_TEARDOWN; break; case CURL_RTSPREQ_GET_PARAMETER: rtspreq = RTSPREQ_GET_PARAMETER; break; case CURL_RTSPREQ_SET_PARAMETER: rtspreq = RTSPREQ_SET_PARAMETER; break; case CURL_RTSPREQ_RECORD: rtspreq = RTSPREQ_RECORD; break; case CURL_RTSPREQ_RECEIVE: rtspreq = RTSPREQ_RECEIVE; break; default: rtspreq = RTSPREQ_NONE; } data->set.rtspreq = rtspreq; break; } case CURLOPT_RTSP_SESSION_ID: /* * Set the RTSP Session ID manually. Useful if the application is * resuming a previously established RTSP session */ result = Curl_setstropt(&data->set.str[STRING_RTSP_SESSION_ID], va_arg(param, char *)); break; case CURLOPT_RTSP_STREAM_URI: /* * Set the Stream URI for the RTSP request. Unless the request is * for generic server options, the application will need to set this. */ result = Curl_setstropt(&data->set.str[STRING_RTSP_STREAM_URI], va_arg(param, char *)); break; case CURLOPT_RTSP_TRANSPORT: /* * The content of the Transport: header for the RTSP request */ result = Curl_setstropt(&data->set.str[STRING_RTSP_TRANSPORT], va_arg(param, char *)); break; case CURLOPT_RTSP_CLIENT_CSEQ: /* * Set the CSEQ number to issue for the next RTSP request. Useful if the * application is resuming a previously broken connection. The CSEQ * will increment from this new number henceforth. */ data->state.rtsp_next_client_CSeq = va_arg(param, long); break; case CURLOPT_RTSP_SERVER_CSEQ: /* Same as the above, but for server-initiated requests */ data->state.rtsp_next_server_CSeq = va_arg(param, long); break; case CURLOPT_INTERLEAVEDATA: data->set.rtp_out = va_arg(param, void *); break; case CURLOPT_INTERLEAVEFUNCTION: /* Set the user defined RTP write function */ data->set.fwrite_rtp = va_arg(param, curl_write_callback); break; #endif #ifndef CURL_DISABLE_FTP case CURLOPT_WILDCARDMATCH: data->set.wildcard_enabled = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_CHUNK_BGN_FUNCTION: data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback); break; case CURLOPT_CHUNK_END_FUNCTION: data->set.chunk_end = va_arg(param, curl_chunk_end_callback); break; case CURLOPT_FNMATCH_FUNCTION: data->set.fnmatch = va_arg(param, curl_fnmatch_callback); break; case CURLOPT_CHUNK_DATA: data->wildcard.customptr = va_arg(param, void *); break; case CURLOPT_FNMATCH_DATA: data->set.fnmatch_data = va_arg(param, void *); break; #endif #ifdef USE_TLS_SRP case CURLOPT_TLSAUTH_USERNAME: result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_USERNAME], va_arg(param, char *)); if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype) data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ break; case CURLOPT_PROXY_TLSAUTH_USERNAME: result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_USERNAME_PROXY], va_arg(param, char *)); #ifndef CURL_DISABLE_PROXY if(data->set.str[STRING_TLSAUTH_USERNAME_PROXY] && !data->set.proxy_ssl.authtype) data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ #endif break; case CURLOPT_TLSAUTH_PASSWORD: result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD], va_arg(param, char *)); if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype) data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ break; case CURLOPT_PROXY_TLSAUTH_PASSWORD: result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD_PROXY], va_arg(param, char *)); #ifndef CURL_DISABLE_PROXY if(data->set.str[STRING_TLSAUTH_USERNAME_PROXY] && !data->set.proxy_ssl.authtype) data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */ #endif break; case CURLOPT_TLSAUTH_TYPE: argptr = va_arg(param, char *); if(!argptr || strncasecompare(argptr, "SRP", strlen("SRP"))) data->set.ssl.authtype = CURL_TLSAUTH_SRP; else data->set.ssl.authtype = CURL_TLSAUTH_NONE; break; #ifndef CURL_DISABLE_PROXY case CURLOPT_PROXY_TLSAUTH_TYPE: argptr = va_arg(param, char *); if(!argptr || strncasecompare(argptr, "SRP", strlen("SRP"))) data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; else data->set.proxy_ssl.authtype = CURL_TLSAUTH_NONE; break; #endif #endif #ifdef USE_ARES case CURLOPT_DNS_SERVERS: result = Curl_setstropt(&data->set.str[STRING_DNS_SERVERS], va_arg(param, char *)); if(result) return result; result = Curl_set_dns_servers(data, data->set.str[STRING_DNS_SERVERS]); break; case CURLOPT_DNS_INTERFACE: result = Curl_setstropt(&data->set.str[STRING_DNS_INTERFACE], va_arg(param, char *)); if(result) return result; result = Curl_set_dns_interface(data, data->set.str[STRING_DNS_INTERFACE]); break; case CURLOPT_DNS_LOCAL_IP4: result = Curl_setstropt(&data->set.str[STRING_DNS_LOCAL_IP4], va_arg(param, char *)); if(result) return result; result = Curl_set_dns_local_ip4(data, data->set.str[STRING_DNS_LOCAL_IP4]); break; case CURLOPT_DNS_LOCAL_IP6: result = Curl_setstropt(&data->set.str[STRING_DNS_LOCAL_IP6], va_arg(param, char *)); if(result) return result; result = Curl_set_dns_local_ip6(data, data->set.str[STRING_DNS_LOCAL_IP6]); break; #endif case CURLOPT_TCP_KEEPALIVE: data->set.tcp_keepalive = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_TCP_KEEPIDLE: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.tcp_keepidle = arg; break; case CURLOPT_TCP_KEEPINTVL: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.tcp_keepintvl = arg; break; case CURLOPT_TCP_FASTOPEN: #if defined(CONNECT_DATA_IDEMPOTENT) || defined(MSG_FASTOPEN) || \ defined(TCP_FASTOPEN_CONNECT) data->set.tcp_fastopen = (0 != va_arg(param, long))?TRUE:FALSE; #else result = CURLE_NOT_BUILT_IN; #endif break; case CURLOPT_SSL_ENABLE_NPN: data->set.ssl_enable_npn = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_SSL_ENABLE_ALPN: data->set.ssl_enable_alpn = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifdef USE_UNIX_SOCKETS case CURLOPT_UNIX_SOCKET_PATH: data->set.abstract_unix_socket = FALSE; result = Curl_setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH], va_arg(param, char *)); break; case CURLOPT_ABSTRACT_UNIX_SOCKET: data->set.abstract_unix_socket = TRUE; result = Curl_setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH], va_arg(param, char *)); break; #endif case CURLOPT_PATH_AS_IS: data->set.path_as_is = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_PIPEWAIT: data->set.pipewait = (0 != va_arg(param, long)) ? TRUE : FALSE; break; case CURLOPT_STREAM_WEIGHT: #ifndef USE_NGHTTP2 return CURLE_NOT_BUILT_IN; #else arg = va_arg(param, long); if((arg >= 1) && (arg <= 256)) data->set.stream_weight = (int)arg; break; #endif case CURLOPT_STREAM_DEPENDS: case CURLOPT_STREAM_DEPENDS_E: { #ifndef USE_NGHTTP2 return CURLE_NOT_BUILT_IN; #else struct Curl_easy *dep = va_arg(param, struct Curl_easy *); if(!dep || GOOD_EASY_HANDLE(dep)) { if(data->set.stream_depends_on) { Curl_http2_remove_child(data->set.stream_depends_on, data); } Curl_http2_add_child(dep, data, (option == CURLOPT_STREAM_DEPENDS_E)); } break; #endif } case CURLOPT_CONNECT_TO: data->set.connect_to = va_arg(param, struct curl_slist *); break; case CURLOPT_SUPPRESS_CONNECT_HEADERS: data->set.suppress_connect_headers = (0 != va_arg(param, long))?TRUE:FALSE; break; case CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.happy_eyeballs_timeout = arg; break; #ifndef CURL_DISABLE_SHUFFLE_DNS case CURLOPT_DNS_SHUFFLE_ADDRESSES: data->set.dns_shuffle_addresses = (0 != va_arg(param, long)) ? TRUE:FALSE; break; #endif case CURLOPT_DISALLOW_USERNAME_IN_URL: data->set.disallow_username_in_url = (0 != va_arg(param, long)) ? TRUE : FALSE; break; #ifndef CURL_DISABLE_DOH case CURLOPT_DOH_URL: result = Curl_setstropt(&data->set.str[STRING_DOH], va_arg(param, char *)); data->set.doh = data->set.str[STRING_DOH]?TRUE:FALSE; break; #endif case CURLOPT_UPKEEP_INTERVAL_MS: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.upkeep_interval_ms = arg; break; case CURLOPT_MAXAGE_CONN: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.maxage_conn = arg; break; case CURLOPT_MAXLIFETIME_CONN: arg = va_arg(param, long); if(arg < 0) return CURLE_BAD_FUNCTION_ARGUMENT; data->set.maxlifetime_conn = arg; break; case CURLOPT_TRAILERFUNCTION: #ifndef CURL_DISABLE_HTTP data->set.trailer_callback = va_arg(param, curl_trailer_callback); #endif break; case CURLOPT_TRAILERDATA: #ifndef CURL_DISABLE_HTTP data->set.trailer_data = va_arg(param, void *); #endif break; #ifndef CURL_DISABLE_HSTS case CURLOPT_HSTSREADFUNCTION: data->set.hsts_read = va_arg(param, curl_hstsread_callback); break; case CURLOPT_HSTSREADDATA: data->set.hsts_read_userp = va_arg(param, void *); break; case CURLOPT_HSTSWRITEFUNCTION: data->set.hsts_write = va_arg(param, curl_hstswrite_callback); break; case CURLOPT_HSTSWRITEDATA: data->set.hsts_write_userp = va_arg(param, void *); break; case CURLOPT_HSTS: if(!data->hsts) { data->hsts = Curl_hsts_init(); if(!data->hsts) return CURLE_OUT_OF_MEMORY; } argptr = va_arg(param, char *); result = Curl_setstropt(&data->set.str[STRING_HSTS], argptr); if(result) return result; if(argptr) (void)Curl_hsts_loadfile(data, data->hsts, argptr); break; case CURLOPT_HSTS_CTRL: arg = va_arg(param, long); if(arg & CURLHSTS_ENABLE) { if(!data->hsts) { data->hsts = Curl_hsts_init(); if(!data->hsts) return CURLE_OUT_OF_MEMORY; } } else Curl_hsts_cleanup(&data->hsts); break; #endif #ifndef CURL_DISABLE_ALTSVC case CURLOPT_ALTSVC: if(!data->asi) { data->asi = Curl_altsvc_init(); if(!data->asi) return CURLE_OUT_OF_MEMORY; } argptr = va_arg(param, char *); result = Curl_setstropt(&data->set.str[STRING_ALTSVC], argptr); if(result) return result; if(argptr) (void)Curl_altsvc_load(data->asi, argptr); break; case CURLOPT_ALTSVC_CTRL: if(!data->asi) { data->asi = Curl_altsvc_init(); if(!data->asi) return CURLE_OUT_OF_MEMORY; } arg = va_arg(param, long); result = Curl_altsvc_ctrl(data->asi, arg); if(result) return result; break; #endif case CURLOPT_PREREQFUNCTION: data->set.fprereq = va_arg(param, curl_prereq_callback); break; case CURLOPT_PREREQDATA: data->set.prereq_userp = va_arg(param, void *); break; default: /* unknown tag and its companion, just ignore: */ result = CURLE_UNKNOWN_OPTION; break; } return result; } /* * curl_easy_setopt() is the external interface for setting options on an * easy handle. * * NOTE: This is one of few API functions that are allowed to be called from * within a callback. */ #undef curl_easy_setopt CURLcode curl_easy_setopt(struct Curl_easy *data, CURLoption tag, ...) { va_list arg; CURLcode result; if(!data) return CURLE_BAD_FUNCTION_ARGUMENT; va_start(arg, tag); result = Curl_vsetopt(data, tag, arg); va_end(arg); return result; }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/mqtt.h
#ifndef HEADER_CURL_MQTT_H #define HEADER_CURL_MQTT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2019 - 2020, Björn Stenberg, <[email protected]> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifndef CURL_DISABLE_MQTT extern const struct Curl_handler Curl_handler_mqtt; #endif enum mqttstate { MQTT_FIRST, /* 0 */ MQTT_REMAINING_LENGTH, /* 1 */ MQTT_CONNACK, /* 2 */ MQTT_SUBACK, /* 3 */ MQTT_SUBACK_COMING, /* 4 - the SUBACK remainder */ MQTT_PUBWAIT, /* 5 - wait for publish */ MQTT_PUB_REMAIN, /* 6 - wait for the remainder of the publish */ MQTT_NOSTATE /* 7 - never used an actual state */ }; struct mqtt_conn { enum mqttstate state; enum mqttstate nextstate; /* switch to this after remaining length is done */ unsigned int packetid; }; /* protocol-specific transfer-related data */ struct MQTT { char *sendleftovers; size_t nsend; /* size of sendleftovers */ /* when receiving */ size_t npacket; /* byte counter */ unsigned char firstbyte; size_t remaining_length; }; #endif /* HEADER_CURL_MQTT_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/easy.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /* * See comment in curl_memory.h for the explanation of this sanity check. */ #ifdef CURLX_NO_MEMORY_CALLBACKS #error "libcurl shall not ever be built with CURLX_NO_MEMORY_CALLBACKS defined" #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H #include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H #include <sys/ioctl.h> #endif #ifdef HAVE_SYS_PARAM_H #include <sys/param.h> #endif #include "urldata.h" #include <curl/curl.h> #include "transfer.h" #include "vtls/vtls.h" #include "url.h" #include "getinfo.h" #include "hostip.h" #include "share.h" #include "strdup.h" #include "progress.h" #include "easyif.h" #include "multiif.h" #include "select.h" #include "sendf.h" /* for failf function prototype */ #include "connect.h" /* for Curl_getconnectinfo */ #include "slist.h" #include "mime.h" #include "amigaos.h" #include "non-ascii.h" #include "warnless.h" #include "multiif.h" #include "sigpipe.h" #include "vssh/ssh.h" #include "setopt.h" #include "http_digest.h" #include "system_win32.h" #include "http2.h" #include "dynbuf.h" #include "altsvc.h" #include "hsts.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* true globals -- for curl_global_init() and curl_global_cleanup() */ static unsigned int initialized; static long init_flags; /* * strdup (and other memory functions) is redefined in complicated * ways, but at this point it must be defined as the system-supplied strdup * so the callback pointer is initialized correctly. */ #if defined(_WIN32_WCE) #define system_strdup _strdup #elif !defined(HAVE_STRDUP) #define system_strdup curlx_strdup #else #define system_strdup strdup #endif #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__) # pragma warning(disable:4232) /* MSVC extension, dllimport identity */ #endif /* * If a memory-using function (like curl_getenv) is used before * curl_global_init() is called, we need to have these pointers set already. */ curl_malloc_callback Curl_cmalloc = (curl_malloc_callback)malloc; curl_free_callback Curl_cfree = (curl_free_callback)free; curl_realloc_callback Curl_crealloc = (curl_realloc_callback)realloc; curl_strdup_callback Curl_cstrdup = (curl_strdup_callback)system_strdup; curl_calloc_callback Curl_ccalloc = (curl_calloc_callback)calloc; #if defined(WIN32) && defined(UNICODE) curl_wcsdup_callback Curl_cwcsdup = Curl_wcsdup; #endif #if defined(_MSC_VER) && defined(_DLL) && !defined(__POCC__) # pragma warning(default:4232) /* MSVC extension, dllimport identity */ #endif #ifdef DEBUGBUILD static char *leakpointer; #endif /** * curl_global_init() globally initializes curl given a bitwise set of the * different features of what to initialize. */ static CURLcode global_init(long flags, bool memoryfuncs) { if(initialized++) return CURLE_OK; if(memoryfuncs) { /* Setup the default memory functions here (again) */ Curl_cmalloc = (curl_malloc_callback)malloc; Curl_cfree = (curl_free_callback)free; Curl_crealloc = (curl_realloc_callback)realloc; Curl_cstrdup = (curl_strdup_callback)system_strdup; Curl_ccalloc = (curl_calloc_callback)calloc; #if defined(WIN32) && defined(UNICODE) Curl_cwcsdup = (curl_wcsdup_callback)_wcsdup; #endif } if(!Curl_ssl_init()) { DEBUGF(fprintf(stderr, "Error: Curl_ssl_init failed\n")); goto fail; } #ifdef WIN32 if(Curl_win32_init(flags)) { DEBUGF(fprintf(stderr, "Error: win32_init failed\n")); goto fail; } #endif #ifdef __AMIGA__ if(!Curl_amiga_init()) { DEBUGF(fprintf(stderr, "Error: Curl_amiga_init failed\n")); goto fail; } #endif #ifdef NETWARE if(netware_init()) { DEBUGF(fprintf(stderr, "Warning: LONG namespace not available\n")); } #endif if(Curl_resolver_global_init()) { DEBUGF(fprintf(stderr, "Error: resolver_global_init failed\n")); goto fail; } #if defined(USE_SSH) if(Curl_ssh_init()) { goto fail; } #endif #ifdef USE_WOLFSSH if(WS_SUCCESS != wolfSSH_Init()) { DEBUGF(fprintf(stderr, "Error: wolfSSH_Init failed\n")); return CURLE_FAILED_INIT; } #endif init_flags = flags; #ifdef DEBUGBUILD if(getenv("CURL_GLOBAL_INIT")) /* alloc data that will leak if *cleanup() is not called! */ leakpointer = malloc(1); #endif return CURLE_OK; fail: initialized--; /* undo the increase */ return CURLE_FAILED_INIT; } /** * curl_global_init() globally initializes curl given a bitwise set of the * different features of what to initialize. */ CURLcode curl_global_init(long flags) { return global_init(flags, TRUE); } /* * curl_global_init_mem() globally initializes curl and also registers the * user provided callback routines. */ CURLcode curl_global_init_mem(long flags, curl_malloc_callback m, curl_free_callback f, curl_realloc_callback r, curl_strdup_callback s, curl_calloc_callback c) { /* Invalid input, return immediately */ if(!m || !f || !r || !s || !c) return CURLE_FAILED_INIT; if(initialized) { /* Already initialized, don't do it again, but bump the variable anyway to work like curl_global_init() and require the same amount of cleanup calls. */ initialized++; return CURLE_OK; } /* set memory functions before global_init() in case it wants memory functions */ Curl_cmalloc = m; Curl_cfree = f; Curl_cstrdup = s; Curl_crealloc = r; Curl_ccalloc = c; /* Call the actual init function, but without setting */ return global_init(flags, FALSE); } /** * curl_global_cleanup() globally cleanups curl, uses the value of * "init_flags" to determine what needs to be cleaned up and what doesn't. */ void curl_global_cleanup(void) { if(!initialized) return; if(--initialized) return; Curl_ssl_cleanup(); Curl_resolver_global_cleanup(); #ifdef WIN32 Curl_win32_cleanup(init_flags); #endif Curl_amiga_cleanup(); Curl_ssh_cleanup(); #ifdef USE_WOLFSSH (void)wolfSSH_Cleanup(); #endif #ifdef DEBUGBUILD free(leakpointer); #endif init_flags = 0; } /* * curl_easy_init() is the external interface to alloc, setup and init an * easy handle that is returned. If anything goes wrong, NULL is returned. */ struct Curl_easy *curl_easy_init(void) { CURLcode result; struct Curl_easy *data; /* Make sure we inited the global SSL stuff */ if(!initialized) { result = curl_global_init(CURL_GLOBAL_DEFAULT); if(result) { /* something in the global init failed, return nothing */ DEBUGF(fprintf(stderr, "Error: curl_global_init failed\n")); return NULL; } } /* We use curl_open() with undefined URL so far */ result = Curl_open(&data); if(result) { DEBUGF(fprintf(stderr, "Error: Curl_open failed\n")); return NULL; } return data; } #ifdef CURLDEBUG struct socketmonitor { struct socketmonitor *next; /* the next node in the list or NULL */ struct pollfd socket; /* socket info of what to monitor */ }; struct events { long ms; /* timeout, run the timeout function when reached */ bool msbump; /* set TRUE when timeout is set by callback */ int num_sockets; /* number of nodes in the monitor list */ struct socketmonitor *list; /* list of sockets to monitor */ int running_handles; /* store the returned number */ }; /* events_timer * * Callback that gets called with a new value when the timeout should be * updated. */ static int events_timer(struct Curl_multi *multi, /* multi handle */ long timeout_ms, /* see above */ void *userp) /* private callback pointer */ { struct events *ev = userp; (void)multi; if(timeout_ms == -1) /* timeout removed */ timeout_ms = 0; else if(timeout_ms == 0) /* timeout is already reached! */ timeout_ms = 1; /* trigger asap */ ev->ms = timeout_ms; ev->msbump = TRUE; return 0; } /* poll2cselect * * convert from poll() bit definitions to libcurl's CURL_CSELECT_* ones */ static int poll2cselect(int pollmask) { int omask = 0; if(pollmask & POLLIN) omask |= CURL_CSELECT_IN; if(pollmask & POLLOUT) omask |= CURL_CSELECT_OUT; if(pollmask & POLLERR) omask |= CURL_CSELECT_ERR; return omask; } /* socketcb2poll * * convert from libcurl' CURL_POLL_* bit definitions to poll()'s */ static short socketcb2poll(int pollmask) { short omask = 0; if(pollmask & CURL_POLL_IN) omask |= POLLIN; if(pollmask & CURL_POLL_OUT) omask |= POLLOUT; return omask; } /* events_socket * * Callback that gets called with information about socket activity to * monitor. */ static int events_socket(struct Curl_easy *easy, /* easy handle */ curl_socket_t s, /* socket */ int what, /* see above */ void *userp, /* private callback pointer */ void *socketp) /* private socket pointer */ { struct events *ev = userp; struct socketmonitor *m; struct socketmonitor *prev = NULL; #if defined(CURL_DISABLE_VERBOSE_STRINGS) (void) easy; #endif (void)socketp; m = ev->list; while(m) { if(m->socket.fd == s) { if(what == CURL_POLL_REMOVE) { struct socketmonitor *nxt = m->next; /* remove this node from the list of monitored sockets */ if(prev) prev->next = nxt; else ev->list = nxt; free(m); m = nxt; infof(easy, "socket cb: socket %d REMOVED", s); } else { /* The socket 's' is already being monitored, update the activity mask. Convert from libcurl bitmask to the poll one. */ m->socket.events = socketcb2poll(what); infof(easy, "socket cb: socket %d UPDATED as %s%s", s, (what&CURL_POLL_IN)?"IN":"", (what&CURL_POLL_OUT)?"OUT":""); } break; } prev = m; m = m->next; /* move to next node */ } if(!m) { if(what == CURL_POLL_REMOVE) { /* this happens a bit too often, libcurl fix perhaps? */ /* fprintf(stderr, "%s: socket %d asked to be REMOVED but not present!\n", __func__, s); */ } else { m = malloc(sizeof(struct socketmonitor)); if(m) { m->next = ev->list; m->socket.fd = s; m->socket.events = socketcb2poll(what); m->socket.revents = 0; ev->list = m; infof(easy, "socket cb: socket %d ADDED as %s%s", s, (what&CURL_POLL_IN)?"IN":"", (what&CURL_POLL_OUT)?"OUT":""); } else return CURLE_OUT_OF_MEMORY; } } return 0; } /* * events_setup() * * Do the multi handle setups that only event-based transfers need. */ static void events_setup(struct Curl_multi *multi, struct events *ev) { /* timer callback */ curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, events_timer); curl_multi_setopt(multi, CURLMOPT_TIMERDATA, ev); /* socket callback */ curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, events_socket); curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, ev); } /* wait_or_timeout() * * waits for activity on any of the given sockets, or the timeout to trigger. */ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev) { bool done = FALSE; CURLMcode mcode = CURLM_OK; CURLcode result = CURLE_OK; while(!done) { CURLMsg *msg; struct socketmonitor *m; struct pollfd *f; struct pollfd fds[4]; int numfds = 0; int pollrc; int i; struct curltime before; struct curltime after; /* populate the fds[] array */ for(m = ev->list, f = &fds[0]; m; m = m->next) { f->fd = m->socket.fd; f->events = m->socket.events; f->revents = 0; /* fprintf(stderr, "poll() %d check socket %d\n", numfds, f->fd); */ f++; numfds++; } /* get the time stamp to use to figure out how long poll takes */ before = Curl_now(); /* wait for activity or timeout */ pollrc = Curl_poll(fds, numfds, ev->ms); after = Curl_now(); ev->msbump = FALSE; /* reset here */ if(0 == pollrc) { /* timeout! */ ev->ms = 0; /* fprintf(stderr, "call curl_multi_socket_action(TIMEOUT)\n"); */ mcode = curl_multi_socket_action(multi, CURL_SOCKET_TIMEOUT, 0, &ev->running_handles); } else if(pollrc > 0) { /* loop over the monitored sockets to see which ones had activity */ for(i = 0; i< numfds; i++) { if(fds[i].revents) { /* socket activity, tell libcurl */ int act = poll2cselect(fds[i].revents); /* convert */ infof(multi->easyp, "call curl_multi_socket_action(socket %d)", fds[i].fd); mcode = curl_multi_socket_action(multi, fds[i].fd, act, &ev->running_handles); } } if(!ev->msbump) { /* If nothing updated the timeout, we decrease it by the spent time. * If it was updated, it has the new timeout time stored already. */ timediff_t timediff = Curl_timediff(after, before); if(timediff > 0) { if(timediff > ev->ms) ev->ms = 0; else ev->ms -= (long)timediff; } } } else return CURLE_RECV_ERROR; if(mcode) return CURLE_URL_MALFORMAT; /* we don't really care about the "msgs_in_queue" value returned in the second argument */ msg = curl_multi_info_read(multi, &pollrc); if(msg) { result = msg->data.result; done = TRUE; } } return result; } /* easy_events() * * Runs a transfer in a blocking manner using the events-based API */ static CURLcode easy_events(struct Curl_multi *multi) { /* this struct is made static to allow it to be used after this function returns and curl_multi_remove_handle() is called */ static struct events evs = {2, FALSE, 0, NULL, 0}; /* if running event-based, do some further multi inits */ events_setup(multi, &evs); return wait_or_timeout(multi, &evs); } #else /* CURLDEBUG */ /* when not built with debug, this function doesn't exist */ #define easy_events(x) CURLE_NOT_BUILT_IN #endif static CURLcode easy_transfer(struct Curl_multi *multi) { bool done = FALSE; CURLMcode mcode = CURLM_OK; CURLcode result = CURLE_OK; while(!done && !mcode) { int still_running = 0; mcode = curl_multi_poll(multi, NULL, 0, 1000, NULL); if(!mcode) mcode = curl_multi_perform(multi, &still_running); /* only read 'still_running' if curl_multi_perform() return OK */ if(!mcode && !still_running) { int rc; CURLMsg *msg = curl_multi_info_read(multi, &rc); if(msg) { result = msg->data.result; done = TRUE; } } } /* Make sure to return some kind of error if there was a multi problem */ if(mcode) { result = (mcode == CURLM_OUT_OF_MEMORY) ? CURLE_OUT_OF_MEMORY : /* The other multi errors should never happen, so return something suitably generic */ CURLE_BAD_FUNCTION_ARGUMENT; } return result; } /* * easy_perform() is the external interface that performs a blocking * transfer as previously setup. * * CONCEPT: This function creates a multi handle, adds the easy handle to it, * runs curl_multi_perform() until the transfer is done, then detaches the * easy handle, destroys the multi handle and returns the easy handle's return * code. * * REALITY: it can't just create and destroy the multi handle that easily. It * needs to keep it around since if this easy handle is used again by this * function, the same multi handle must be re-used so that the same pools and * caches can be used. * * DEBUG: if 'events' is set TRUE, this function will use a replacement engine * instead of curl_multi_perform() and use curl_multi_socket_action(). */ static CURLcode easy_perform(struct Curl_easy *data, bool events) { struct Curl_multi *multi; CURLMcode mcode; CURLcode result = CURLE_OK; SIGPIPE_VARIABLE(pipe_st); if(!data) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->set.errorbuffer) /* clear this as early as possible */ data->set.errorbuffer[0] = 0; if(data->multi) { failf(data, "easy handle already used in multi handle"); return CURLE_FAILED_INIT; } if(data->multi_easy) multi = data->multi_easy; else { /* this multi handle will only ever have a single easy handled attached to it, so make it use minimal hashes */ multi = Curl_multi_handle(1, 3); if(!multi) return CURLE_OUT_OF_MEMORY; data->multi_easy = multi; } if(multi->in_callback) return CURLE_RECURSIVE_API_CALL; /* Copy the MAXCONNECTS option to the multi handle */ curl_multi_setopt(multi, CURLMOPT_MAXCONNECTS, data->set.maxconnects); mcode = curl_multi_add_handle(multi, data); if(mcode) { curl_multi_cleanup(multi); data->multi_easy = NULL; if(mcode == CURLM_OUT_OF_MEMORY) return CURLE_OUT_OF_MEMORY; return CURLE_FAILED_INIT; } sigpipe_ignore(data, &pipe_st); /* run the transfer */ result = events ? easy_events(multi) : easy_transfer(multi); /* ignoring the return code isn't nice, but atm we can't really handle a failure here, room for future improvement! */ (void)curl_multi_remove_handle(multi, data); sigpipe_restore(&pipe_st); /* The multi handle is kept alive, owned by the easy handle */ return result; } /* * curl_easy_perform() is the external interface that performs a blocking * transfer as previously setup. */ CURLcode curl_easy_perform(struct Curl_easy *data) { return easy_perform(data, FALSE); } #ifdef CURLDEBUG /* * curl_easy_perform_ev() is the external interface that performs a blocking * transfer using the event-based API internally. */ CURLcode curl_easy_perform_ev(struct Curl_easy *data) { return easy_perform(data, TRUE); } #endif /* * curl_easy_cleanup() is the external interface to cleaning/freeing the given * easy handle. */ void curl_easy_cleanup(struct Curl_easy *data) { SIGPIPE_VARIABLE(pipe_st); if(!data) return; sigpipe_ignore(data, &pipe_st); Curl_close(&data); sigpipe_restore(&pipe_st); } /* * curl_easy_getinfo() is an external interface that allows an app to retrieve * information from a performed transfer and similar. */ #undef curl_easy_getinfo CURLcode curl_easy_getinfo(struct Curl_easy *data, CURLINFO info, ...) { va_list arg; void *paramp; CURLcode result; va_start(arg, info); paramp = va_arg(arg, void *); result = Curl_getinfo(data, info, paramp); va_end(arg); return result; } static CURLcode dupset(struct Curl_easy *dst, struct Curl_easy *src) { CURLcode result = CURLE_OK; enum dupstring i; enum dupblob j; /* Copy src->set into dst->set first, then deal with the strings afterwards */ dst->set = src->set; Curl_mime_initpart(&dst->set.mimepost, dst); /* clear all string pointers first */ memset(dst->set.str, 0, STRING_LAST * sizeof(char *)); /* duplicate all strings */ for(i = (enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) { result = Curl_setstropt(&dst->set.str[i], src->set.str[i]); if(result) return result; } /* clear all blob pointers first */ memset(dst->set.blobs, 0, BLOB_LAST * sizeof(struct curl_blob *)); /* duplicate all blobs */ for(j = (enum dupblob)0; j < BLOB_LAST; j++) { result = Curl_setblobopt(&dst->set.blobs[j], src->set.blobs[j]); if(result) return result; } /* duplicate memory areas pointed to */ i = STRING_COPYPOSTFIELDS; if(src->set.postfieldsize && src->set.str[i]) { /* postfieldsize is curl_off_t, Curl_memdup() takes a size_t ... */ dst->set.str[i] = Curl_memdup(src->set.str[i], curlx_sotouz(src->set.postfieldsize)); if(!dst->set.str[i]) return CURLE_OUT_OF_MEMORY; /* point to the new copy */ dst->set.postfields = dst->set.str[i]; } /* Duplicate mime data. */ result = Curl_mime_duppart(&dst->set.mimepost, &src->set.mimepost); if(src->set.resolve) dst->state.resolve = dst->set.resolve; return result; } /* * curl_easy_duphandle() is an external interface to allow duplication of a * given input easy handle. The returned handle will be a new working handle * with all options set exactly as the input source handle. */ struct Curl_easy *curl_easy_duphandle(struct Curl_easy *data) { struct Curl_easy *outcurl = calloc(1, sizeof(struct Curl_easy)); if(NULL == outcurl) goto fail; /* * We setup a few buffers we need. We should probably make them * get setup on-demand in the code, as that would probably decrease * the likeliness of us forgetting to init a buffer here in the future. */ outcurl->set.buffer_size = data->set.buffer_size; /* copy all userdefined values */ if(dupset(outcurl, data)) goto fail; Curl_dyn_init(&outcurl->state.headerb, CURL_MAX_HTTP_HEADER); /* the connection cache is setup on demand */ outcurl->state.conn_cache = NULL; outcurl->state.lastconnect_id = -1; outcurl->progress.flags = data->progress.flags; outcurl->progress.callback = data->progress.callback; if(data->cookies) { /* If cookies are enabled in the parent handle, we enable them in the clone as well! */ outcurl->cookies = Curl_cookie_init(data, data->cookies->filename, outcurl->cookies, data->set.cookiesession); if(!outcurl->cookies) goto fail; } /* duplicate all values in 'change' */ if(data->state.cookielist) { outcurl->state.cookielist = Curl_slist_duplicate(data->state.cookielist); if(!outcurl->state.cookielist) goto fail; } if(data->state.url) { outcurl->state.url = strdup(data->state.url); if(!outcurl->state.url) goto fail; outcurl->state.url_alloc = TRUE; } if(data->state.referer) { outcurl->state.referer = strdup(data->state.referer); if(!outcurl->state.referer) goto fail; outcurl->state.referer_alloc = TRUE; } /* Reinitialize an SSL engine for the new handle * note: the engine name has already been copied by dupset */ if(outcurl->set.str[STRING_SSL_ENGINE]) { if(Curl_ssl_set_engine(outcurl, outcurl->set.str[STRING_SSL_ENGINE])) goto fail; } #ifdef USE_ALTSVC if(data->asi) { outcurl->asi = Curl_altsvc_init(); if(!outcurl->asi) goto fail; if(outcurl->set.str[STRING_ALTSVC]) (void)Curl_altsvc_load(outcurl->asi, outcurl->set.str[STRING_ALTSVC]); } #endif #ifndef CURL_DISABLE_HSTS if(data->hsts) { outcurl->hsts = Curl_hsts_init(); if(!outcurl->hsts) goto fail; if(outcurl->set.str[STRING_HSTS]) (void)Curl_hsts_loadfile(outcurl, outcurl->hsts, outcurl->set.str[STRING_HSTS]); (void)Curl_hsts_loadcb(outcurl, outcurl->hsts); } #endif /* Clone the resolver handle, if present, for the new handle */ if(Curl_resolver_duphandle(outcurl, &outcurl->state.async.resolver, data->state.async.resolver)) goto fail; #ifdef USE_ARES { CURLcode rc; rc = Curl_set_dns_servers(outcurl, data->set.str[STRING_DNS_SERVERS]); if(rc && rc != CURLE_NOT_BUILT_IN) goto fail; rc = Curl_set_dns_interface(outcurl, data->set.str[STRING_DNS_INTERFACE]); if(rc && rc != CURLE_NOT_BUILT_IN) goto fail; rc = Curl_set_dns_local_ip4(outcurl, data->set.str[STRING_DNS_LOCAL_IP4]); if(rc && rc != CURLE_NOT_BUILT_IN) goto fail; rc = Curl_set_dns_local_ip6(outcurl, data->set.str[STRING_DNS_LOCAL_IP6]); if(rc && rc != CURLE_NOT_BUILT_IN) goto fail; } #endif /* USE_ARES */ Curl_convert_setup(outcurl); Curl_initinfo(outcurl); outcurl->magic = CURLEASY_MAGIC_NUMBER; /* we reach this point and thus we are OK */ return outcurl; fail: if(outcurl) { curl_slist_free_all(outcurl->state.cookielist); outcurl->state.cookielist = NULL; Curl_safefree(outcurl->state.buffer); Curl_dyn_free(&outcurl->state.headerb); Curl_safefree(outcurl->state.url); Curl_safefree(outcurl->state.referer); Curl_altsvc_cleanup(&outcurl->asi); Curl_hsts_cleanup(&outcurl->hsts); Curl_freeset(outcurl); free(outcurl); } return NULL; } /* * curl_easy_reset() is an external interface that allows an app to re- * initialize a session handle to the default values. */ void curl_easy_reset(struct Curl_easy *data) { Curl_free_request_state(data); /* zero out UserDefined data: */ Curl_freeset(data); memset(&data->set, 0, sizeof(struct UserDefined)); (void)Curl_init_userdefined(data); /* zero out Progress data: */ memset(&data->progress, 0, sizeof(struct Progress)); /* zero out PureInfo data: */ Curl_initinfo(data); data->progress.flags |= PGRS_HIDE; data->state.current_speed = -1; /* init to negative == impossible */ data->state.retrycount = 0; /* reset the retry counter */ /* zero out authentication data: */ memset(&data->state.authhost, 0, sizeof(struct auth)); memset(&data->state.authproxy, 0, sizeof(struct auth)); #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) Curl_http_auth_cleanup_digest(data); #endif } /* * curl_easy_pause() allows an application to pause or unpause a specific * transfer and direction. This function sets the full new state for the * current connection this easy handle operates on. * * NOTE: if you have the receiving paused and you call this function to remove * the pausing, you may get your write callback called at this point. * * Action is a bitmask consisting of CURLPAUSE_* bits in curl/curl.h * * NOTE: This is one of few API functions that are allowed to be called from * within a callback. */ CURLcode curl_easy_pause(struct Curl_easy *data, int action) { struct SingleRequest *k; CURLcode result = CURLE_OK; int oldstate; int newstate; if(!GOOD_EASY_HANDLE(data) || !data->conn) /* crazy input, don't continue */ return CURLE_BAD_FUNCTION_ARGUMENT; k = &data->req; oldstate = k->keepon & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE); /* first switch off both pause bits then set the new pause bits */ newstate = (k->keepon &~ (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) | ((action & CURLPAUSE_RECV)?KEEP_RECV_PAUSE:0) | ((action & CURLPAUSE_SEND)?KEEP_SEND_PAUSE:0); if((newstate & (KEEP_RECV_PAUSE| KEEP_SEND_PAUSE)) == oldstate) { /* Not changing any pause state, return */ DEBUGF(infof(data, "pause: no change, early return")); return CURLE_OK; } /* Unpause parts in active mime tree. */ if((k->keepon & ~newstate & KEEP_SEND_PAUSE) && (data->mstate == MSTATE_PERFORMING || data->mstate == MSTATE_RATELIMITING) && data->state.fread_func == (curl_read_callback) Curl_mime_read) { Curl_mime_unpause(data->state.in); } /* put it back in the keepon */ k->keepon = newstate; if(!(newstate & KEEP_RECV_PAUSE)) { Curl_http2_stream_pause(data, FALSE); if(data->state.tempcount) { /* there are buffers for sending that can be delivered as the receive pausing is lifted! */ unsigned int i; unsigned int count = data->state.tempcount; struct tempbuf writebuf[3]; /* there can only be three */ /* copy the structs to allow for immediate re-pausing */ for(i = 0; i < data->state.tempcount; i++) { writebuf[i] = data->state.tempwrite[i]; Curl_dyn_init(&data->state.tempwrite[i].b, DYN_PAUSE_BUFFER); } data->state.tempcount = 0; for(i = 0; i < count; i++) { /* even if one function returns error, this loops through and frees all buffers */ if(!result) result = Curl_client_write(data, writebuf[i].type, Curl_dyn_ptr(&writebuf[i].b), Curl_dyn_len(&writebuf[i].b)); Curl_dyn_free(&writebuf[i].b); } if(result) return result; } } /* if there's no error and we're not pausing both directions, we want to have this handle checked soon */ if((newstate & (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) != (KEEP_RECV_PAUSE|KEEP_SEND_PAUSE)) { Curl_expire(data, 0, EXPIRE_RUN_NOW); /* get this handle going again */ /* reset the too-slow time keeper */ data->state.keeps_speed.tv_sec = 0; if(!data->state.tempcount) /* if not pausing again, force a recv/send check of this connection as the data might've been read off the socket already */ data->conn->cselect_bits = CURL_CSELECT_IN | CURL_CSELECT_OUT; if(data->multi) Curl_update_timer(data->multi); } if(!data->state.done) /* This transfer may have been moved in or out of the bundle, update the corresponding socket callback, if used */ Curl_updatesocket(data); return result; } static CURLcode easy_connection(struct Curl_easy *data, curl_socket_t *sfd, struct connectdata **connp) { if(!data) return CURLE_BAD_FUNCTION_ARGUMENT; /* only allow these to be called on handles with CURLOPT_CONNECT_ONLY */ if(!data->set.connect_only) { failf(data, "CONNECT_ONLY is required!"); return CURLE_UNSUPPORTED_PROTOCOL; } *sfd = Curl_getconnectinfo(data, connp); if(*sfd == CURL_SOCKET_BAD) { failf(data, "Failed to get recent socket"); return CURLE_UNSUPPORTED_PROTOCOL; } return CURLE_OK; } /* * Receives data from the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. * Returns CURLE_OK on success, error code on error. */ CURLcode curl_easy_recv(struct Curl_easy *data, void *buffer, size_t buflen, size_t *n) { curl_socket_t sfd; CURLcode result; ssize_t n1; struct connectdata *c; if(Curl_is_in_callback(data)) return CURLE_RECURSIVE_API_CALL; result = easy_connection(data, &sfd, &c); if(result) return result; if(!data->conn) /* on first invoke, the transfer has been detached from the connection and needs to be reattached */ Curl_attach_connnection(data, c); *n = 0; result = Curl_read(data, sfd, buffer, buflen, &n1); if(result) return result; *n = (size_t)n1; return CURLE_OK; } /* * Sends data over the connected socket. Use after successful * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. */ CURLcode curl_easy_send(struct Curl_easy *data, const void *buffer, size_t buflen, size_t *n) { curl_socket_t sfd; CURLcode result; ssize_t n1; struct connectdata *c = NULL; SIGPIPE_VARIABLE(pipe_st); if(Curl_is_in_callback(data)) return CURLE_RECURSIVE_API_CALL; result = easy_connection(data, &sfd, &c); if(result) return result; if(!data->conn) /* on first invoke, the transfer has been detached from the connection and needs to be reattached */ Curl_attach_connnection(data, c); *n = 0; sigpipe_ignore(data, &pipe_st); result = Curl_write(data, sfd, buffer, buflen, &n1); sigpipe_restore(&pipe_st); if(n1 == -1) return CURLE_SEND_ERROR; /* detect EAGAIN */ if(!result && !n1) return CURLE_AGAIN; *n = (size_t)n1; return result; } /* * Wrapper to call functions in Curl_conncache_foreach() * * Returns always 0. */ static int conn_upkeep(struct Curl_easy *data, struct connectdata *conn, void *param) { /* Param is unused. */ (void)param; if(conn->handler->connection_check) { /* briefly attach the connection to this transfer for the purpose of checking it */ Curl_attach_connnection(data, conn); /* Do a protocol-specific keepalive check on the connection. */ conn->handler->connection_check(data, conn, CONNCHECK_KEEPALIVE); /* detach the connection again */ Curl_detach_connnection(data); } return 0; /* continue iteration */ } static CURLcode upkeep(struct conncache *conn_cache, void *data) { /* Loop over every connection and make connection alive. */ Curl_conncache_foreach(data, conn_cache, data, conn_upkeep); return CURLE_OK; } /* * Performs connection upkeep for the given session handle. */ CURLcode curl_easy_upkeep(struct Curl_easy *data) { /* Verify that we got an easy handle we can work with. */ if(!GOOD_EASY_HANDLE(data)) return CURLE_BAD_FUNCTION_ARGUMENT; if(data->multi_easy) { /* Use the common function to keep connections alive. */ return upkeep(&data->multi_easy->conn_cache, data); } else { /* No connections, so just return success */ return CURLE_OK; } }
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_fnmatch.h
#ifndef HEADER_CURL_FNMATCH_H #define HEADER_CURL_FNMATCH_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #define CURL_FNMATCH_MATCH 0 #define CURL_FNMATCH_NOMATCH 1 #define CURL_FNMATCH_FAIL 2 /* default pattern matching function * ================================= * Implemented with recursive backtracking, if you want to use Curl_fnmatch, * please note that there is not implemented UTF/UNICODE support. * * Implemented features: * '?' notation, does not match UTF characters * '*' can also work with UTF string * [a-zA-Z0-9] enumeration support * * keywords: alnum, digit, xdigit, alpha, print, blank, lower, graph, space * and upper (use as "[[:alnum:]]") */ int Curl_fnmatch(void *ptr, const char *pattern, const char *string); #endif /* HEADER_CURL_FNMATCH_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/version_win32.h
#ifndef HEADER_CURL_VERSION_WIN32_H #define HEADER_CURL_VERSION_WIN32_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2016 - 2020, Steve Holme, <[email protected]>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #if defined(WIN32) /* Version condition */ typedef enum { VERSION_LESS_THAN, VERSION_LESS_THAN_EQUAL, VERSION_EQUAL, VERSION_GREATER_THAN_EQUAL, VERSION_GREATER_THAN } VersionCondition; /* Platform identifier */ typedef enum { PLATFORM_DONT_CARE, PLATFORM_WINDOWS, PLATFORM_WINNT } PlatformIdentifier; /* This is used to verify if we are running on a specific windows version */ bool curlx_verify_windows_version(const unsigned int majorVersion, const unsigned int minorVersion, const PlatformIdentifier platform, const VersionCondition condition); #endif /* WIN32 */ #endif /* HEADER_CURL_VERSION_WIN32_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/formdata.h
#ifndef HEADER_CURL_FORMDATA_H #define HEADER_CURL_FORMDATA_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_MIME /* used by FormAdd for temporary storage */ struct FormInfo { char *name; size_t namelength; char *value; curl_off_t contentslength; char *contenttype; long flags; char *buffer; /* pointer to existing buffer used for file upload */ size_t bufferlength; char *showfilename; /* The file name to show. If not set, the actual file name will be used */ char *userp; /* pointer for the read callback */ struct curl_slist *contentheader; struct FormInfo *more; bool name_alloc; bool value_alloc; bool contenttype_alloc; bool showfilename_alloc; }; CURLcode Curl_getformdata(struct Curl_easy *data, curl_mimepart *, struct curl_httppost *post, curl_read_callback fread_func); #else /* disabled */ #define Curl_getformdata(a,b,c,d) CURLE_NOT_BUILT_IN #endif #endif /* HEADER_CURL_FORMDATA_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/hostsyn.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /*********************************************************************** * Only for builds using synchronous name resolves **********************************************************************/ #ifdef CURLRES_SYNCH #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "url.h" #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* * Function provided by the resolver backend to set DNS servers to use. */ CURLcode Curl_set_dns_servers(struct Curl_easy *data, char *servers) { (void)data; (void)servers; return CURLE_NOT_BUILT_IN; } /* * Function provided by the resolver backend to set * outgoing interface to use for DNS requests */ CURLcode Curl_set_dns_interface(struct Curl_easy *data, const char *interf) { (void)data; (void)interf; return CURLE_NOT_BUILT_IN; } /* * Function provided by the resolver backend to set * local IPv4 address to use as source address for DNS requests */ CURLcode Curl_set_dns_local_ip4(struct Curl_easy *data, const char *local_ip4) { (void)data; (void)local_ip4; return CURLE_NOT_BUILT_IN; } /* * Function provided by the resolver backend to set * local IPv6 address to use as source address for DNS requests */ CURLcode Curl_set_dns_local_ip6(struct Curl_easy *data, const char *local_ip6) { (void)data; (void)local_ip6; return CURLE_NOT_BUILT_IN; } #endif /* truly sync */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/select.h
#ifndef HEADER_CURL_SELECT_H #define HEADER_CURL_SELECT_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_POLL_H #include <poll.h> #elif defined(HAVE_SYS_POLL_H) #include <sys/poll.h> #endif /* * Definition of pollfd struct and constants for platforms lacking them. */ #if !defined(HAVE_STRUCT_POLLFD) && \ !defined(HAVE_SYS_POLL_H) && \ !defined(HAVE_POLL_H) && \ !defined(POLLIN) #define POLLIN 0x01 #define POLLPRI 0x02 #define POLLOUT 0x04 #define POLLERR 0x08 #define POLLHUP 0x10 #define POLLNVAL 0x20 struct pollfd { curl_socket_t fd; short events; short revents; }; #endif #ifndef POLLRDNORM #define POLLRDNORM POLLIN #endif #ifndef POLLWRNORM #define POLLWRNORM POLLOUT #endif #ifndef POLLRDBAND #define POLLRDBAND POLLPRI #endif /* there are three CSELECT defines that are defined in the public header that are exposed to users, but this *IN2 bit is only ever used internally and therefore defined here */ #define CURL_CSELECT_IN2 (CURL_CSELECT_ERR << 1) int Curl_socket_check(curl_socket_t readfd, curl_socket_t readfd2, curl_socket_t writefd, timediff_t timeout_ms); #define SOCKET_READABLE(x,z) \ Curl_socket_check(x, CURL_SOCKET_BAD, CURL_SOCKET_BAD, z) #define SOCKET_WRITABLE(x,z) \ Curl_socket_check(CURL_SOCKET_BAD, CURL_SOCKET_BAD, x, z) int Curl_poll(struct pollfd ufds[], unsigned int nfds, timediff_t timeout_ms); int Curl_wait_ms(timediff_t timeout_ms); #ifdef TPF int tpf_select_libcurl(int maxfds, fd_set* reads, fd_set* writes, fd_set* excepts, struct timeval *tv); #endif /* TPF sockets are not in range [0..FD_SETSIZE-1], which unfortunately makes it impossible for us to easily check if they're valid With Winsock the valid range is [0..INVALID_SOCKET-1] according to https://docs.microsoft.com/en-us/windows/win32/winsock/socket-data-type-2 */ #if defined(TPF) #define VALID_SOCK(x) 1 #define VERIFY_SOCK(x) Curl_nop_stmt #define FDSET_SOCK(x) 1 #elif defined(USE_WINSOCK) #define VALID_SOCK(s) ((s) < INVALID_SOCKET) #define FDSET_SOCK(x) 1 #define VERIFY_SOCK(x) do { \ if(!VALID_SOCK(x)) { \ SET_SOCKERRNO(WSAEINVAL); \ return -1; \ } \ } while(0) #else #define VALID_SOCK(s) ((s) >= 0) /* If the socket is small enough to get set or read from an fdset */ #define FDSET_SOCK(s) ((s) < FD_SETSIZE) #define VERIFY_SOCK(x) do { \ if(!VALID_SOCK(x) || !FDSET_SOCK(x)) { \ SET_SOCKERRNO(EINVAL); \ return -1; \ } \ } while(0) #endif #endif /* HEADER_CURL_SELECT_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/strdup.h
#ifndef HEADER_CURL_STRDUP_H #define HEADER_CURL_STRDUP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef HAVE_STRDUP extern char *curlx_strdup(const char *str); #endif #ifdef WIN32 wchar_t* Curl_wcsdup(const wchar_t* src); #endif void *Curl_memdup(const void *src, size_t buffer_length); void *Curl_saferealloc(void *ptr, size_t size); #endif /* HEADER_CURL_STRDUP_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/socks.h
#ifndef HEADER_CURL_SOCKS_H #define HEADER_CURL_SOCKS_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef CURL_DISABLE_PROXY #define Curl_SOCKS4(a,b,c,d,e) CURLE_NOT_BUILT_IN #define Curl_SOCKS5(a,b,c,d,e,f) CURLE_NOT_BUILT_IN #define Curl_SOCKS_getsock(x,y,z) 0 #else /* * Helper read-from-socket functions. Does the same as Curl_read() but it * blocks until all bytes amount of buffersize will be read. No more, no less. * * This is STUPID BLOCKING behavior */ int Curl_blockread_all(struct Curl_easy *data, curl_socket_t sockfd, char *buf, ssize_t buffersize, ssize_t *n); int Curl_SOCKS_getsock(struct connectdata *conn, curl_socket_t *sock, int sockindex); /* * This function logs in to a SOCKS4(a) proxy and sends the specifics to the * final destination server. */ CURLproxycode Curl_SOCKS4(const char *proxy_name, const char *hostname, int remote_port, int sockindex, struct Curl_easy *data, bool *done); /* * This function logs in to a SOCKS5 proxy and sends the specifics to the * final destination server. */ CURLproxycode Curl_SOCKS5(const char *proxy_name, const char *proxy_password, const char *hostname, int remote_port, int sockindex, struct Curl_easy *data, bool *done); #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI) /* * This function handles the SOCKS5 GSS-API negotiation and initialisation */ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex, struct Curl_easy *data); #endif #endif /* CURL_DISABLE_PROXY */ #endif /* HEADER_CURL_SOCKS_H */
0
repos/gpt4all.zig/src/zig-libcurl/curl
repos/gpt4all.zig/src/zig-libcurl/curl/lib/curl_rtmp.h
#ifndef HEADER_CURL_RTMP_H #define HEADER_CURL_RTMP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2010 - 2020, Howard Chu, <[email protected]> * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #ifdef USE_LIBRTMP extern const struct Curl_handler Curl_handler_rtmp; extern const struct Curl_handler Curl_handler_rtmpt; extern const struct Curl_handler Curl_handler_rtmpe; extern const struct Curl_handler Curl_handler_rtmpte; extern const struct Curl_handler Curl_handler_rtmps; extern const struct Curl_handler Curl_handler_rtmpts; #endif #endif /* HEADER_CURL_RTMP_H */