1 /**
2  * @file
3  * HTTP client
4  */
5 
6 /*
7  * Copyright (c) 2018 Simon Goldschmidt <goldsimon@gmx.de>
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without modification,
11  * are permitted provided that the following conditions are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright notice,
14  *    this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright notice,
16  *    this list of conditions and the following disclaimer in the documentation
17  *    and/or other materials provided with the distribution.
18  * 3. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
22  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
24  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
26  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
29  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
30  * OF SUCH DAMAGE.
31  *
32  * This file is part of the lwIP TCP/IP stack.
33  *
34  * Author: Simon Goldschmidt <goldsimon@gmx.de>
35  */
36 
37 /**
38  * @defgroup httpc HTTP client
39  * @ingroup apps
40  * @todo:
41  * - persistent connections
42  * - select outgoing http version
43  * - optionally follow redirect
44  * - check request uri for invalid characters? (e.g. encode spaces)
45  * - IPv6 support
46  */
47 
48 #include "lwip/apps/http_client.h"
49 
50 #include "lwip/altcp_tcp.h"
51 #include "lwip/dns.h"
52 #include "lwip/debug.h"
53 #include "lwip/mem.h"
54 #include "lwip/altcp_tls.h"
55 #include "lwip/init.h"
56 
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 
61 #if LWIP_TCP && LWIP_CALLBACK_API
62 
63 /**
64  * HTTPC_DEBUG: Enable debugging for HTTP client.
65  */
66 #ifndef HTTPC_DEBUG
67 #define HTTPC_DEBUG                 LWIP_DBG_OFF
68 #endif
69 
70 /** Set this to 1 to keep server name and uri in request state */
71 #ifndef HTTPC_DEBUG_REQUEST
72 #define HTTPC_DEBUG_REQUEST         0
73 #endif
74 
75 /** This string is passed in the HTTP header as "User-Agent: " */
76 #ifndef HTTPC_CLIENT_AGENT
77 #define HTTPC_CLIENT_AGENT "lwIP/" LWIP_VERSION_STRING " (http://savannah.nongnu.org/projects/lwip)"
78 #endif
79 
80 /* the various debug levels for this file */
81 #define HTTPC_DEBUG_TRACE        (HTTPC_DEBUG | LWIP_DBG_TRACE)
82 #define HTTPC_DEBUG_STATE        (HTTPC_DEBUG | LWIP_DBG_STATE)
83 #define HTTPC_DEBUG_WARN         (HTTPC_DEBUG | LWIP_DBG_LEVEL_WARNING)
84 #define HTTPC_DEBUG_WARN_STATE   (HTTPC_DEBUG | LWIP_DBG_LEVEL_WARNING | LWIP_DBG_STATE)
85 #define HTTPC_DEBUG_SERIOUS      (HTTPC_DEBUG | LWIP_DBG_LEVEL_SERIOUS)
86 
87 #define HTTPC_POLL_INTERVAL     1
88 #define HTTPC_POLL_TIMEOUT      30 /* 15 seconds */
89 
90 #define HTTPC_CONTENT_LEN_INVALID 0xFFFFFFFF
91 
92 /* GET request basic */
93 #define HTTPC_REQ_11 "GET %s HTTP/1.1\r\n" /* URI */\
94     "User-Agent: %s\r\n" /* User-Agent */ \
95     "Accept: */*\r\n" \
96     "Connection: Close\r\n" /* we don't support persistent connections, yet */ \
97     "\r\n"
98 #define HTTPC_REQ_11_FORMAT(uri) HTTPC_REQ_11, uri, HTTPC_CLIENT_AGENT
99 
100 /* GET request with host */
101 #define HTTPC_REQ_11_HOST "GET %s HTTP/1.1\r\n" /* URI */\
102     "User-Agent: %s\r\n" /* User-Agent */ \
103     "Accept: */*\r\n" \
104     "Host: %s\r\n" /* server name */ \
105     "Connection: Close\r\n" /* we don't support persistent connections, yet */ \
106     "\r\n"
107 #define HTTPC_REQ_11_HOST_FORMAT(uri, srv_name) HTTPC_REQ_11_HOST, uri, HTTPC_CLIENT_AGENT, srv_name
108 
109 /* GET request with proxy */
110 #define HTTPC_REQ_11_PROXY "GET http://%s%s HTTP/1.1\r\n" /* HOST, URI */\
111     "User-Agent: %s\r\n" /* User-Agent */ \
112     "Accept: */*\r\n" \
113     "Host: %s\r\n" /* server name */ \
114     "Connection: Close\r\n" /* we don't support persistent connections, yet */ \
115     "\r\n"
116 #define HTTPC_REQ_11_PROXY_FORMAT(host, uri, srv_name) HTTPC_REQ_11_PROXY, host, uri, HTTPC_CLIENT_AGENT, srv_name
117 
118 /* GET request with proxy (non-default server port) */
119 #define HTTPC_REQ_11_PROXY_PORT "GET http://%s:%d%s HTTP/1.1\r\n" /* HOST, host-port, URI */\
120     "User-Agent: %s\r\n" /* User-Agent */ \
121     "Accept: */*\r\n" \
122     "Host: %s\r\n" /* server name */ \
123     "Connection: Close\r\n" /* we don't support persistent connections, yet */ \
124     "\r\n"
125 #define HTTPC_REQ_11_PROXY_PORT_FORMAT(host, host_port, uri, srv_name) HTTPC_REQ_11_PROXY_PORT, host, host_port, uri, HTTPC_CLIENT_AGENT, srv_name
126 
127 typedef enum ehttpc_parse_state {
128   HTTPC_PARSE_WAIT_FIRST_LINE = 0,
129   HTTPC_PARSE_WAIT_HEADERS,
130   HTTPC_PARSE_RX_DATA
131 } httpc_parse_state_t;
132 
133 typedef struct _httpc_state
134 {
135   struct altcp_pcb* pcb;
136   ip_addr_t remote_addr;
137   u16_t remote_port;
138   int timeout_ticks;
139   struct pbuf *request;
140   struct pbuf *rx_hdrs;
141   u16_t rx_http_version;
142   u16_t rx_status;
143   altcp_recv_fn recv_fn;
144   const httpc_connection_t *conn_settings;
145   void* callback_arg;
146   u32_t rx_content_len;
147   u32_t hdr_content_len;
148   httpc_parse_state_t parse_state;
149 #if HTTPC_DEBUG_REQUEST
150   char* server_name;
151   char* uri;
152 #endif
153 } httpc_state_t;
154 
155 /** Free http client state and deallocate all resources within */
156 static err_t
httpc_free_state(httpc_state_t * req)157 httpc_free_state(httpc_state_t* req)
158 {
159   struct altcp_pcb* tpcb;
160 
161   if (req->request != NULL) {
162     pbuf_free(req->request);
163     req->request = NULL;
164   }
165   if (req->rx_hdrs != NULL) {
166     pbuf_free(req->rx_hdrs);
167     req->rx_hdrs = NULL;
168   }
169 
170   tpcb = req->pcb;
171   mem_free(req);
172   req = NULL;
173 
174   if (tpcb != NULL) {
175     err_t r;
176     altcp_arg(tpcb, NULL);
177     altcp_recv(tpcb, NULL);
178     altcp_err(tpcb, NULL);
179     altcp_poll(tpcb, NULL, 0);
180     altcp_sent(tpcb, NULL);
181     r = altcp_close(tpcb);
182     if (r != ERR_OK) {
183       altcp_abort(tpcb);
184       return ERR_ABRT;
185     }
186   }
187   return ERR_OK;
188 }
189 
190 /** Close the connection: call finished callback and free the state */
191 static err_t
httpc_close(httpc_state_t * req,httpc_result_t result,u32_t server_response,err_t err)192 httpc_close(httpc_state_t* req, httpc_result_t result, u32_t server_response, err_t err)
193 {
194   if (req != NULL) {
195     if (req->conn_settings != NULL) {
196       if (req->conn_settings->result_fn != NULL) {
197         req->conn_settings->result_fn(req->callback_arg, result, req->rx_content_len, server_response, err);
198       }
199     }
200     return httpc_free_state(req);
201   }
202   return ERR_OK;
203 }
204 
205 /** Parse http header response line 1 */
206 static err_t
http_parse_response_status(struct pbuf * p,u16_t * http_version,u16_t * http_status,u16_t * http_status_str_offset)207 http_parse_response_status(struct pbuf *p, u16_t *http_version, u16_t *http_status, u16_t *http_status_str_offset)
208 {
209   u16_t end1 = pbuf_memfind(p, "\r\n", 2, 0);
210   if (end1 != 0xFFFF) {
211     /* get parts of first line */
212     u16_t space1, space2;
213     space1 = pbuf_memfind(p, " ", 1, 0);
214     if (space1 != 0xFFFF) {
215       if ((pbuf_memcmp(p, 0, "HTTP/", 5) == 0)  && (pbuf_get_at(p, 6) == '.')) {
216         char status_num[10];
217         size_t status_num_len;
218         /* parse http version */
219         u16_t version = pbuf_get_at(p, 5) - '0';
220         version <<= 8;
221         version |= pbuf_get_at(p, 7) - '0';
222         *http_version = version;
223 
224         /* parse http status number */
225         space2 = pbuf_memfind(p, " ", 1, space1 + 1);
226         if (space2 != 0xFFFF) {
227           *http_status_str_offset = space2 + 1;
228           status_num_len = space2 - space1 - 1;
229         } else {
230           status_num_len = end1 - space1 - 1;
231         }
232         memset(status_num, 0, sizeof(status_num));
233         if (pbuf_copy_partial(p, status_num, (u16_t)status_num_len, space1 + 1) == status_num_len) {
234           int status = atoi(status_num);
235           if ((status > 0) && (status <= 0xFFFF)) {
236             *http_status = (u16_t)status;
237             return ERR_OK;
238           }
239         }
240       }
241     }
242   }
243   return ERR_VAL;
244 }
245 
246 /** Wait for all headers to be received, return its length and content-length (if available) */
247 static err_t
http_wait_headers(struct pbuf * p,u32_t * content_length,u16_t * total_header_len)248 http_wait_headers(struct pbuf *p, u32_t *content_length, u16_t *total_header_len)
249 {
250   u16_t end1 = pbuf_memfind(p, "\r\n\r\n", 4, 0);
251   if (end1 < (0xFFFF - 2)) {
252     /* all headers received */
253     /* check if we have a content length (@todo: case insensitive?) */
254     u16_t content_len_hdr;
255     *content_length = HTTPC_CONTENT_LEN_INVALID;
256     *total_header_len = end1 + 4;
257 
258     content_len_hdr = pbuf_memfind(p, "Content-Length: ", 16, 0);
259     if (content_len_hdr != 0xFFFF) {
260       u16_t content_len_line_end = pbuf_memfind(p, "\r\n", 2, content_len_hdr);
261       if (content_len_line_end != 0xFFFF) {
262         char content_len_num[16];
263         u16_t content_len_num_len = (u16_t)(content_len_line_end - content_len_hdr - 16);
264         memset(content_len_num, 0, sizeof(content_len_num));
265         if (pbuf_copy_partial(p, content_len_num, content_len_num_len, content_len_hdr + 16) == content_len_num_len) {
266           int len = atoi(content_len_num);
267           if ((len >= 0) && ((u32_t)len < HTTPC_CONTENT_LEN_INVALID)) {
268             *content_length = (u32_t)len;
269           }
270         }
271       }
272     }
273     return ERR_OK;
274   }
275   return ERR_VAL;
276 }
277 
278 /** http client tcp recv callback */
279 static err_t
httpc_tcp_recv(void * arg,struct altcp_pcb * pcb,struct pbuf * p,err_t r)280 httpc_tcp_recv(void *arg, struct altcp_pcb *pcb, struct pbuf *p, err_t r)
281 {
282   httpc_state_t* req = (httpc_state_t*)arg;
283   LWIP_UNUSED_ARG(r);
284 
285   if (p == NULL) {
286     httpc_result_t result;
287     if (req->parse_state != HTTPC_PARSE_RX_DATA) {
288       /* did not get RX data yet */
289       result = HTTPC_RESULT_ERR_CLOSED;
290     } else if ((req->hdr_content_len != HTTPC_CONTENT_LEN_INVALID) &&
291       (req->hdr_content_len != req->rx_content_len)) {
292       /* header has been received with content length but not all data received */
293       result = HTTPC_RESULT_ERR_CONTENT_LEN;
294     } else {
295       /* receiving data and either all data received or no content length header */
296       result = HTTPC_RESULT_OK;
297     }
298     return httpc_close(req, result, req->rx_status, ERR_OK);
299   }
300   if (req->parse_state != HTTPC_PARSE_RX_DATA) {
301     if (req->rx_hdrs == NULL) {
302       req->rx_hdrs = p;
303     } else {
304       pbuf_cat(req->rx_hdrs, p);
305     }
306     if (req->parse_state == HTTPC_PARSE_WAIT_FIRST_LINE) {
307       u16_t status_str_off;
308       err_t err = http_parse_response_status(req->rx_hdrs, &req->rx_http_version, &req->rx_status, &status_str_off);
309       if (err == ERR_OK) {
310         /* don't care status string */
311         req->parse_state = HTTPC_PARSE_WAIT_HEADERS;
312       }
313     }
314     if (req->parse_state == HTTPC_PARSE_WAIT_HEADERS) {
315       u16_t total_header_len;
316       err_t err = http_wait_headers(req->rx_hdrs, &req->hdr_content_len, &total_header_len);
317       if (err == ERR_OK) {
318         struct pbuf *q;
319         /* full header received, send window update for header bytes and call into client callback */
320         altcp_recved(pcb, total_header_len);
321         if (req->conn_settings) {
322           if (req->conn_settings->headers_done_fn) {
323             err = req->conn_settings->headers_done_fn(req, req->callback_arg, req->rx_hdrs, total_header_len, req->hdr_content_len);
324             if (err != ERR_OK) {
325               return httpc_close(req, HTTPC_RESULT_LOCAL_ABORT, req->rx_status, err);
326             }
327           }
328         }
329         /* hide header bytes in pbuf */
330         q = pbuf_free_header(req->rx_hdrs, total_header_len);
331         p = q;
332         req->rx_hdrs = NULL;
333         /* go on with data */
334         req->parse_state = HTTPC_PARSE_RX_DATA;
335       }
336     }
337   }
338   if ((p != NULL) && (req->parse_state == HTTPC_PARSE_RX_DATA)) {
339     req->rx_content_len += p->tot_len;
340     /* received valid data: reset timeout */
341     req->timeout_ticks = HTTPC_POLL_TIMEOUT;
342     if (req->recv_fn != NULL) {
343       /* directly return here: the connection might already be aborted from the callback! */
344       return req->recv_fn(req->callback_arg, pcb, p, r);
345     } else {
346       altcp_recved(pcb, p->tot_len);
347       pbuf_free(p);
348     }
349   }
350   return ERR_OK;
351 }
352 
353 /** http client tcp err callback */
354 static void
httpc_tcp_err(void * arg,err_t err)355 httpc_tcp_err(void *arg, err_t err)
356 {
357   httpc_state_t* req = (httpc_state_t*)arg;
358   if (req != NULL) {
359     /* pcb has already been deallocated */
360     req->pcb = NULL;
361     httpc_close(req, HTTPC_RESULT_ERR_CLOSED, 0, err);
362   }
363 }
364 
365 /** http client tcp poll callback */
366 static err_t
httpc_tcp_poll(void * arg,struct altcp_pcb * pcb)367 httpc_tcp_poll(void *arg, struct altcp_pcb *pcb)
368 {
369   /* implement timeout */
370   httpc_state_t* req = (httpc_state_t*)arg;
371   LWIP_UNUSED_ARG(pcb);
372   if (req != NULL) {
373     if (req->timeout_ticks) {
374       req->timeout_ticks--;
375     }
376     if (!req->timeout_ticks) {
377       return httpc_close(req, HTTPC_RESULT_ERR_TIMEOUT, 0, ERR_OK);
378     }
379   }
380   return ERR_OK;
381 }
382 
383 /** http client tcp sent callback */
384 static err_t
httpc_tcp_sent(void * arg,struct altcp_pcb * pcb,u16_t len)385 httpc_tcp_sent(void *arg, struct altcp_pcb *pcb, u16_t len)
386 {
387   /* nothing to do here for now */
388   LWIP_UNUSED_ARG(arg);
389   LWIP_UNUSED_ARG(pcb);
390   LWIP_UNUSED_ARG(len);
391   return ERR_OK;
392 }
393 
394 /** http client tcp connected callback */
395 static err_t
httpc_tcp_connected(void * arg,struct altcp_pcb * pcb,err_t err)396 httpc_tcp_connected(void *arg, struct altcp_pcb *pcb, err_t err)
397 {
398   err_t r;
399   httpc_state_t* req = (httpc_state_t*)arg;
400   LWIP_UNUSED_ARG(pcb);
401   LWIP_UNUSED_ARG(err);
402 
403   /* send request; last char is zero termination */
404   r = altcp_write(req->pcb, req->request->payload, req->request->len - 1, TCP_WRITE_FLAG_COPY);
405   if (r != ERR_OK) {
406      /* could not write the single small request -> fail, don't retry */
407      return httpc_close(req, HTTPC_RESULT_ERR_MEM, 0, r);
408   }
409   /* everything written, we can free the request */
410   pbuf_free(req->request);
411   req->request = NULL;
412 
413   altcp_output(req->pcb);
414   return ERR_OK;
415 }
416 
417 /** Start the http request when the server IP addr is known */
418 static err_t
httpc_get_internal_addr(httpc_state_t * req,const ip_addr_t * ipaddr)419 httpc_get_internal_addr(httpc_state_t* req, const ip_addr_t *ipaddr)
420 {
421   err_t err;
422   LWIP_ASSERT("req != NULL", req != NULL);
423 
424   if (&req->remote_addr != ipaddr) {
425     /* fill in remote addr if called externally */
426     req->remote_addr = *ipaddr;
427   }
428 
429   err = altcp_connect(req->pcb, &req->remote_addr, req->remote_port, httpc_tcp_connected);
430   if (err == ERR_OK) {
431     return ERR_OK;
432   }
433   LWIP_DEBUGF(HTTPC_DEBUG_WARN_STATE, ("tcp_connect failed: %d\n", (int)err));
434   return err;
435 }
436 
437 #if LWIP_DNS
438 /** DNS callback
439  * If ipaddr is non-NULL, resolving succeeded and the request can be sent, otherwise it failed.
440  */
441 static void
httpc_dns_found(const char * hostname,const ip_addr_t * ipaddr,void * arg)442 httpc_dns_found(const char* hostname, const ip_addr_t *ipaddr, void *arg)
443 {
444   httpc_state_t* req = (httpc_state_t*)arg;
445   err_t err;
446   httpc_result_t result;
447 
448   LWIP_UNUSED_ARG(hostname);
449 
450   if (ipaddr != NULL) {
451     err = httpc_get_internal_addr(req, ipaddr);
452     if (err == ERR_OK) {
453       return;
454     }
455     result = HTTPC_RESULT_ERR_CONNECT;
456   } else {
457     LWIP_DEBUGF(HTTPC_DEBUG_WARN_STATE, ("httpc_dns_found: failed to resolve hostname: %s\n",
458       hostname));
459     result = HTTPC_RESULT_ERR_HOSTNAME;
460     err = ERR_ARG;
461   }
462   httpc_close(req, result, 0, err);
463 }
464 #endif /* LWIP_DNS */
465 
466 /** Start the http request after converting 'server_name' to ip address (DNS or address string) */
467 static err_t
httpc_get_internal_dns(httpc_state_t * req,const char * server_name)468 httpc_get_internal_dns(httpc_state_t* req, const char* server_name)
469 {
470   err_t err;
471   LWIP_ASSERT("req != NULL", req != NULL);
472 
473 #if LWIP_DNS
474   err = dns_gethostbyname(server_name, &req->remote_addr, httpc_dns_found, req);
475 #else
476   err = ipaddr_aton(server_name, &req->remote_addr) ? ERR_OK : ERR_ARG;
477 #endif
478 
479   if (err == ERR_OK) {
480     /* cached or IP-string */
481     err = httpc_get_internal_addr(req, &req->remote_addr);
482   } else if (err == ERR_INPROGRESS) {
483     return ERR_OK;
484   }
485   return err;
486 }
487 
488 static int
httpc_create_request_string(const httpc_connection_t * settings,const char * server_name,int server_port,const char * uri,int use_host,char * buffer,size_t buffer_size)489 httpc_create_request_string(const httpc_connection_t *settings, const char* server_name, int server_port, const char* uri,
490                             int use_host, char *buffer, size_t buffer_size)
491 {
492   if (settings->use_proxy) {
493     LWIP_ASSERT("server_name != NULL", server_name != NULL);
494     if (server_port != HTTP_DEFAULT_PORT) {
495       return snprintf(buffer, buffer_size, HTTPC_REQ_11_PROXY_PORT_FORMAT(server_name, server_port, uri, server_name));
496     } else {
497       return snprintf(buffer, buffer_size, HTTPC_REQ_11_PROXY_FORMAT(server_name, uri, server_name));
498     }
499   } else if (use_host) {
500     LWIP_ASSERT("server_name != NULL", server_name != NULL);
501     return snprintf(buffer, buffer_size, HTTPC_REQ_11_HOST_FORMAT(uri, server_name));
502   } else {
503     return snprintf(buffer, buffer_size, HTTPC_REQ_11_FORMAT(uri));
504   }
505 }
506 
507 /** Initialize the connection struct */
508 static err_t
httpc_init_connection_common(httpc_state_t ** connection,const httpc_connection_t * settings,const char * server_name,u16_t server_port,const char * uri,altcp_recv_fn recv_fn,void * callback_arg,int use_host)509 httpc_init_connection_common(httpc_state_t **connection, const httpc_connection_t *settings, const char* server_name,
510                       u16_t server_port, const char* uri, altcp_recv_fn recv_fn, void* callback_arg, int use_host)
511 {
512   size_t alloc_len;
513   mem_size_t mem_alloc_len;
514   int req_len, req_len2;
515   httpc_state_t *req;
516 #if HTTPC_DEBUG_REQUEST
517   size_t server_name_len, uri_len;
518 #endif
519 
520   LWIP_ASSERT("uri != NULL", uri != NULL);
521 
522   /* get request len */
523   req_len = httpc_create_request_string(settings, server_name, server_port, uri, use_host, NULL, 0);
524   if ((req_len < 0) || (req_len > 0xFFFF)) {
525     return ERR_VAL;
526   }
527   /* alloc state and request in one block */
528   alloc_len = sizeof(httpc_state_t);
529 #if HTTPC_DEBUG_REQUEST
530   server_name_len = server_name ? strlen(server_name) : 0;
531   uri_len = strlen(uri);
532   alloc_len += server_name_len + 1 + uri_len + 1;
533 #endif
534   mem_alloc_len = (mem_size_t)alloc_len;
535   if ((mem_alloc_len < alloc_len) || (req_len + 1 > 0xFFFF)) {
536     return ERR_VAL;
537   }
538 
539   req = (httpc_state_t*)mem_malloc((mem_size_t)alloc_len);
540   if(req == NULL) {
541     return ERR_MEM;
542   }
543   memset(req, 0, sizeof(httpc_state_t));
544   req->timeout_ticks = HTTPC_POLL_TIMEOUT;
545   req->request = pbuf_alloc(PBUF_RAW, (u16_t)(req_len + 1), PBUF_RAM);
546   if (req->request == NULL) {
547     httpc_free_state(req);
548     return ERR_MEM;
549   }
550   if (req->request->next != NULL) {
551     /* need a pbuf in one piece */
552     httpc_free_state(req);
553     return ERR_MEM;
554   }
555   req->hdr_content_len = HTTPC_CONTENT_LEN_INVALID;
556 #if HTTPC_DEBUG_REQUEST
557   req->server_name = (char*)(req + 1);
558   if (server_name) {
559     memcpy(req->server_name, server_name, server_name_len + 1);
560   }
561   req->uri = req->server_name + server_name_len + 1;
562   memcpy(req->uri, uri, uri_len + 1);
563 #endif
564   req->pcb = altcp_new(settings->altcp_allocator);
565   if(req->pcb == NULL) {
566     httpc_free_state(req);
567     return ERR_MEM;
568   }
569   req->remote_port = settings->use_proxy ? settings->proxy_port : server_port;
570   altcp_arg(req->pcb, req);
571   altcp_recv(req->pcb, httpc_tcp_recv);
572   altcp_err(req->pcb, httpc_tcp_err);
573   altcp_poll(req->pcb, httpc_tcp_poll, HTTPC_POLL_INTERVAL);
574   altcp_sent(req->pcb, httpc_tcp_sent);
575 
576   /* set up request buffer */
577   req_len2 = httpc_create_request_string(settings, server_name, server_port, uri, use_host,
578     (char *)req->request->payload, req_len + 1);
579   if (req_len2 != req_len) {
580     httpc_free_state(req);
581     return ERR_VAL;
582   }
583 
584   req->recv_fn = recv_fn;
585   req->conn_settings = settings;
586   req->callback_arg = callback_arg;
587 
588   *connection = req;
589   return ERR_OK;
590 }
591 
592 /**
593  * Initialize the connection struct
594  */
595 static err_t
httpc_init_connection(httpc_state_t ** connection,const httpc_connection_t * settings,const char * server_name,u16_t server_port,const char * uri,altcp_recv_fn recv_fn,void * callback_arg)596 httpc_init_connection(httpc_state_t **connection, const httpc_connection_t *settings, const char* server_name,
597                       u16_t server_port, const char* uri, altcp_recv_fn recv_fn, void* callback_arg)
598 {
599   return httpc_init_connection_common(connection, settings, server_name, server_port, uri, recv_fn, callback_arg, 1);
600 }
601 
602 
603 /**
604  * Initialize the connection struct (from IP address)
605  */
606 static err_t
httpc_init_connection_addr(httpc_state_t ** connection,const httpc_connection_t * settings,const ip_addr_t * server_addr,u16_t server_port,const char * uri,altcp_recv_fn recv_fn,void * callback_arg)607 httpc_init_connection_addr(httpc_state_t **connection, const httpc_connection_t *settings,
608                            const ip_addr_t* server_addr, u16_t server_port, const char* uri,
609                            altcp_recv_fn recv_fn, void* callback_arg)
610 {
611   char *server_addr_str = ipaddr_ntoa(server_addr);
612   if (server_addr_str == NULL) {
613     return ERR_VAL;
614   }
615   return httpc_init_connection_common(connection, settings, server_addr_str, server_port, uri,
616     recv_fn, callback_arg, 1);
617 }
618 
619 /**
620  * @ingroup httpc
621  * HTTP client API: get a file by passing server IP address
622  *
623  * @param server_addr IP address of the server to connect
624  * @param port tcp port of the server
625  * @param uri uri to get from the server, remember leading "/"!
626  * @param settings connection settings (callbacks, proxy, etc.)
627  * @param recv_fn the http body (not the headers) are passed to this callback
628  * @param callback_arg argument passed to all the callbacks
629  * @param connection retreives the connection handle (to match in callbacks)
630  * @return ERR_OK if starting the request succeeds (callback_fn will be called later)
631  *         or an error code
632  */
633 err_t
httpc_get_file(const ip_addr_t * server_addr,u16_t port,const char * uri,const httpc_connection_t * settings,altcp_recv_fn recv_fn,void * callback_arg,httpc_state_t ** connection)634 httpc_get_file(const ip_addr_t* server_addr, u16_t port, const char* uri, const httpc_connection_t *settings,
635                altcp_recv_fn recv_fn, void* callback_arg, httpc_state_t **connection)
636 {
637   err_t err;
638   httpc_state_t* req;
639 
640   LWIP_ERROR("invalid parameters", (server_addr != NULL) && (uri != NULL) && (recv_fn != NULL), return ERR_ARG;);
641 
642   err = httpc_init_connection_addr(&req, settings, server_addr, port,
643     uri, recv_fn, callback_arg);
644   if (err != ERR_OK) {
645     return err;
646   }
647 
648   if (settings->use_proxy) {
649     err = httpc_get_internal_addr(req, &settings->proxy_addr);
650   } else {
651     err = httpc_get_internal_addr(req, server_addr);
652   }
653   if(err != ERR_OK) {
654     httpc_free_state(req);
655     return err;
656   }
657 
658   if (connection != NULL) {
659     *connection = req;
660   }
661   return ERR_OK;
662 }
663 
664 /**
665  * @ingroup httpc
666  * HTTP client API: get a file by passing server name as string (DNS name or IP address string)
667  *
668  * @param server_name server name as string (DNS name or IP address string)
669  * @param port tcp port of the server
670  * @param uri uri to get from the server, remember leading "/"!
671  * @param settings connection settings (callbacks, proxy, etc.)
672  * @param recv_fn the http body (not the headers) are passed to this callback
673  * @param callback_arg argument passed to all the callbacks
674  * @param connection retreives the connection handle (to match in callbacks)
675  * @return ERR_OK if starting the request succeeds (callback_fn will be called later)
676  *         or an error code
677  */
678 err_t
httpc_get_file_dns(const char * server_name,u16_t port,const char * uri,const httpc_connection_t * settings,altcp_recv_fn recv_fn,void * callback_arg,httpc_state_t ** connection)679 httpc_get_file_dns(const char* server_name, u16_t port, const char* uri, const httpc_connection_t *settings,
680                    altcp_recv_fn recv_fn, void* callback_arg, httpc_state_t **connection)
681 {
682   err_t err;
683   httpc_state_t* req;
684 
685   LWIP_ERROR("invalid parameters", (server_name != NULL) && (uri != NULL) && (recv_fn != NULL), return ERR_ARG;);
686 
687   err = httpc_init_connection(&req, settings, server_name, port, uri, recv_fn, callback_arg);
688   if (err != ERR_OK) {
689     return err;
690   }
691 
692   if (settings->use_proxy) {
693     err = httpc_get_internal_addr(req, &settings->proxy_addr);
694   } else {
695     err = httpc_get_internal_dns(req, server_name);
696   }
697   if(err != ERR_OK) {
698     httpc_free_state(req);
699     return err;
700   }
701 
702   if (connection != NULL) {
703     *connection = req;
704   }
705   return ERR_OK;
706 }
707 
708 #if LWIP_HTTPC_HAVE_FILE_IO
709 /* Implementation to disk via fopen/fwrite/fclose follows */
710 
711 typedef struct _httpc_filestate
712 {
713   const char* local_file_name;
714   FILE *file;
715   httpc_connection_t settings;
716   const httpc_connection_t *client_settings;
717   void *callback_arg;
718 } httpc_filestate_t;
719 
720 static void httpc_fs_result(void *arg, httpc_result_t httpc_result, u32_t rx_content_len,
721   u32_t srv_res, err_t err);
722 
723 /** Initialize http client state for download to file system */
724 static err_t
httpc_fs_init(httpc_filestate_t ** filestate_out,const char * local_file_name,const httpc_connection_t * settings,void * callback_arg)725 httpc_fs_init(httpc_filestate_t **filestate_out, const char* local_file_name,
726               const httpc_connection_t *settings, void* callback_arg)
727 {
728   httpc_filestate_t *filestate;
729   size_t file_len, alloc_len;
730   FILE *f;
731 
732   file_len = strlen(local_file_name);
733   alloc_len = sizeof(httpc_filestate_t) + file_len + 1;
734 
735   filestate = (httpc_filestate_t *)mem_malloc((mem_size_t)alloc_len);
736   if (filestate == NULL) {
737     return ERR_MEM;
738   }
739   memset(filestate, 0, sizeof(httpc_filestate_t));
740   filestate->local_file_name = (const char *)(filestate + 1);
741   memcpy((char *)(filestate + 1), local_file_name, file_len + 1);
742   filestate->file = NULL;
743   filestate->client_settings = settings;
744   filestate->callback_arg = callback_arg;
745   /* copy client settings but override result callback */
746   memcpy(&filestate->settings, settings, sizeof(httpc_connection_t));
747   filestate->settings.result_fn = httpc_fs_result;
748 
749   f = fopen(local_file_name, "wb");
750   if(f == NULL) {
751     /* could not open file */
752     mem_free(filestate);
753     return ERR_VAL;
754   }
755   filestate->file = f;
756   *filestate_out = filestate;
757   return ERR_OK;
758 }
759 
760 /** Free http client state for download to file system */
761 static void
httpc_fs_free(httpc_filestate_t * filestate)762 httpc_fs_free(httpc_filestate_t *filestate)
763 {
764   if (filestate != NULL) {
765     if (filestate->file != NULL) {
766       fclose(filestate->file);
767       filestate->file = NULL;
768     }
769     mem_free(filestate);
770   }
771 }
772 
773 /** Connection closed (success or error) */
774 static void
httpc_fs_result(void * arg,httpc_result_t httpc_result,u32_t rx_content_len,u32_t srv_res,err_t err)775 httpc_fs_result(void *arg, httpc_result_t httpc_result, u32_t rx_content_len,
776                 u32_t srv_res, err_t err)
777 {
778   httpc_filestate_t *filestate = (httpc_filestate_t *)arg;
779   if (filestate != NULL) {
780     if (filestate->client_settings->result_fn != NULL) {
781       filestate->client_settings->result_fn(filestate->callback_arg, httpc_result, rx_content_len,
782         srv_res, err);
783     }
784     httpc_fs_free(filestate);
785   }
786 }
787 
788 /** tcp recv callback */
789 static err_t
httpc_fs_tcp_recv(void * arg,struct altcp_pcb * pcb,struct pbuf * p,err_t err)790 httpc_fs_tcp_recv(void *arg, struct altcp_pcb *pcb, struct pbuf *p, err_t err)
791 {
792   httpc_filestate_t *filestate = (httpc_filestate_t*)arg;
793   struct pbuf* q;
794   LWIP_UNUSED_ARG(err);
795 
796   LWIP_ASSERT("p != NULL", p != NULL);
797 
798   for (q = p; q != NULL; q = q->next) {
799     fwrite(q->payload, 1, q->len, filestate->file);
800   }
801   altcp_recved(pcb, p->tot_len);
802   pbuf_free(p);
803   return ERR_OK;
804 }
805 
806 /**
807  * @ingroup httpc
808  * HTTP client API: get a file to disk by passing server IP address
809  *
810  * @param server_addr IP address of the server to connect
811  * @param port tcp port of the server
812  * @param uri uri to get from the server, remember leading "/"!
813  * @param settings connection settings (callbacks, proxy, etc.)
814  * @param callback_arg argument passed to all the callbacks
815  * @param connection retreives the connection handle (to match in callbacks)
816  * @return ERR_OK if starting the request succeeds (callback_fn will be called later)
817  *         or an error code
818  */
819 err_t
httpc_get_file_to_disk(const ip_addr_t * server_addr,u16_t port,const char * uri,const httpc_connection_t * settings,void * callback_arg,const char * local_file_name,httpc_state_t ** connection)820 httpc_get_file_to_disk(const ip_addr_t* server_addr, u16_t port, const char* uri, const httpc_connection_t *settings,
821                        void* callback_arg, const char* local_file_name, httpc_state_t **connection)
822 {
823   err_t err;
824   httpc_state_t* req;
825   httpc_filestate_t *filestate;
826 
827   LWIP_ERROR("invalid parameters", (server_addr != NULL) && (uri != NULL) && (local_file_name != NULL), return ERR_ARG;);
828 
829   err = httpc_fs_init(&filestate, local_file_name, settings, callback_arg);
830   if (err != ERR_OK) {
831     return err;
832   }
833 
834   err = httpc_init_connection_addr(&req, &filestate->settings, server_addr, port,
835     uri, httpc_fs_tcp_recv, filestate);
836   if (err != ERR_OK) {
837     httpc_fs_free(filestate);
838     return err;
839   }
840 
841   if (settings->use_proxy) {
842     err = httpc_get_internal_addr(req, &settings->proxy_addr);
843   } else {
844     err = httpc_get_internal_addr(req, server_addr);
845   }
846   if(err != ERR_OK) {
847     httpc_fs_free(filestate);
848     httpc_free_state(req);
849     return err;
850   }
851 
852   if (connection != NULL) {
853     *connection = req;
854   }
855   return ERR_OK;
856 }
857 
858 /**
859  * @ingroup httpc
860  * HTTP client API: get a file to disk by passing server name as string (DNS name or IP address string)
861  *
862  * @param server_name server name as string (DNS name or IP address string)
863  * @param port tcp port of the server
864  * @param uri uri to get from the server, remember leading "/"!
865  * @param settings connection settings (callbacks, proxy, etc.)
866  * @param callback_arg argument passed to all the callbacks
867  * @param connection retreives the connection handle (to match in callbacks)
868  * @return ERR_OK if starting the request succeeds (callback_fn will be called later)
869  *         or an error code
870  */
871 err_t
httpc_get_file_dns_to_disk(const char * server_name,u16_t port,const char * uri,const httpc_connection_t * settings,void * callback_arg,const char * local_file_name,httpc_state_t ** connection)872 httpc_get_file_dns_to_disk(const char* server_name, u16_t port, const char* uri, const httpc_connection_t *settings,
873                            void* callback_arg, const char* local_file_name, httpc_state_t **connection)
874 {
875   err_t err;
876   httpc_state_t* req;
877   httpc_filestate_t *filestate;
878 
879   LWIP_ERROR("invalid parameters", (server_name != NULL) && (uri != NULL) && (local_file_name != NULL), return ERR_ARG;);
880 
881   err = httpc_fs_init(&filestate, local_file_name, settings, callback_arg);
882   if (err != ERR_OK) {
883     return err;
884   }
885 
886   err = httpc_init_connection(&req, &filestate->settings, server_name, port,
887     uri, httpc_fs_tcp_recv, filestate);
888   if (err != ERR_OK) {
889     httpc_fs_free(filestate);
890     return err;
891   }
892 
893   if (settings->use_proxy) {
894     err = httpc_get_internal_addr(req, &settings->proxy_addr);
895   } else {
896     err = httpc_get_internal_dns(req, server_name);
897   }
898   if(err != ERR_OK) {
899     httpc_fs_free(filestate);
900     httpc_free_state(req);
901     return err;
902   }
903 
904   if (connection != NULL) {
905     *connection = req;
906   }
907   return ERR_OK;
908 }
909 #endif /* LWIP_HTTPC_HAVE_FILE_IO */
910 
911 #endif /* LWIP_TCP && LWIP_CALLBACK_API */
912