blob: 183dd17a76d5507bddcb3f60aeb5b07698beebe1 [file] [log] [blame]
Lucas Eckels9bd90e62012-08-06 15:07:02 -07001Online: http://curl.haxx.se/docs/httpscripting.html
2Date: May 28, 2008
3
4 The Art Of Scripting HTTP Requests Using Curl
5 =============================================
6
7 This document will assume that you're familiar with HTML and general
8 networking.
9
10 The possibility to write scripts is essential to make a good computer
11 system. Unix' capability to be extended by shell scripts and various tools to
12 run various automated commands and scripts is one reason why it has succeeded
13 so well.
14
15 The increasing amount of applications moving to the web has made "HTTP
16 Scripting" more frequently requested and wanted. To be able to automatically
17 extract information from the web, to fake users, to post or upload data to
18 web servers are all important tasks today.
19
20 Curl is a command line tool for doing all sorts of URL manipulations and
21 transfers, but this particular document will focus on how to use it when
22 doing HTTP requests for fun and profit. I'll assume that you know how to
23 invoke 'curl --help' or 'curl --manual' to get basic information about it.
24
25 Curl is not written to do everything for you. It makes the requests, it gets
26 the data, it sends data and it retrieves the information. You probably need
27 to glue everything together using some kind of script language or repeated
28 manual invokes.
29
301. The HTTP Protocol
31
32 HTTP is the protocol used to fetch data from web servers. It is a very simple
33 protocol that is built upon TCP/IP. The protocol also allows information to
34 get sent to the server from the client using a few different methods, as will
35 be shown here.
36
37 HTTP is plain ASCII text lines being sent by the client to a server to
38 request a particular action, and then the server replies a few text lines
39 before the actual requested content is sent to the client.
40
41 Using curl's option --verbose (-v as a short option) will display what kind of
42 commands curl sends to the server, as well as a few other informational texts.
43 --verbose is the single most useful option when it comes to debug or even
44 understand the curl<->server interaction.
45
462. URL
47
48 The Uniform Resource Locator format is how you specify the address of a
49 particular resource on the Internet. You know these, you've seen URLs like
50 http://curl.haxx.se or https://yourbank.com a million times.
51
523. GET a page
53
54 The simplest and most common request/operation made using HTTP is to get a
55 URL. The URL could itself refer to a web page, an image or a file. The client
56 issues a GET request to the server and receives the document it asked for.
57 If you issue the command line
58
59 curl http://curl.haxx.se
60
61 you get a web page returned in your terminal window. The entire HTML document
62 that that URL holds.
63
64 All HTTP replies contain a set of headers that are normally hidden, use
65 curl's --include (-i) option to display them as well as the rest of the
66 document. You can also ask the remote server for ONLY the headers by using the
67 --head (-I) option (which will make curl issue a HEAD request).
68
694. Forms
70
71 Forms are the general way a web site can present a HTML page with fields for
72 the user to enter data in, and then press some kind of 'OK' or 'submit'
73 button to get that data sent to the server. The server then typically uses
74 the posted data to decide how to act. Like using the entered words to search
75 in a database, or to add the info in a bug track system, display the entered
76 address on a map or using the info as a login-prompt verifying that the user
77 is allowed to see what it is about to see.
78
79 Of course there has to be some kind of program in the server end to receive
80 the data you send. You cannot just invent something out of the air.
81
82 4.1 GET
83
84 A GET-form uses the method GET, as specified in HTML like:
85
86 <form method="GET" action="junk.cgi">
87 <input type=text name="birthyear">
88 <input type=submit name=press value="OK">
89 </form>
90
91 In your favorite browser, this form will appear with a text box to fill in
92 and a press-button labeled "OK". If you fill in '1905' and press the OK
93 button, your browser will then create a new URL to get for you. The URL will
94 get "junk.cgi?birthyear=1905&press=OK" appended to the path part of the
95 previous URL.
96
97 If the original form was seen on the page "www.hotmail.com/when/birth.html",
98 the second page you'll get will become
99 "www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK".
100
101 Most search engines work this way.
102
103 To make curl do the GET form post for you, just enter the expected created
104 URL:
105
106 curl "http://www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK"
107
108 4.2 POST
109
110 The GET method makes all input field names get displayed in the URL field of
111 your browser. That's generally a good thing when you want to be able to
112 bookmark that page with your given data, but it is an obvious disadvantage
113 if you entered secret information in one of the fields or if there are a
114 large amount of fields creating a very long and unreadable URL.
115
116 The HTTP protocol then offers the POST method. This way the client sends the
117 data separated from the URL and thus you won't see any of it in the URL
118 address field.
119
120 The form would look very similar to the previous one:
121
122 <form method="POST" action="junk.cgi">
123 <input type=text name="birthyear">
124 <input type=submit name=press value=" OK ">
125 </form>
126
127 And to use curl to post this form with the same data filled in as before, we
128 could do it like:
129
130 curl --data "birthyear=1905&press=%20OK%20" http://www.hotmail.com/when/junk.cgi
131
132 This kind of POST will use the Content-Type
133 application/x-www-form-urlencoded and is the most widely used POST kind.
134
135 The data you send to the server MUST already be properly encoded, curl will
136 not do that for you. For example, if you want the data to contain a space,
137 you need to replace that space with %20 etc. Failing to comply with this
138 will most likely cause your data to be received wrongly and messed up.
139
140 Recent curl versions can in fact url-encode POST data for you, like this:
141
142 curl --data-urlencode "name=I am Daniel" http://www.example.com
143
144 4.3 File Upload POST
145
146 Back in late 1995 they defined an additional way to post data over HTTP. It
147 is documented in the RFC 1867, why this method sometimes is referred to as
148 RFC1867-posting.
149
150 This method is mainly designed to better support file uploads. A form that
151 allows a user to upload a file could be written like this in HTML:
152
153 <form method="POST" enctype='multipart/form-data' action="upload.cgi">
154 <input type=file name=upload>
155 <input type=submit name=press value="OK">
156 </form>
157
158 This clearly shows that the Content-Type about to be sent is
159 multipart/form-data.
160
161 To post to a form like this with curl, you enter a command line like:
162
163 curl --form upload=@localfilename --form press=OK [URL]
164
165 4.4 Hidden Fields
166
167 A very common way for HTML based application to pass state information
168 between pages is to add hidden fields to the forms. Hidden fields are
169 already filled in, they aren't displayed to the user and they get passed
170 along just as all the other fields.
171
172 A similar example form with one visible field, one hidden field and one
173 submit button could look like:
174
175 <form method="POST" action="foobar.cgi">
176 <input type=text name="birthyear">
177 <input type=hidden name="person" value="daniel">
178 <input type=submit name="press" value="OK">
179 </form>
180
181 To post this with curl, you won't have to think about if the fields are
182 hidden or not. To curl they're all the same:
183
184 curl --data "birthyear=1905&press=OK&person=daniel" [URL]
185
186 4.5 Figure Out What A POST Looks Like
187
188 When you're about fill in a form and send to a server by using curl instead
189 of a browser, you're of course very interested in sending a POST exactly the
190 way your browser does.
191
192 An easy way to get to see this, is to save the HTML page with the form on
193 your local disk, modify the 'method' to a GET, and press the submit button
194 (you could also change the action URL if you want to).
195
196 You will then clearly see the data get appended to the URL, separated with a
197 '?'-letter as GET forms are supposed to.
198
1995. PUT
200
201 The perhaps best way to upload data to a HTTP server is to use PUT. Then
202 again, this of course requires that someone put a program or script on the
203 server end that knows how to receive a HTTP PUT stream.
204
205 Put a file to a HTTP server with curl:
206
207 curl --upload-file uploadfile http://www.uploadhttp.com/receive.cgi
208
2096. HTTP Authentication
210
211 HTTP Authentication is the ability to tell the server your username and
212 password so that it can verify that you're allowed to do the request you're
213 doing. The Basic authentication used in HTTP (which is the type curl uses by
214 default) is *plain* *text* based, which means it sends username and password
215 only slightly obfuscated, but still fully readable by anyone that sniffs on
216 the network between you and the remote server.
217
218 To tell curl to use a user and password for authentication:
219
220 curl --user name:password http://www.secrets.com
221
222 The site might require a different authentication method (check the headers
223 returned by the server), and then --ntlm, --digest, --negotiate or even
224 --anyauth might be options that suit you.
225
226 Sometimes your HTTP access is only available through the use of a HTTP
227 proxy. This seems to be especially common at various companies. A HTTP proxy
228 may require its own user and password to allow the client to get through to
229 the Internet. To specify those with curl, run something like:
230
231 curl --proxy-user proxyuser:proxypassword curl.haxx.se
232
233 If your proxy requires the authentication to be done using the NTLM method,
234 use --proxy-ntlm, if it requires Digest use --proxy-digest.
235
236 If you use any one these user+password options but leave out the password
237 part, curl will prompt for the password interactively.
238
239 Do note that when a program is run, its parameters might be possible to see
240 when listing the running processes of the system. Thus, other users may be
241 able to watch your passwords if you pass them as plain command line
242 options. There are ways to circumvent this.
243
244 It is worth noting that while this is how HTTP Authentication works, very
245 many web sites will not use this concept when they provide logins etc. See
246 the Web Login chapter further below for more details on that.
247
2487. Referer
249
250 A HTTP request may include a 'referer' field (yes it is misspelled), which
251 can be used to tell from which URL the client got to this particular
252 resource. Some programs/scripts check the referer field of requests to verify
253 that this wasn't arriving from an external site or an unknown page. While
254 this is a stupid way to check something so easily forged, many scripts still
255 do it. Using curl, you can put anything you want in the referer-field and
256 thus more easily be able to fool the server into serving your request.
257
258 Use curl to set the referer field with:
259
260 curl --referer http://curl.haxx.se http://daniel.haxx.se
261
2628. User Agent
263
264 Very similar to the referer field, all HTTP requests may set the User-Agent
265 field. It names what user agent (client) that is being used. Many
266 applications use this information to decide how to display pages. Silly web
267 programmers try to make different pages for users of different browsers to
268 make them look the best possible for their particular browsers. They usually
269 also do different kinds of javascript, vbscript etc.
270
271 At times, you will see that getting a page with curl will not return the same
272 page that you see when getting the page with your browser. Then you know it
273 is time to set the User Agent field to fool the server into thinking you're
274 one of those browsers.
275
276 To make curl look like Internet Explorer on a Windows 2000 box:
277
278 curl --user-agent "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" [URL]
279
280 Or why not look like you're using Netscape 4.73 on a Linux (PIII) box:
281
282 curl --user-agent "Mozilla/4.73 [en] (X11; U; Linux 2.2.15 i686)" [URL]
283
2849. Redirects
285
286 When a resource is requested from a server, the reply from the server may
287 include a hint about where the browser should go next to find this page, or a
288 new page keeping newly generated output. The header that tells the browser
289 to redirect is Location:.
290
291 Curl does not follow Location: headers by default, but will simply display
292 such pages in the same manner it display all HTTP replies. It does however
293 feature an option that will make it attempt to follow the Location: pointers.
294
295 To tell curl to follow a Location:
296
297 curl --location http://www.sitethatredirects.com
298
299 If you use curl to POST to a site that immediately redirects you to another
300 page, you can safely use --location (-L) and --data/--form together. Curl will
301 only use POST in the first request, and then revert to GET in the following
302 operations.
303
30410. Cookies
305
306 The way the web browsers do "client side state control" is by using
307 cookies. Cookies are just names with associated contents. The cookies are
308 sent to the client by the server. The server tells the client for what path
309 and host name it wants the cookie sent back, and it also sends an expiration
310 date and a few more properties.
311
312 When a client communicates with a server with a name and path as previously
313 specified in a received cookie, the client sends back the cookies and their
314 contents to the server, unless of course they are expired.
315
316 Many applications and servers use this method to connect a series of requests
317 into a single logical session. To be able to use curl in such occasions, we
318 must be able to record and send back cookies the way the web application
319 expects them. The same way browsers deal with them.
320
321 The simplest way to send a few cookies to the server when getting a page with
322 curl is to add them on the command line like:
323
324 curl --cookie "name=Daniel" http://www.cookiesite.com
325
326 Cookies are sent as common HTTP headers. This is practical as it allows curl
327 to record cookies simply by recording headers. Record cookies with curl by
328 using the --dump-header (-D) option like:
329
330 curl --dump-header headers_and_cookies http://www.cookiesite.com
331
332 (Take note that the --cookie-jar option described below is a better way to
333 store cookies.)
334
335 Curl has a full blown cookie parsing engine built-in that comes to use if you
336 want to reconnect to a server and use cookies that were stored from a
337 previous connection (or handicrafted manually to fool the server into
338 believing you had a previous connection). To use previously stored cookies,
339 you run curl like:
340
341 curl --cookie stored_cookies_in_file http://www.cookiesite.com
342
343 Curl's "cookie engine" gets enabled when you use the --cookie option. If you
344 only want curl to understand received cookies, use --cookie with a file that
345 doesn't exist. Example, if you want to let curl understand cookies from a page
346 and follow a location (and thus possibly send back cookies it received), you
347 can invoke it like:
348
349 curl --cookie nada --location http://www.cookiesite.com
350
351 Curl has the ability to read and write cookie files that use the same file
352 format that Netscape and Mozilla do. It is a convenient way to share cookies
353 between browsers and automatic scripts. The --cookie (-b) switch automatically
354 detects if a given file is such a cookie file and parses it, and by using the
355 --cookie-jar (-c) option you'll make curl write a new cookie file at the end of
356 an operation:
357
358 curl --cookie cookies.txt --cookie-jar newcookies.txt http://www.cookiesite.com
359
36011. HTTPS
361
362 There are a few ways to do secure HTTP transfers. The by far most common
363 protocol for doing this is what is generally known as HTTPS, HTTP over
364 SSL. SSL encrypts all the data that is sent and received over the network and
365 thus makes it harder for attackers to spy on sensitive information.
366
367 SSL (or TLS as the latest version of the standard is called) offers a
368 truckload of advanced features to allow all those encryptions and key
369 infrastructure mechanisms encrypted HTTP requires.
370
371 Curl supports encrypted fetches thanks to the freely available OpenSSL
372 libraries. To get a page from a HTTPS server, simply run curl like:
373
374 curl https://that.secure.server.com
375
376 11.1 Certificates
377
378 In the HTTPS world, you use certificates to validate that you are the one
379 you claim to be, as an addition to normal passwords. Curl supports client-
380 side certificates. All certificates are locked with a pass phrase, which you
381 need to enter before the certificate can be used by curl. The pass phrase
382 can be specified on the command line or if not, entered interactively when
383 curl queries for it. Use a certificate with curl on a HTTPS server like:
384
385 curl --cert mycert.pem https://that.secure.server.com
386
387 curl also tries to verify that the server is who it claims to be, by
388 verifying the server's certificate against a locally stored CA cert
389 bundle. Failing the verification will cause curl to deny the connection. You
390 must then use --insecure (-k) in case you want to tell curl to ignore that
391 the server can't be verified.
392
393 More about server certificate verification and ca cert bundles can be read
394 in the SSLCERTS document, available online here:
395
396 http://curl.haxx.se/docs/sslcerts.html
397
39812. Custom Request Elements
399
400 Doing fancy stuff, you may need to add or change elements of a single curl
401 request.
402
403 For example, you can change the POST request to a PROPFIND and send the data
404 as "Content-Type: text/xml" (instead of the default Content-Type) like this:
405
406 curl --data "<xml>" --header "Content-Type: text/xml" --request PROPFIND url.com
407
408 You can delete a default header by providing one without content. Like you
409 can ruin the request by chopping off the Host: header:
410
411 curl --header "Host:" http://mysite.com
412
413 You can add headers the same way. Your server may want a "Destination:"
414 header, and you can add it:
415
416 curl --header "Destination: http://moo.com/nowhere" http://url.com
417
41813. Web Login
419
420 While not strictly just HTTP related, it still cause a lot of people problems
421 so here's the executive run-down of how the vast majority of all login forms
422 work and how to login to them using curl.
423
424 It can also be noted that to do this properly in an automated fashion, you
425 will most certainly need to script things and do multiple curl invokes etc.
426
427 First, servers mostly use cookies to track the logged-in status of the
428 client, so you will need to capture the cookies you receive in the
429 responses. Then, many sites also set a special cookie on the login page (to
430 make sure you got there through their login page) so you should make a habit
431 of first getting the login-form page to capture the cookies set there.
432
433 Some web-based login systems features various amounts of javascript, and
434 sometimes they use such code to set or modify cookie contents. Possibly they
435 do that to prevent programmed logins, like this manual describes how to...
436 Anyway, if reading the code isn't enough to let you repeat the behavior
437 manually, capturing the HTTP requests done by your browers and analyzing the
438 sent cookies is usually a working method to work out how to shortcut the
439 javascript need.
440
441 In the actual <form> tag for the login, lots of sites fill-in random/session
442 or otherwise secretly generated hidden tags and you may need to first capture
443 the HTML code for the login form and extract all the hidden fields to be able
444 to do a proper login POST. Remember that the contents need to be URL encoded
445 when sent in a normal POST.
446
447
44814. Debug
449
450 Many times when you run curl on a site, you'll notice that the site doesn't
451 seem to respond the same way to your curl requests as it does to your
452 browser's.
453
454 Then you need to start making your curl requests more similar to your
455 browser's requests:
456
457 * Use the --trace-ascii option to store fully detailed logs of the requests
458 for easier analyzing and better understanding
459
460 * Make sure you check for and use cookies when needed (both reading with
461 --cookie and writing with --cookie-jar)
462
463 * Set user-agent to one like a recent popular browser does
464
465 * Set referer like it is set by the browser
466
467 * If you use POST, make sure you send all the fields and in the same order as
468 the browser does it. (See chapter 4.5 above)
469
470 A very good helper to make sure you do this right, is the LiveHTTPHeader tool
471 that lets you view all headers you send and receive with Mozilla/Firefox
472 (even when using HTTPS).
473
474 A more raw approach is to capture the HTTP traffic on the network with tools
475 such as ethereal or tcpdump and check what headers that were sent and
476 received by the browser. (HTTPS makes this technique inefficient.)
477
47815. References
479
480 RFC 2616 is a must to read if you want in-depth understanding of the HTTP
481 protocol.
482
483 RFC 2396 explains the URL syntax.
484
485 RFC 2109 defines how cookies are supposed to work.
486
487 RFC 1867 defines the HTTP post upload format.
488
489 http://www.openssl.org is the home of the OpenSSL project
490
491 http://curl.haxx.se is the home of the cURL project