urlapi.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #include "urldata.h"
  26. #include "urlapi-int.h"
  27. #include "strcase.h"
  28. #include "url.h"
  29. #include "escape.h"
  30. #include "curl_ctype.h"
  31. #include "inet_pton.h"
  32. #include "inet_ntop.h"
  33. #include "strdup.h"
  34. /* The last 3 #include files should be in this order */
  35. #include "curl_printf.h"
  36. #include "curl_memory.h"
  37. #include "memdebug.h"
  38. /* MSDOS/Windows style drive prefix, eg c: in c:foo */
  39. #define STARTS_WITH_DRIVE_PREFIX(str) \
  40. ((('a' <= str[0] && str[0] <= 'z') || \
  41. ('A' <= str[0] && str[0] <= 'Z')) && \
  42. (str[1] == ':'))
  43. /* MSDOS/Windows style drive prefix, optionally with
  44. * a '|' instead of ':', followed by a slash or NUL */
  45. #define STARTS_WITH_URL_DRIVE_PREFIX(str) \
  46. ((('a' <= (str)[0] && (str)[0] <= 'z') || \
  47. ('A' <= (str)[0] && (str)[0] <= 'Z')) && \
  48. ((str)[1] == ':' || (str)[1] == '|') && \
  49. ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
  50. /* scheme is not URL encoded, the longest libcurl supported ones are... */
  51. #define MAX_SCHEME_LEN 40
  52. /* Internal representation of CURLU. Point to URL-encoded strings. */
  53. struct Curl_URL {
  54. char *scheme;
  55. char *user;
  56. char *password;
  57. char *options; /* IMAP only? */
  58. char *host;
  59. char *zoneid; /* for numerical IPv6 addresses */
  60. char *port;
  61. char *path;
  62. char *query;
  63. char *fragment;
  64. long portnum; /* the numerical version */
  65. };
  66. #define DEFAULT_SCHEME "https"
  67. static void free_urlhandle(struct Curl_URL *u)
  68. {
  69. free(u->scheme);
  70. free(u->user);
  71. free(u->password);
  72. free(u->options);
  73. free(u->host);
  74. free(u->zoneid);
  75. free(u->port);
  76. free(u->path);
  77. free(u->query);
  78. free(u->fragment);
  79. }
  80. /*
  81. * Find the separator at the end of the host name, or the '?' in cases like
  82. * http://www.url.com?id=2380
  83. */
  84. static const char *find_host_sep(const char *url)
  85. {
  86. const char *sep;
  87. const char *query;
  88. /* Find the start of the hostname */
  89. sep = strstr(url, "//");
  90. if(!sep)
  91. sep = url;
  92. else
  93. sep += 2;
  94. query = strchr(sep, '?');
  95. sep = strchr(sep, '/');
  96. if(!sep)
  97. sep = url + strlen(url);
  98. if(!query)
  99. query = url + strlen(url);
  100. return sep < query ? sep : query;
  101. }
  102. /*
  103. * Decide in an encoding-independent manner whether a character in a URL must
  104. * be escaped. This is used in urlencode_str().
  105. */
  106. static bool urlchar_needs_escaping(int c)
  107. {
  108. return !(ISCNTRL(c) || ISSPACE(c) || ISGRAPH(c));
  109. }
  110. /* urlencode_str() writes data into an output dynbuf and URL-encodes the
  111. * spaces in the source URL accordingly.
  112. *
  113. * URL encoding should be skipped for host names, otherwise IDN resolution
  114. * will fail.
  115. */
  116. static CURLUcode urlencode_str(struct dynbuf *o, const char *url,
  117. size_t len, bool relative,
  118. bool query)
  119. {
  120. /* we must add this with whitespace-replacing */
  121. bool left = !query;
  122. const unsigned char *iptr;
  123. const unsigned char *host_sep = (const unsigned char *) url;
  124. if(!relative)
  125. host_sep = (const unsigned char *) find_host_sep(url);
  126. for(iptr = (unsigned char *)url; /* read from here */
  127. len; iptr++, len--) {
  128. if(iptr < host_sep) {
  129. if(Curl_dyn_addn(o, iptr, 1))
  130. return CURLUE_OUT_OF_MEMORY;
  131. continue;
  132. }
  133. if(*iptr == ' ') {
  134. if(left) {
  135. if(Curl_dyn_addn(o, "%20", 3))
  136. return CURLUE_OUT_OF_MEMORY;
  137. }
  138. else {
  139. if(Curl_dyn_addn(o, "+", 1))
  140. return CURLUE_OUT_OF_MEMORY;
  141. }
  142. continue;
  143. }
  144. if(*iptr == '?')
  145. left = FALSE;
  146. if(urlchar_needs_escaping(*iptr)) {
  147. if(Curl_dyn_addf(o, "%%%02x", *iptr))
  148. return CURLUE_OUT_OF_MEMORY;
  149. }
  150. else {
  151. if(Curl_dyn_addn(o, iptr, 1))
  152. return CURLUE_OUT_OF_MEMORY;
  153. }
  154. }
  155. return CURLUE_OK;
  156. }
  157. /*
  158. * Returns the length of the scheme if the given URL is absolute (as opposed
  159. * to relative). Stores the scheme in the buffer if TRUE and 'buf' is
  160. * non-NULL. The buflen must be larger than MAX_SCHEME_LEN if buf is set.
  161. *
  162. * If 'guess_scheme' is TRUE, it means the URL might be provided without
  163. * scheme.
  164. */
  165. size_t Curl_is_absolute_url(const char *url, char *buf, size_t buflen,
  166. bool guess_scheme)
  167. {
  168. int i;
  169. DEBUGASSERT(!buf || (buflen > MAX_SCHEME_LEN));
  170. (void)buflen; /* only used in debug-builds */
  171. if(buf)
  172. buf[0] = 0; /* always leave a defined value in buf */
  173. #ifdef WIN32
  174. if(guess_scheme && STARTS_WITH_DRIVE_PREFIX(url))
  175. return 0;
  176. #endif
  177. for(i = 0; i < MAX_SCHEME_LEN; ++i) {
  178. char s = url[i];
  179. if(s && (ISALNUM(s) || (s == '+') || (s == '-') || (s == '.') )) {
  180. /* RFC 3986 3.1 explains:
  181. scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  182. */
  183. }
  184. else {
  185. break;
  186. }
  187. }
  188. if(i && (url[i] == ':') && ((url[i + 1] == '/') || !guess_scheme)) {
  189. /* If this does not guess scheme, the scheme always ends with the colon so
  190. that this also detects data: URLs etc. In guessing mode, data: could
  191. be the host name "data" with a specified port number. */
  192. /* the length of the scheme is the name part only */
  193. size_t len = i;
  194. if(buf) {
  195. buf[i] = 0;
  196. while(i--) {
  197. buf[i] = Curl_raw_tolower(url[i]);
  198. }
  199. }
  200. return len;
  201. }
  202. return 0;
  203. }
  204. /*
  205. * Concatenate a relative URL to a base URL making it absolute.
  206. * URL-encodes any spaces.
  207. * The returned pointer must be freed by the caller unless NULL
  208. * (returns NULL on out of memory).
  209. *
  210. * Note that this function destroys the 'base' string.
  211. */
  212. static char *concat_url(char *base, const char *relurl)
  213. {
  214. /***
  215. TRY to append this new path to the old URL
  216. to the right of the host part. Oh crap, this is doomed to cause
  217. problems in the future...
  218. */
  219. struct dynbuf newest;
  220. char *protsep;
  221. char *pathsep;
  222. bool host_changed = FALSE;
  223. const char *useurl = relurl;
  224. /* protsep points to the start of the host name */
  225. protsep = strstr(base, "//");
  226. if(!protsep)
  227. protsep = base;
  228. else
  229. protsep += 2; /* pass the slashes */
  230. if('/' != relurl[0]) {
  231. int level = 0;
  232. /* First we need to find out if there's a ?-letter in the URL,
  233. and cut it and the right-side of that off */
  234. pathsep = strchr(protsep, '?');
  235. if(pathsep)
  236. *pathsep = 0;
  237. /* we have a relative path to append to the last slash if there's one
  238. available, or if the new URL is just a query string (starts with a
  239. '?') we append the new one at the end of the entire currently worked
  240. out URL */
  241. if(useurl[0] != '?') {
  242. pathsep = strrchr(protsep, '/');
  243. if(pathsep)
  244. *pathsep = 0;
  245. }
  246. /* Check if there's any slash after the host name, and if so, remember
  247. that position instead */
  248. pathsep = strchr(protsep, '/');
  249. if(pathsep)
  250. protsep = pathsep + 1;
  251. else
  252. protsep = NULL;
  253. /* now deal with one "./" or any amount of "../" in the newurl
  254. and act accordingly */
  255. if((useurl[0] == '.') && (useurl[1] == '/'))
  256. useurl += 2; /* just skip the "./" */
  257. while((useurl[0] == '.') &&
  258. (useurl[1] == '.') &&
  259. (useurl[2] == '/')) {
  260. level++;
  261. useurl += 3; /* pass the "../" */
  262. }
  263. if(protsep) {
  264. while(level--) {
  265. /* cut off one more level from the right of the original URL */
  266. pathsep = strrchr(protsep, '/');
  267. if(pathsep)
  268. *pathsep = 0;
  269. else {
  270. *protsep = 0;
  271. break;
  272. }
  273. }
  274. }
  275. }
  276. else {
  277. /* We got a new absolute path for this server */
  278. if(relurl[1] == '/') {
  279. /* the new URL starts with //, just keep the protocol part from the
  280. original one */
  281. *protsep = 0;
  282. useurl = &relurl[2]; /* we keep the slashes from the original, so we
  283. skip the new ones */
  284. host_changed = TRUE;
  285. }
  286. else {
  287. /* cut off the original URL from the first slash, or deal with URLs
  288. without slash */
  289. pathsep = strchr(protsep, '/');
  290. if(pathsep) {
  291. /* When people use badly formatted URLs, such as
  292. "http://www.url.com?dir=/home/daniel" we must not use the first
  293. slash, if there's a ?-letter before it! */
  294. char *sep = strchr(protsep, '?');
  295. if(sep && (sep < pathsep))
  296. pathsep = sep;
  297. *pathsep = 0;
  298. }
  299. else {
  300. /* There was no slash. Now, since we might be operating on a badly
  301. formatted URL, such as "http://www.url.com?id=2380" which doesn't
  302. use a slash separator as it is supposed to, we need to check for a
  303. ?-letter as well! */
  304. pathsep = strchr(protsep, '?');
  305. if(pathsep)
  306. *pathsep = 0;
  307. }
  308. }
  309. }
  310. Curl_dyn_init(&newest, CURL_MAX_INPUT_LENGTH);
  311. /* copy over the root url part */
  312. if(Curl_dyn_add(&newest, base))
  313. return NULL;
  314. /* check if we need to append a slash */
  315. if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
  316. ;
  317. else {
  318. if(Curl_dyn_addn(&newest, "/", 1))
  319. return NULL;
  320. }
  321. /* then append the new piece on the right side */
  322. urlencode_str(&newest, useurl, strlen(useurl), !host_changed, FALSE);
  323. return Curl_dyn_ptr(&newest);
  324. }
  325. /* scan for byte values < 31 or 127 */
  326. static bool junkscan(const char *part, unsigned int flags)
  327. {
  328. if(part) {
  329. static const char badbytes[]={
  330. /* */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  331. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  332. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  333. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  334. 0x7f, 0x00 /* null-terminate */
  335. };
  336. size_t n = strlen(part);
  337. size_t nfine = strcspn(part, badbytes);
  338. if(nfine != n)
  339. /* since we don't know which part is scanned, return a generic error
  340. code */
  341. return TRUE;
  342. if(!(flags & CURLU_ALLOW_SPACE) && strchr(part, ' '))
  343. return TRUE;
  344. }
  345. return FALSE;
  346. }
  347. /*
  348. * parse_hostname_login()
  349. *
  350. * Parse the login details (user name, password and options) from the URL and
  351. * strip them out of the host name
  352. *
  353. */
  354. static CURLUcode parse_hostname_login(struct Curl_URL *u,
  355. struct dynbuf *host,
  356. unsigned int flags)
  357. {
  358. CURLUcode result = CURLUE_OK;
  359. CURLcode ccode;
  360. char *userp = NULL;
  361. char *passwdp = NULL;
  362. char *optionsp = NULL;
  363. const struct Curl_handler *h = NULL;
  364. /* At this point, we assume all the other special cases have been taken
  365. * care of, so the host is at most
  366. *
  367. * [user[:password][;options]]@]hostname
  368. *
  369. * We need somewhere to put the embedded details, so do that first.
  370. */
  371. char *login = Curl_dyn_ptr(host);
  372. char *ptr;
  373. DEBUGASSERT(login);
  374. ptr = strchr(login, '@');
  375. if(!ptr)
  376. goto out;
  377. /* We will now try to extract the
  378. * possible login information in a string like:
  379. * ftp://user:password@ftp.my.site:8021/README */
  380. ptr++;
  381. /* if this is a known scheme, get some details */
  382. if(u->scheme)
  383. h = Curl_builtin_scheme(u->scheme, CURL_ZERO_TERMINATED);
  384. /* We could use the login information in the URL so extract it. Only parse
  385. options if the handler says we should. Note that 'h' might be NULL! */
  386. ccode = Curl_parse_login_details(login, ptr - login - 1,
  387. &userp, &passwdp,
  388. (h && (h->flags & PROTOPT_URLOPTIONS)) ?
  389. &optionsp:NULL);
  390. if(ccode) {
  391. result = CURLUE_BAD_LOGIN;
  392. goto out;
  393. }
  394. if(userp) {
  395. if(flags & CURLU_DISALLOW_USER) {
  396. /* Option DISALLOW_USER is set and url contains username. */
  397. result = CURLUE_USER_NOT_ALLOWED;
  398. goto out;
  399. }
  400. if(junkscan(userp, flags)) {
  401. result = CURLUE_BAD_USER;
  402. goto out;
  403. }
  404. u->user = userp;
  405. }
  406. if(passwdp) {
  407. if(junkscan(passwdp, flags)) {
  408. result = CURLUE_BAD_PASSWORD;
  409. goto out;
  410. }
  411. u->password = passwdp;
  412. }
  413. if(optionsp) {
  414. if(junkscan(optionsp, flags)) {
  415. result = CURLUE_BAD_LOGIN;
  416. goto out;
  417. }
  418. u->options = optionsp;
  419. }
  420. /* move the name to the start of the host buffer */
  421. if(Curl_dyn_tail(host, strlen(ptr)))
  422. return CURLUE_OUT_OF_MEMORY;
  423. return CURLUE_OK;
  424. out:
  425. free(userp);
  426. free(passwdp);
  427. free(optionsp);
  428. u->user = NULL;
  429. u->password = NULL;
  430. u->options = NULL;
  431. return result;
  432. }
  433. UNITTEST CURLUcode Curl_parse_port(struct Curl_URL *u, struct dynbuf *host,
  434. bool has_scheme)
  435. {
  436. char *portptr = NULL;
  437. char endbracket;
  438. int len;
  439. char *hostname = Curl_dyn_ptr(host);
  440. /*
  441. * Find the end of an IPv6 address, either on the ']' ending bracket or
  442. * a percent-encoded zone index.
  443. */
  444. if(1 == sscanf(hostname, "[%*45[0123456789abcdefABCDEF:.]%c%n",
  445. &endbracket, &len)) {
  446. if(']' == endbracket)
  447. portptr = &hostname[len];
  448. else if('%' == endbracket) {
  449. int zonelen = len;
  450. if(1 == sscanf(hostname + zonelen, "%*[^]]%c%n", &endbracket, &len)) {
  451. if(']' != endbracket)
  452. return CURLUE_BAD_IPV6;
  453. portptr = &hostname[--zonelen + len + 1];
  454. }
  455. else
  456. return CURLUE_BAD_IPV6;
  457. }
  458. else
  459. return CURLUE_BAD_IPV6;
  460. /* this is a RFC2732-style specified IP-address */
  461. if(portptr && *portptr) {
  462. if(*portptr != ':')
  463. return CURLUE_BAD_IPV6;
  464. }
  465. else
  466. portptr = NULL;
  467. }
  468. else
  469. portptr = strchr(hostname, ':');
  470. if(portptr) {
  471. char *rest;
  472. long port;
  473. char portbuf[7];
  474. size_t keep = portptr - hostname;
  475. /* Browser behavior adaptation. If there's a colon with no digits after,
  476. just cut off the name there which makes us ignore the colon and just
  477. use the default port. Firefox, Chrome and Safari all do that.
  478. Don't do it if the URL has no scheme, to make something that looks like
  479. a scheme not work!
  480. */
  481. Curl_dyn_setlen(host, keep);
  482. portptr++;
  483. if(!*portptr)
  484. return has_scheme ? CURLUE_OK : CURLUE_BAD_PORT_NUMBER;
  485. if(!ISDIGIT(*portptr))
  486. return CURLUE_BAD_PORT_NUMBER;
  487. port = strtol(portptr, &rest, 10); /* Port number must be decimal */
  488. if(port > 0xffff)
  489. return CURLUE_BAD_PORT_NUMBER;
  490. if(rest[0])
  491. return CURLUE_BAD_PORT_NUMBER;
  492. *rest = 0;
  493. /* generate a new port number string to get rid of leading zeroes etc */
  494. msnprintf(portbuf, sizeof(portbuf), "%ld", port);
  495. u->portnum = port;
  496. u->port = strdup(portbuf);
  497. if(!u->port)
  498. return CURLUE_OUT_OF_MEMORY;
  499. }
  500. return CURLUE_OK;
  501. }
  502. static CURLUcode hostname_check(struct Curl_URL *u, char *hostname,
  503. size_t hlen) /* length of hostname */
  504. {
  505. size_t len;
  506. DEBUGASSERT(hostname);
  507. if(!hostname[0])
  508. return CURLUE_NO_HOST;
  509. else if(hostname[0] == '[') {
  510. const char *l = "0123456789abcdefABCDEF:.";
  511. if(hlen < 4) /* '[::]' is the shortest possible valid string */
  512. return CURLUE_BAD_IPV6;
  513. hostname++;
  514. hlen -= 2;
  515. if(hostname[hlen] != ']')
  516. return CURLUE_BAD_IPV6;
  517. /* only valid letters are ok */
  518. len = strspn(hostname, l);
  519. if(hlen != len) {
  520. hlen = len;
  521. if(hostname[len] == '%') {
  522. /* this could now be '%[zone id]' */
  523. char zoneid[16];
  524. int i = 0;
  525. char *h = &hostname[len + 1];
  526. /* pass '25' if present and is a url encoded percent sign */
  527. if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']'))
  528. h += 2;
  529. while(*h && (*h != ']') && (i < 15))
  530. zoneid[i++] = *h++;
  531. if(!i || (']' != *h))
  532. /* impossible to reach? */
  533. return CURLUE_MALFORMED_INPUT;
  534. zoneid[i] = 0;
  535. u->zoneid = strdup(zoneid);
  536. if(!u->zoneid)
  537. return CURLUE_OUT_OF_MEMORY;
  538. hostname[len] = ']'; /* insert end bracket */
  539. hostname[len + 1] = 0; /* terminate the hostname */
  540. }
  541. else
  542. return CURLUE_BAD_IPV6;
  543. /* hostname is fine */
  544. }
  545. #ifdef ENABLE_IPV6
  546. {
  547. char dest[16]; /* fits a binary IPv6 address */
  548. char norm[MAX_IPADR_LEN];
  549. hostname[hlen] = 0; /* end the address there */
  550. if(1 != Curl_inet_pton(AF_INET6, hostname, dest))
  551. return CURLUE_BAD_IPV6;
  552. /* check if it can be done shorter */
  553. if(Curl_inet_ntop(AF_INET6, dest, norm, sizeof(norm)) &&
  554. (strlen(norm) < hlen)) {
  555. strcpy(hostname, norm);
  556. hlen = strlen(norm);
  557. hostname[hlen + 1] = 0;
  558. }
  559. hostname[hlen] = ']'; /* restore ending bracket */
  560. }
  561. #endif
  562. }
  563. else {
  564. /* letters from the second string are not ok */
  565. len = strcspn(hostname, " \r\n\t/:#?!@{}[]\\$\'\"^`*<>=;,");
  566. if(hlen != len)
  567. /* hostname with bad content */
  568. return CURLUE_BAD_HOSTNAME;
  569. }
  570. return CURLUE_OK;
  571. }
  572. #define HOSTNAME_END(x) (((x) == '/') || ((x) == '?') || ((x) == '#'))
  573. /*
  574. * Handle partial IPv4 numerical addresses and different bases, like
  575. * '16843009', '0x7f', '0x7f.1' '0177.1.1.1' etc.
  576. *
  577. * If the given input string is syntactically wrong or any part for example is
  578. * too big, this function returns FALSE and doesn't create any output.
  579. *
  580. * Output the "normalized" version of that input string in plain quad decimal
  581. * integers and return TRUE.
  582. */
  583. static bool ipv4_normalize(const char *hostname, char *outp, size_t olen)
  584. {
  585. bool done = FALSE;
  586. int n = 0;
  587. const char *c = hostname;
  588. unsigned long parts[4] = {0, 0, 0, 0};
  589. while(!done) {
  590. char *endp;
  591. unsigned long l;
  592. if((*c < '0') || (*c > '9'))
  593. /* most importantly this doesn't allow a leading plus or minus */
  594. return FALSE;
  595. l = strtoul(c, &endp, 0);
  596. /* overflow or nothing parsed at all */
  597. if(((l == ULONG_MAX) && (errno == ERANGE)) || (endp == c))
  598. return FALSE;
  599. #if SIZEOF_LONG > 4
  600. /* a value larger than 32 bits */
  601. if(l > UINT_MAX)
  602. return FALSE;
  603. #endif
  604. parts[n] = l;
  605. c = endp;
  606. switch (*c) {
  607. case '.' :
  608. if(n == 3)
  609. return FALSE;
  610. n++;
  611. c++;
  612. break;
  613. case '\0':
  614. done = TRUE;
  615. break;
  616. default:
  617. return FALSE;
  618. }
  619. }
  620. /* this is deemed a valid IPv4 numerical address */
  621. switch(n) {
  622. case 0: /* a -- 32 bits */
  623. msnprintf(outp, olen, "%u.%u.%u.%u",
  624. parts[0] >> 24, (parts[0] >> 16) & 0xff,
  625. (parts[0] >> 8) & 0xff, parts[0] & 0xff);
  626. break;
  627. case 1: /* a.b -- 8.24 bits */
  628. if((parts[0] > 0xff) || (parts[1] > 0xffffff))
  629. return FALSE;
  630. msnprintf(outp, olen, "%u.%u.%u.%u",
  631. parts[0], (parts[1] >> 16) & 0xff,
  632. (parts[1] >> 8) & 0xff, parts[1] & 0xff);
  633. break;
  634. case 2: /* a.b.c -- 8.8.16 bits */
  635. if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff))
  636. return FALSE;
  637. msnprintf(outp, olen, "%u.%u.%u.%u",
  638. parts[0], parts[1], (parts[2] >> 8) & 0xff,
  639. parts[2] & 0xff);
  640. break;
  641. case 3: /* a.b.c.d -- 8.8.8.8 bits */
  642. if((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) ||
  643. (parts[3] > 0xff))
  644. return FALSE;
  645. msnprintf(outp, olen, "%u.%u.%u.%u",
  646. parts[0], parts[1], parts[2], parts[3]);
  647. break;
  648. }
  649. return TRUE;
  650. }
  651. /* if necessary, replace the host content with a URL decoded version */
  652. static CURLUcode decode_host(struct dynbuf *host)
  653. {
  654. char *per = NULL;
  655. const char *hostname = Curl_dyn_ptr(host);
  656. if(hostname[0] == '[')
  657. /* only decode if not an ipv6 numerical */
  658. return CURLUE_OK;
  659. per = strchr(hostname, '%');
  660. if(!per)
  661. /* nothing to decode */
  662. return CURLUE_OK;
  663. else {
  664. /* encoded */
  665. size_t dlen;
  666. char *decoded;
  667. CURLcode result = Curl_urldecode(hostname, 0, &decoded, &dlen,
  668. REJECT_CTRL);
  669. if(result)
  670. return CURLUE_BAD_HOSTNAME;
  671. Curl_dyn_reset(host);
  672. result = Curl_dyn_addn(host, decoded, dlen);
  673. free(decoded);
  674. if(result)
  675. return CURLUE_OUT_OF_MEMORY;
  676. }
  677. return CURLUE_OK;
  678. }
  679. /*
  680. * "Remove Dot Segments"
  681. * https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
  682. */
  683. /*
  684. * dedotdotify()
  685. * @unittest: 1395
  686. *
  687. * This function gets a null-terminated path with dot and dotdot sequences
  688. * passed in and strips them off according to the rules in RFC 3986 section
  689. * 5.2.4.
  690. *
  691. * The function handles a query part ('?' + stuff) appended but it expects
  692. * that fragments ('#' + stuff) have already been cut off.
  693. *
  694. * RETURNS
  695. *
  696. * an allocated dedotdotified output string
  697. */
  698. UNITTEST char *dedotdotify(const char *input, size_t clen);
  699. UNITTEST char *dedotdotify(const char *input, size_t clen)
  700. {
  701. char *out = malloc(clen + 1);
  702. char *outptr;
  703. const char *orginput = input;
  704. char *queryp;
  705. if(!out)
  706. return NULL; /* out of memory */
  707. *out = 0; /* null-terminates, for inputs like "./" */
  708. outptr = out;
  709. if(!*input)
  710. /* zero length input string, return that */
  711. return out;
  712. /*
  713. * To handle query-parts properly, we must find it and remove it during the
  714. * dotdot-operation and then append it again at the end to the output
  715. * string.
  716. */
  717. queryp = strchr(input, '?');
  718. do {
  719. bool dotdot = TRUE;
  720. if(*input == '.') {
  721. /* A. If the input buffer begins with a prefix of "../" or "./", then
  722. remove that prefix from the input buffer; otherwise, */
  723. if(!strncmp("./", input, 2)) {
  724. input += 2;
  725. clen -= 2;
  726. }
  727. else if(!strncmp("../", input, 3)) {
  728. input += 3;
  729. clen -= 3;
  730. }
  731. /* D. if the input buffer consists only of "." or "..", then remove
  732. that from the input buffer; otherwise, */
  733. else if(!strcmp(".", input) || !strcmp("..", input) ||
  734. !strncmp(".?", input, 2) || !strncmp("..?", input, 3)) {
  735. *out = 0;
  736. break;
  737. }
  738. else
  739. dotdot = FALSE;
  740. }
  741. else if(*input == '/') {
  742. /* B. if the input buffer begins with a prefix of "/./" or "/.", where
  743. "." is a complete path segment, then replace that prefix with "/" in
  744. the input buffer; otherwise, */
  745. if(!strncmp("/./", input, 3)) {
  746. input += 2;
  747. clen -= 2;
  748. }
  749. else if(!strcmp("/.", input) || !strncmp("/.?", input, 3)) {
  750. *outptr++ = '/';
  751. *outptr = 0;
  752. break;
  753. }
  754. /* C. if the input buffer begins with a prefix of "/../" or "/..",
  755. where ".." is a complete path segment, then replace that prefix with
  756. "/" in the input buffer and remove the last segment and its
  757. preceding "/" (if any) from the output buffer; otherwise, */
  758. else if(!strncmp("/../", input, 4)) {
  759. input += 3;
  760. clen -= 3;
  761. /* remove the last segment from the output buffer */
  762. while(outptr > out) {
  763. outptr--;
  764. if(*outptr == '/')
  765. break;
  766. }
  767. *outptr = 0; /* null-terminate where it stops */
  768. }
  769. else if(!strcmp("/..", input) || !strncmp("/..?", input, 4)) {
  770. /* remove the last segment from the output buffer */
  771. while(outptr > out) {
  772. outptr--;
  773. if(*outptr == '/')
  774. break;
  775. }
  776. *outptr++ = '/';
  777. *outptr = 0; /* null-terminate where it stops */
  778. break;
  779. }
  780. else
  781. dotdot = FALSE;
  782. }
  783. else
  784. dotdot = FALSE;
  785. if(!dotdot) {
  786. /* E. move the first path segment in the input buffer to the end of
  787. the output buffer, including the initial "/" character (if any) and
  788. any subsequent characters up to, but not including, the next "/"
  789. character or the end of the input buffer. */
  790. do {
  791. *outptr++ = *input++;
  792. clen--;
  793. } while(*input && (*input != '/') && (*input != '?'));
  794. *outptr = 0;
  795. }
  796. /* continue until end of input string OR, if there is a terminating
  797. query part, stop there */
  798. } while(*input && (!queryp || (input < queryp)));
  799. if(queryp) {
  800. size_t qlen;
  801. /* There was a query part, append that to the output. */
  802. size_t oindex = queryp - orginput;
  803. qlen = strlen(&orginput[oindex]);
  804. memcpy(outptr, &orginput[oindex], qlen + 1); /* include zero byte */
  805. }
  806. return out;
  807. }
  808. static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
  809. {
  810. const char *path;
  811. size_t pathlen;
  812. bool uncpath = FALSE;
  813. char *query = NULL;
  814. char *fragment = NULL;
  815. char schemebuf[MAX_SCHEME_LEN + 1];
  816. const char *schemep = NULL;
  817. size_t schemelen = 0;
  818. size_t urllen;
  819. CURLUcode result = CURLUE_OK;
  820. size_t fraglen = 0;
  821. struct dynbuf host;
  822. DEBUGASSERT(url);
  823. Curl_dyn_init(&host, CURL_MAX_INPUT_LENGTH);
  824. /*************************************************************
  825. * Parse the URL.
  826. ************************************************************/
  827. /* allocate scratch area */
  828. urllen = strlen(url);
  829. if(urllen > CURL_MAX_INPUT_LENGTH) {
  830. /* excessive input length */
  831. result = CURLUE_MALFORMED_INPUT;
  832. goto fail;
  833. }
  834. schemelen = Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf),
  835. flags & (CURLU_GUESS_SCHEME|
  836. CURLU_DEFAULT_SCHEME));
  837. /* handle the file: scheme */
  838. if(schemelen && !strcmp(schemebuf, "file")) {
  839. if(urllen <= 6) {
  840. /* file:/ is not enough to actually be a complete file: URL */
  841. result = CURLUE_BAD_FILE_URL;
  842. goto fail;
  843. }
  844. /* path has been allocated large enough to hold this */
  845. path = (char *)&url[5];
  846. schemep = u->scheme = strdup("file");
  847. if(!u->scheme) {
  848. result = CURLUE_OUT_OF_MEMORY;
  849. goto fail;
  850. }
  851. /* Extra handling URLs with an authority component (i.e. that start with
  852. * "file://")
  853. *
  854. * We allow omitted hostname (e.g. file:/<path>) -- valid according to
  855. * RFC 8089, but not the (current) WHAT-WG URL spec.
  856. */
  857. if(path[0] == '/' && path[1] == '/') {
  858. /* swallow the two slashes */
  859. const char *ptr = &path[2];
  860. /*
  861. * According to RFC 8089, a file: URL can be reliably dereferenced if:
  862. *
  863. * o it has no/blank hostname, or
  864. *
  865. * o the hostname matches "localhost" (case-insensitively), or
  866. *
  867. * o the hostname is a FQDN that resolves to this machine, or
  868. *
  869. * o it is an UNC String transformed to an URI (Windows only, RFC 8089
  870. * Appendix E.3).
  871. *
  872. * For brevity, we only consider URLs with empty, "localhost", or
  873. * "127.0.0.1" hostnames as local, otherwise as an UNC String.
  874. *
  875. * Additionally, there is an exception for URLs with a Windows drive
  876. * letter in the authority (which was accidentally omitted from RFC 8089
  877. * Appendix E, but believe me, it was meant to be there. --MK)
  878. */
  879. if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
  880. /* the URL includes a host name, it must match "localhost" or
  881. "127.0.0.1" to be valid */
  882. if(checkprefix("localhost/", ptr) ||
  883. checkprefix("127.0.0.1/", ptr)) {
  884. ptr += 9; /* now points to the slash after the host */
  885. }
  886. else {
  887. #if defined(WIN32)
  888. size_t len;
  889. /* the host name, NetBIOS computer name, can not contain disallowed
  890. chars, and the delimiting slash character must be appended to the
  891. host name */
  892. path = strpbrk(ptr, "/\\:*?\"<>|");
  893. if(!path || *path != '/') {
  894. result = CURLUE_BAD_FILE_URL;
  895. goto fail;
  896. }
  897. len = path - ptr;
  898. if(len) {
  899. if(Curl_dyn_addn(&host, ptr, len)) {
  900. result = CURLUE_OUT_OF_MEMORY;
  901. goto fail;
  902. }
  903. uncpath = TRUE;
  904. }
  905. ptr -= 2; /* now points to the // before the host in UNC */
  906. #else
  907. /* Invalid file://hostname/, expected localhost or 127.0.0.1 or
  908. none */
  909. result = CURLUE_BAD_FILE_URL;
  910. goto fail;
  911. #endif
  912. }
  913. }
  914. path = ptr;
  915. }
  916. if(!uncpath)
  917. /* no host for file: URLs by default */
  918. Curl_dyn_reset(&host);
  919. #if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__)
  920. /* Don't allow Windows drive letters when not in Windows.
  921. * This catches both "file:/c:" and "file:c:" */
  922. if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
  923. STARTS_WITH_URL_DRIVE_PREFIX(path)) {
  924. /* File drive letters are only accepted in MSDOS/Windows */
  925. result = CURLUE_BAD_FILE_URL;
  926. goto fail;
  927. }
  928. #else
  929. /* If the path starts with a slash and a drive letter, ditch the slash */
  930. if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) {
  931. /* This cannot be done with strcpy, as the memory chunks overlap! */
  932. path++;
  933. }
  934. #endif
  935. }
  936. else {
  937. /* clear path */
  938. const char *p;
  939. const char *hostp;
  940. size_t len;
  941. if(schemelen) {
  942. int i = 0;
  943. p = &url[schemelen + 1];
  944. while(p && (*p == '/') && (i < 4)) {
  945. p++;
  946. i++;
  947. }
  948. schemep = schemebuf;
  949. if(!Curl_builtin_scheme(schemep, CURL_ZERO_TERMINATED) &&
  950. !(flags & CURLU_NON_SUPPORT_SCHEME)) {
  951. result = CURLUE_UNSUPPORTED_SCHEME;
  952. goto fail;
  953. }
  954. if((i < 1) || (i>3)) {
  955. /* less than one or more than three slashes */
  956. result = CURLUE_BAD_SLASHES;
  957. goto fail;
  958. }
  959. if(junkscan(schemep, flags)) {
  960. result = CURLUE_BAD_SCHEME;
  961. goto fail;
  962. }
  963. }
  964. else {
  965. /* no scheme! */
  966. if(!(flags & (CURLU_DEFAULT_SCHEME|CURLU_GUESS_SCHEME))) {
  967. result = CURLUE_BAD_SCHEME;
  968. goto fail;
  969. }
  970. if(flags & CURLU_DEFAULT_SCHEME)
  971. schemep = DEFAULT_SCHEME;
  972. /*
  973. * The URL was badly formatted, let's try without scheme specified.
  974. */
  975. p = url;
  976. }
  977. hostp = p; /* host name starts here */
  978. /* find the end of the host name + port number */
  979. while(*p && !HOSTNAME_END(*p))
  980. p++;
  981. len = p - hostp;
  982. if(len) {
  983. if(Curl_dyn_addn(&host, hostp, len)) {
  984. result = CURLUE_OUT_OF_MEMORY;
  985. goto fail;
  986. }
  987. }
  988. else {
  989. if(!(flags & CURLU_NO_AUTHORITY)) {
  990. result = CURLUE_NO_HOST;
  991. goto fail;
  992. }
  993. }
  994. path = (char *)p;
  995. if(schemep) {
  996. u->scheme = strdup(schemep);
  997. if(!u->scheme) {
  998. result = CURLUE_OUT_OF_MEMORY;
  999. goto fail;
  1000. }
  1001. }
  1002. }
  1003. fragment = strchr(path, '#');
  1004. if(fragment) {
  1005. fraglen = strlen(fragment);
  1006. if(fraglen > 1) {
  1007. /* skip the leading '#' in the copy but include the terminating null */
  1008. u->fragment = Curl_memdup(fragment + 1, fraglen);
  1009. if(!u->fragment) {
  1010. result = CURLUE_OUT_OF_MEMORY;
  1011. goto fail;
  1012. }
  1013. if(junkscan(u->fragment, flags)) {
  1014. result = CURLUE_BAD_FRAGMENT;
  1015. goto fail;
  1016. }
  1017. }
  1018. }
  1019. query = strchr(path, '?');
  1020. if(query && (!fragment || (query < fragment))) {
  1021. size_t qlen = strlen(query) - fraglen; /* includes '?' */
  1022. pathlen = strlen(path) - qlen - fraglen;
  1023. if(qlen > 1) {
  1024. if(qlen && (flags & CURLU_URLENCODE)) {
  1025. struct dynbuf enc;
  1026. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1027. /* skip the leading question mark */
  1028. if(urlencode_str(&enc, query + 1, qlen - 1, TRUE, TRUE)) {
  1029. result = CURLUE_OUT_OF_MEMORY;
  1030. goto fail;
  1031. }
  1032. u->query = Curl_dyn_ptr(&enc);
  1033. }
  1034. else {
  1035. u->query = Curl_memdup(query + 1, qlen);
  1036. if(!u->query) {
  1037. result = CURLUE_OUT_OF_MEMORY;
  1038. goto fail;
  1039. }
  1040. u->query[qlen - 1] = 0;
  1041. }
  1042. if(junkscan(u->query, flags)) {
  1043. result = CURLUE_BAD_QUERY;
  1044. goto fail;
  1045. }
  1046. }
  1047. else {
  1048. /* single byte query */
  1049. u->query = strdup("");
  1050. if(!u->query) {
  1051. result = CURLUE_OUT_OF_MEMORY;
  1052. goto fail;
  1053. }
  1054. }
  1055. }
  1056. else
  1057. pathlen = strlen(path) - fraglen;
  1058. if(pathlen && (flags & CURLU_URLENCODE)) {
  1059. struct dynbuf enc;
  1060. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1061. if(urlencode_str(&enc, path, pathlen, TRUE, FALSE)) {
  1062. result = CURLUE_OUT_OF_MEMORY;
  1063. goto fail;
  1064. }
  1065. pathlen = Curl_dyn_len(&enc);
  1066. path = u->path = Curl_dyn_ptr(&enc);
  1067. }
  1068. if(!pathlen) {
  1069. /* there is no path left, unset */
  1070. path = NULL;
  1071. }
  1072. else {
  1073. if(!u->path) {
  1074. u->path = Curl_memdup(path, pathlen + 1);
  1075. if(!u->path) {
  1076. result = CURLUE_OUT_OF_MEMORY;
  1077. goto fail;
  1078. }
  1079. u->path[pathlen] = 0;
  1080. path = u->path;
  1081. }
  1082. else if(flags & CURLU_URLENCODE)
  1083. /* it might have encoded more than just the path so cut it */
  1084. u->path[pathlen] = 0;
  1085. if(junkscan(u->path, flags)) {
  1086. result = CURLUE_BAD_PATH;
  1087. goto fail;
  1088. }
  1089. if(!(flags & CURLU_PATH_AS_IS)) {
  1090. /* remove ../ and ./ sequences according to RFC3986 */
  1091. char *newp = dedotdotify((char *)path, pathlen);
  1092. if(!newp) {
  1093. result = CURLUE_OUT_OF_MEMORY;
  1094. goto fail;
  1095. }
  1096. free(u->path);
  1097. u->path = newp;
  1098. }
  1099. }
  1100. if(Curl_dyn_len(&host)) {
  1101. char normalized_ipv4[sizeof("255.255.255.255") + 1];
  1102. /*
  1103. * Parse the login details and strip them out of the host name.
  1104. */
  1105. result = parse_hostname_login(u, &host, flags);
  1106. if(!result)
  1107. result = Curl_parse_port(u, &host, schemelen);
  1108. if(result)
  1109. goto fail;
  1110. if(junkscan(Curl_dyn_ptr(&host), flags)) {
  1111. result = CURLUE_BAD_HOSTNAME;
  1112. goto fail;
  1113. }
  1114. if(ipv4_normalize(Curl_dyn_ptr(&host),
  1115. normalized_ipv4, sizeof(normalized_ipv4))) {
  1116. Curl_dyn_reset(&host);
  1117. if(Curl_dyn_add(&host, normalized_ipv4)) {
  1118. result = CURLUE_OUT_OF_MEMORY;
  1119. goto fail;
  1120. }
  1121. }
  1122. else {
  1123. result = decode_host(&host);
  1124. if(!result)
  1125. result = hostname_check(u, Curl_dyn_ptr(&host), Curl_dyn_len(&host));
  1126. if(result)
  1127. goto fail;
  1128. }
  1129. if((flags & CURLU_GUESS_SCHEME) && !schemep) {
  1130. const char *hostname = Curl_dyn_ptr(&host);
  1131. /* legacy curl-style guess based on host name */
  1132. if(checkprefix("ftp.", hostname))
  1133. schemep = "ftp";
  1134. else if(checkprefix("dict.", hostname))
  1135. schemep = "dict";
  1136. else if(checkprefix("ldap.", hostname))
  1137. schemep = "ldap";
  1138. else if(checkprefix("imap.", hostname))
  1139. schemep = "imap";
  1140. else if(checkprefix("smtp.", hostname))
  1141. schemep = "smtp";
  1142. else if(checkprefix("pop3.", hostname))
  1143. schemep = "pop3";
  1144. else
  1145. schemep = "http";
  1146. u->scheme = strdup(schemep);
  1147. if(!u->scheme) {
  1148. result = CURLUE_OUT_OF_MEMORY;
  1149. goto fail;
  1150. }
  1151. }
  1152. }
  1153. else if(flags & CURLU_NO_AUTHORITY) {
  1154. /* allowed to be empty. */
  1155. if(Curl_dyn_add(&host, "")) {
  1156. result = CURLUE_OUT_OF_MEMORY;
  1157. goto fail;
  1158. }
  1159. }
  1160. u->host = Curl_dyn_ptr(&host);
  1161. return result;
  1162. fail:
  1163. Curl_dyn_free(&host);
  1164. free_urlhandle(u);
  1165. return result;
  1166. }
  1167. /*
  1168. * Parse the URL and, if successful, replace everything in the Curl_URL struct.
  1169. */
  1170. static CURLUcode parseurl_and_replace(const char *url, CURLU *u,
  1171. unsigned int flags)
  1172. {
  1173. CURLUcode result;
  1174. CURLU tmpurl;
  1175. memset(&tmpurl, 0, sizeof(tmpurl));
  1176. result = parseurl(url, &tmpurl, flags);
  1177. if(!result) {
  1178. free_urlhandle(u);
  1179. *u = tmpurl;
  1180. }
  1181. return result;
  1182. }
  1183. /*
  1184. */
  1185. CURLU *curl_url(void)
  1186. {
  1187. return calloc(sizeof(struct Curl_URL), 1);
  1188. }
  1189. void curl_url_cleanup(CURLU *u)
  1190. {
  1191. if(u) {
  1192. free_urlhandle(u);
  1193. free(u);
  1194. }
  1195. }
  1196. #define DUP(dest, src, name) \
  1197. do { \
  1198. if(src->name) { \
  1199. dest->name = strdup(src->name); \
  1200. if(!dest->name) \
  1201. goto fail; \
  1202. } \
  1203. } while(0)
  1204. CURLU *curl_url_dup(CURLU *in)
  1205. {
  1206. struct Curl_URL *u = calloc(sizeof(struct Curl_URL), 1);
  1207. if(u) {
  1208. DUP(u, in, scheme);
  1209. DUP(u, in, user);
  1210. DUP(u, in, password);
  1211. DUP(u, in, options);
  1212. DUP(u, in, host);
  1213. DUP(u, in, port);
  1214. DUP(u, in, path);
  1215. DUP(u, in, query);
  1216. DUP(u, in, fragment);
  1217. u->portnum = in->portnum;
  1218. }
  1219. return u;
  1220. fail:
  1221. curl_url_cleanup(u);
  1222. return NULL;
  1223. }
  1224. CURLUcode curl_url_get(CURLU *u, CURLUPart what,
  1225. char **part, unsigned int flags)
  1226. {
  1227. char *ptr;
  1228. CURLUcode ifmissing = CURLUE_UNKNOWN_PART;
  1229. char portbuf[7];
  1230. bool urldecode = (flags & CURLU_URLDECODE)?1:0;
  1231. bool urlencode = (flags & CURLU_URLENCODE)?1:0;
  1232. bool plusdecode = FALSE;
  1233. (void)flags;
  1234. if(!u)
  1235. return CURLUE_BAD_HANDLE;
  1236. if(!part)
  1237. return CURLUE_BAD_PARTPOINTER;
  1238. *part = NULL;
  1239. switch(what) {
  1240. case CURLUPART_SCHEME:
  1241. ptr = u->scheme;
  1242. ifmissing = CURLUE_NO_SCHEME;
  1243. urldecode = FALSE; /* never for schemes */
  1244. break;
  1245. case CURLUPART_USER:
  1246. ptr = u->user;
  1247. ifmissing = CURLUE_NO_USER;
  1248. break;
  1249. case CURLUPART_PASSWORD:
  1250. ptr = u->password;
  1251. ifmissing = CURLUE_NO_PASSWORD;
  1252. break;
  1253. case CURLUPART_OPTIONS:
  1254. ptr = u->options;
  1255. ifmissing = CURLUE_NO_OPTIONS;
  1256. break;
  1257. case CURLUPART_HOST:
  1258. ptr = u->host;
  1259. ifmissing = CURLUE_NO_HOST;
  1260. break;
  1261. case CURLUPART_ZONEID:
  1262. ptr = u->zoneid;
  1263. ifmissing = CURLUE_NO_ZONEID;
  1264. break;
  1265. case CURLUPART_PORT:
  1266. ptr = u->port;
  1267. ifmissing = CURLUE_NO_PORT;
  1268. urldecode = FALSE; /* never for port */
  1269. if(!ptr && (flags & CURLU_DEFAULT_PORT) && u->scheme) {
  1270. /* there's no stored port number, but asked to deliver
  1271. a default one for the scheme */
  1272. const struct Curl_handler *h =
  1273. Curl_builtin_scheme(u->scheme, CURL_ZERO_TERMINATED);
  1274. if(h) {
  1275. msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
  1276. ptr = portbuf;
  1277. }
  1278. }
  1279. else if(ptr && u->scheme) {
  1280. /* there is a stored port number, but ask to inhibit if
  1281. it matches the default one for the scheme */
  1282. const struct Curl_handler *h =
  1283. Curl_builtin_scheme(u->scheme, CURL_ZERO_TERMINATED);
  1284. if(h && (h->defport == u->portnum) &&
  1285. (flags & CURLU_NO_DEFAULT_PORT))
  1286. ptr = NULL;
  1287. }
  1288. break;
  1289. case CURLUPART_PATH:
  1290. ptr = u->path;
  1291. if(!ptr) {
  1292. ptr = u->path = strdup("/");
  1293. if(!u->path)
  1294. return CURLUE_OUT_OF_MEMORY;
  1295. }
  1296. break;
  1297. case CURLUPART_QUERY:
  1298. ptr = u->query;
  1299. ifmissing = CURLUE_NO_QUERY;
  1300. plusdecode = urldecode;
  1301. break;
  1302. case CURLUPART_FRAGMENT:
  1303. ptr = u->fragment;
  1304. ifmissing = CURLUE_NO_FRAGMENT;
  1305. break;
  1306. case CURLUPART_URL: {
  1307. char *url;
  1308. char *scheme;
  1309. char *options = u->options;
  1310. char *port = u->port;
  1311. char *allochost = NULL;
  1312. if(u->scheme && strcasecompare("file", u->scheme)) {
  1313. url = aprintf("file://%s%s%s",
  1314. u->path,
  1315. u->fragment? "#": "",
  1316. u->fragment? u->fragment : "");
  1317. }
  1318. else if(!u->host)
  1319. return CURLUE_NO_HOST;
  1320. else {
  1321. const struct Curl_handler *h = NULL;
  1322. if(u->scheme)
  1323. scheme = u->scheme;
  1324. else if(flags & CURLU_DEFAULT_SCHEME)
  1325. scheme = (char *) DEFAULT_SCHEME;
  1326. else
  1327. return CURLUE_NO_SCHEME;
  1328. h = Curl_builtin_scheme(scheme, CURL_ZERO_TERMINATED);
  1329. if(!port && (flags & CURLU_DEFAULT_PORT)) {
  1330. /* there's no stored port number, but asked to deliver
  1331. a default one for the scheme */
  1332. if(h) {
  1333. msnprintf(portbuf, sizeof(portbuf), "%u", h->defport);
  1334. port = portbuf;
  1335. }
  1336. }
  1337. else if(port) {
  1338. /* there is a stored port number, but asked to inhibit if it matches
  1339. the default one for the scheme */
  1340. if(h && (h->defport == u->portnum) &&
  1341. (flags & CURLU_NO_DEFAULT_PORT))
  1342. port = NULL;
  1343. }
  1344. if(h && !(h->flags & PROTOPT_URLOPTIONS))
  1345. options = NULL;
  1346. if(u->host[0] == '[') {
  1347. if(u->zoneid) {
  1348. /* make it '[ host %25 zoneid ]' */
  1349. struct dynbuf enc;
  1350. size_t hostlen = strlen(u->host);
  1351. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1352. if(Curl_dyn_addf(&enc, "%.*s%%25%s]", (int)hostlen - 1, u->host,
  1353. u->zoneid))
  1354. return CURLUE_OUT_OF_MEMORY;
  1355. allochost = Curl_dyn_ptr(&enc);
  1356. }
  1357. }
  1358. else if(urlencode) {
  1359. allochost = curl_easy_escape(NULL, u->host, 0);
  1360. if(!allochost)
  1361. return CURLUE_OUT_OF_MEMORY;
  1362. }
  1363. else {
  1364. /* only encode '%' in output host name */
  1365. char *host = u->host;
  1366. bool percent = FALSE;
  1367. /* first, count number of percents present in the name */
  1368. while(*host) {
  1369. if(*host == '%') {
  1370. percent = TRUE;
  1371. break;
  1372. }
  1373. host++;
  1374. }
  1375. /* if there were percent(s), encode the host name */
  1376. if(percent) {
  1377. struct dynbuf enc;
  1378. CURLcode result;
  1379. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1380. host = u->host;
  1381. while(*host) {
  1382. if(*host == '%')
  1383. result = Curl_dyn_addn(&enc, "%25", 3);
  1384. else
  1385. result = Curl_dyn_addn(&enc, host, 1);
  1386. if(result)
  1387. return CURLUE_OUT_OF_MEMORY;
  1388. host++;
  1389. }
  1390. free(u->host);
  1391. u->host = Curl_dyn_ptr(&enc);
  1392. }
  1393. }
  1394. url = aprintf("%s://%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
  1395. scheme,
  1396. u->user ? u->user : "",
  1397. u->password ? ":": "",
  1398. u->password ? u->password : "",
  1399. options ? ";" : "",
  1400. options ? options : "",
  1401. (u->user || u->password || options) ? "@": "",
  1402. allochost ? allochost : u->host,
  1403. port ? ":": "",
  1404. port ? port : "",
  1405. (u->path && (u->path[0] != '/')) ? "/": "",
  1406. u->path ? u->path : "/",
  1407. (u->query && u->query[0]) ? "?": "",
  1408. (u->query && u->query[0]) ? u->query : "",
  1409. u->fragment? "#": "",
  1410. u->fragment? u->fragment : "");
  1411. free(allochost);
  1412. }
  1413. if(!url)
  1414. return CURLUE_OUT_OF_MEMORY;
  1415. *part = url;
  1416. return CURLUE_OK;
  1417. }
  1418. default:
  1419. ptr = NULL;
  1420. break;
  1421. }
  1422. if(ptr) {
  1423. size_t partlen = strlen(ptr);
  1424. size_t i = 0;
  1425. *part = Curl_memdup(ptr, partlen + 1);
  1426. if(!*part)
  1427. return CURLUE_OUT_OF_MEMORY;
  1428. if(plusdecode) {
  1429. /* convert + to space */
  1430. char *plus = *part;
  1431. for(i = 0; i < partlen; ++plus, i++) {
  1432. if(*plus == '+')
  1433. *plus = ' ';
  1434. }
  1435. }
  1436. if(urldecode) {
  1437. char *decoded;
  1438. size_t dlen;
  1439. /* this unconditional rejection of control bytes is documented
  1440. API behavior */
  1441. CURLcode res = Curl_urldecode(*part, 0, &decoded, &dlen, REJECT_CTRL);
  1442. free(*part);
  1443. if(res) {
  1444. *part = NULL;
  1445. return CURLUE_URLDECODE;
  1446. }
  1447. *part = decoded;
  1448. partlen = dlen;
  1449. }
  1450. if(urlencode) {
  1451. struct dynbuf enc;
  1452. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1453. if(urlencode_str(&enc, *part, partlen, TRUE,
  1454. what == CURLUPART_QUERY))
  1455. return CURLUE_OUT_OF_MEMORY;
  1456. free(*part);
  1457. *part = Curl_dyn_ptr(&enc);
  1458. }
  1459. return CURLUE_OK;
  1460. }
  1461. else
  1462. return ifmissing;
  1463. }
  1464. CURLUcode curl_url_set(CURLU *u, CURLUPart what,
  1465. const char *part, unsigned int flags)
  1466. {
  1467. char **storep = NULL;
  1468. long port = 0;
  1469. bool urlencode = (flags & CURLU_URLENCODE)? 1 : 0;
  1470. bool plusencode = FALSE;
  1471. bool urlskipslash = FALSE;
  1472. bool appendquery = FALSE;
  1473. bool equalsencode = FALSE;
  1474. if(!u)
  1475. return CURLUE_BAD_HANDLE;
  1476. if(!part) {
  1477. /* setting a part to NULL clears it */
  1478. switch(what) {
  1479. case CURLUPART_URL:
  1480. break;
  1481. case CURLUPART_SCHEME:
  1482. storep = &u->scheme;
  1483. break;
  1484. case CURLUPART_USER:
  1485. storep = &u->user;
  1486. break;
  1487. case CURLUPART_PASSWORD:
  1488. storep = &u->password;
  1489. break;
  1490. case CURLUPART_OPTIONS:
  1491. storep = &u->options;
  1492. break;
  1493. case CURLUPART_HOST:
  1494. storep = &u->host;
  1495. break;
  1496. case CURLUPART_ZONEID:
  1497. storep = &u->zoneid;
  1498. break;
  1499. case CURLUPART_PORT:
  1500. u->portnum = 0;
  1501. storep = &u->port;
  1502. break;
  1503. case CURLUPART_PATH:
  1504. storep = &u->path;
  1505. break;
  1506. case CURLUPART_QUERY:
  1507. storep = &u->query;
  1508. break;
  1509. case CURLUPART_FRAGMENT:
  1510. storep = &u->fragment;
  1511. break;
  1512. default:
  1513. return CURLUE_UNKNOWN_PART;
  1514. }
  1515. if(storep && *storep) {
  1516. Curl_safefree(*storep);
  1517. }
  1518. else if(!storep) {
  1519. free_urlhandle(u);
  1520. memset(u, 0, sizeof(struct Curl_URL));
  1521. }
  1522. return CURLUE_OK;
  1523. }
  1524. switch(what) {
  1525. case CURLUPART_SCHEME:
  1526. if(strlen(part) > MAX_SCHEME_LEN)
  1527. /* too long */
  1528. return CURLUE_BAD_SCHEME;
  1529. if(!(flags & CURLU_NON_SUPPORT_SCHEME) &&
  1530. /* verify that it is a fine scheme */
  1531. !Curl_builtin_scheme(part, CURL_ZERO_TERMINATED))
  1532. return CURLUE_UNSUPPORTED_SCHEME;
  1533. storep = &u->scheme;
  1534. urlencode = FALSE; /* never */
  1535. break;
  1536. case CURLUPART_USER:
  1537. storep = &u->user;
  1538. break;
  1539. case CURLUPART_PASSWORD:
  1540. storep = &u->password;
  1541. break;
  1542. case CURLUPART_OPTIONS:
  1543. storep = &u->options;
  1544. break;
  1545. case CURLUPART_HOST: {
  1546. size_t len = strcspn(part, " \r\n");
  1547. if(strlen(part) != len)
  1548. /* hostname with bad content */
  1549. return CURLUE_BAD_HOSTNAME;
  1550. storep = &u->host;
  1551. Curl_safefree(u->zoneid);
  1552. break;
  1553. }
  1554. case CURLUPART_ZONEID:
  1555. storep = &u->zoneid;
  1556. break;
  1557. case CURLUPART_PORT:
  1558. {
  1559. char *endp;
  1560. urlencode = FALSE; /* never */
  1561. port = strtol(part, &endp, 10); /* Port number must be decimal */
  1562. if((port <= 0) || (port > 0xffff))
  1563. return CURLUE_BAD_PORT_NUMBER;
  1564. if(*endp)
  1565. /* weirdly provided number, not good! */
  1566. return CURLUE_BAD_PORT_NUMBER;
  1567. storep = &u->port;
  1568. }
  1569. break;
  1570. case CURLUPART_PATH:
  1571. urlskipslash = TRUE;
  1572. storep = &u->path;
  1573. break;
  1574. case CURLUPART_QUERY:
  1575. plusencode = urlencode;
  1576. appendquery = (flags & CURLU_APPENDQUERY)?1:0;
  1577. equalsencode = appendquery;
  1578. storep = &u->query;
  1579. break;
  1580. case CURLUPART_FRAGMENT:
  1581. storep = &u->fragment;
  1582. break;
  1583. case CURLUPART_URL: {
  1584. /*
  1585. * Allow a new URL to replace the existing (if any) contents.
  1586. *
  1587. * If the existing contents is enough for a URL, allow a relative URL to
  1588. * replace it.
  1589. */
  1590. CURLUcode result;
  1591. char *oldurl;
  1592. char *redired_url;
  1593. /* if the new thing is absolute or the old one is not
  1594. * (we could not get an absolute url in 'oldurl'),
  1595. * then replace the existing with the new. */
  1596. if(Curl_is_absolute_url(part, NULL, 0,
  1597. flags & (CURLU_GUESS_SCHEME|
  1598. CURLU_DEFAULT_SCHEME))
  1599. || curl_url_get(u, CURLUPART_URL, &oldurl, flags)) {
  1600. return parseurl_and_replace(part, u, flags);
  1601. }
  1602. /* apply the relative part to create a new URL
  1603. * and replace the existing one with it. */
  1604. redired_url = concat_url(oldurl, part);
  1605. free(oldurl);
  1606. if(!redired_url)
  1607. return CURLUE_OUT_OF_MEMORY;
  1608. result = parseurl_and_replace(redired_url, u, flags);
  1609. free(redired_url);
  1610. return result;
  1611. }
  1612. default:
  1613. return CURLUE_UNKNOWN_PART;
  1614. }
  1615. DEBUGASSERT(storep);
  1616. {
  1617. const char *newp = part;
  1618. size_t nalloc = strlen(part);
  1619. if(nalloc > CURL_MAX_INPUT_LENGTH)
  1620. /* excessive input length */
  1621. return CURLUE_MALFORMED_INPUT;
  1622. if(urlencode) {
  1623. const unsigned char *i;
  1624. struct dynbuf enc;
  1625. Curl_dyn_init(&enc, nalloc * 3 + 1);
  1626. for(i = (const unsigned char *)part; *i; i++) {
  1627. CURLcode result;
  1628. if((*i == ' ') && plusencode) {
  1629. result = Curl_dyn_addn(&enc, "+", 1);
  1630. if(result)
  1631. return CURLUE_OUT_OF_MEMORY;
  1632. }
  1633. else if(Curl_isunreserved(*i) ||
  1634. ((*i == '/') && urlskipslash) ||
  1635. ((*i == '=') && equalsencode)) {
  1636. if((*i == '=') && equalsencode)
  1637. /* only skip the first equals sign */
  1638. equalsencode = FALSE;
  1639. result = Curl_dyn_addn(&enc, i, 1);
  1640. if(result)
  1641. return CURLUE_OUT_OF_MEMORY;
  1642. }
  1643. else {
  1644. result = Curl_dyn_addf(&enc, "%%%02x", *i);
  1645. if(result)
  1646. return CURLUE_OUT_OF_MEMORY;
  1647. }
  1648. }
  1649. newp = Curl_dyn_ptr(&enc);
  1650. }
  1651. else {
  1652. char *p;
  1653. newp = strdup(part);
  1654. if(!newp)
  1655. return CURLUE_OUT_OF_MEMORY;
  1656. p = (char *)newp;
  1657. while(*p) {
  1658. /* make sure percent encoded are lower case */
  1659. if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) &&
  1660. (ISUPPER(p[1]) || ISUPPER(p[2]))) {
  1661. p[1] = Curl_raw_tolower(p[1]);
  1662. p[2] = Curl_raw_tolower(p[2]);
  1663. p += 3;
  1664. }
  1665. else
  1666. p++;
  1667. }
  1668. }
  1669. if(appendquery) {
  1670. /* Append the 'newp' string onto the old query. Add a '&' separator if
  1671. none is present at the end of the existing query already */
  1672. size_t querylen = u->query ? strlen(u->query) : 0;
  1673. bool addamperand = querylen && (u->query[querylen -1] != '&');
  1674. if(querylen) {
  1675. struct dynbuf enc;
  1676. Curl_dyn_init(&enc, CURL_MAX_INPUT_LENGTH);
  1677. if(Curl_dyn_addn(&enc, u->query, querylen)) /* add original query */
  1678. goto nomem;
  1679. if(addamperand) {
  1680. if(Curl_dyn_addn(&enc, "&", 1))
  1681. goto nomem;
  1682. }
  1683. if(Curl_dyn_add(&enc, newp))
  1684. goto nomem;
  1685. free((char *)newp);
  1686. free(*storep);
  1687. *storep = Curl_dyn_ptr(&enc);
  1688. return CURLUE_OK;
  1689. nomem:
  1690. free((char *)newp);
  1691. return CURLUE_OUT_OF_MEMORY;
  1692. }
  1693. }
  1694. if(what == CURLUPART_HOST) {
  1695. size_t n = strlen(newp);
  1696. if(!n && (flags & CURLU_NO_AUTHORITY)) {
  1697. /* Skip hostname check, it's allowed to be empty. */
  1698. }
  1699. else {
  1700. if(hostname_check(u, (char *)newp, n)) {
  1701. free((char *)newp);
  1702. return CURLUE_BAD_HOSTNAME;
  1703. }
  1704. }
  1705. }
  1706. free(*storep);
  1707. *storep = (char *)newp;
  1708. }
  1709. /* set after the string, to make it not assigned if the allocation above
  1710. fails */
  1711. if(port)
  1712. u->portnum = port;
  1713. return CURLUE_OK;
  1714. }