xref: /btstack/example/pan_lwip_http_server.c (revision d58a1b5f11ada8ddf896c41fff5a35e7f140c37e)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define __BTSTACK_FILE__ "pan_lwip_http_server.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(pan_lwip_http_server): PAN - HTTP Server using lwIP
42  *
43  * @text Bluetooth PAN is mainly used for Internet Tethering, where e.g. a mobile
44  * phone provides internet connection to a laptop or a tablet.
45  *
46  * Instead of regular internet access, it's also possible to provide a Web app on a
47  * Bluetooth device, e.g. for configuration or maintenance. For some device,
48  * this can be a more effective way to provide an interface compared to dedicated
49  * smartphone applications (for Android and iOS).
50  *
51  * Before iOS 11, accessing an HTTP server via Bluetooth PAN was not supported on
52  * the iPhone, but on iPod and iPad. With iOS 11, this works as expected.
53  *
54  * After pairing your device, please open the URL http://192.168.7.1 in your web
55  * browser.
56 
57  */
58  // *****************************************************************************
59 
60 #include <stdio.h>
61 #include <inttypes.h>
62 
63 #include "btstack_config.h"
64 #include "bnep_lwip.h"
65 #include "btstack.h"
66 
67 #include "lwip/init.h"
68 #include "lwip/opt.h"
69 #include "lwip/tcpip.h"
70 #include "lwip/apps/fs.h"
71 #include "lwip/apps/httpd.h"
72 #include "dhserver.h"
73 
74 #if !LWIP_HTTPD_CUSTOM_FILES
75 #error This needs LWIP_HTTPD_CUSTOM_FILES
76 #endif
77 #if !LWIP_HTTPD_DYNAMIC_HEADERS
78 #error This needs LWIP_HTTPD_DYNAMIC_HEADERS
79 #endif
80 
81 // network types
82 #define NETWORK_TYPE_IPv4       0x0800
83 #define NETWORK_TYPE_ARP        0x0806
84 #define NETWORK_TYPE_IPv6       0x86DD
85 
86 static uint8_t pan_sdp_record[220];
87 
88 static btstack_packet_callback_registration_t hci_event_callback_registration;
89 
90 /*
91  * @section Packet Handler
92  *
93  * @text All BNEP events are handled in the platform/bnep_lwip.c BNEP-LWIP Adapter.
94  *       Here, we only print status information and handle pairing requests.
95  */
96 
97 /* LISTING_START(packetHandler): Packet Handler */
98 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
99     /* LISTING_PAUSE */
100     UNUSED(channel);
101     UNUSED(size);
102 
103     bd_addr_t event_addr;
104 
105     switch (packet_type) {
106         case HCI_EVENT_PACKET:
107             switch (hci_event_packet_get_type(packet)) {
108 
109                 case HCI_EVENT_PIN_CODE_REQUEST:
110                     // inform about pin code request
111                     printf("Pin code request - using '0000'\n");
112                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
113                     gap_pin_code_response(event_addr, "0000");
114                     break;
115 
116                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
117                     // inform about user confirmation request
118                     printf("SSP User Confirmation Auto accept\n");
119                     hci_event_user_confirmation_request_get_bd_addr(packet, event_addr);
120                     break;
121 
122                 /* @text BNEP_EVENT_CHANNEL_OPENED is received after a BNEP connection was established or
123                  * or when the connection fails. The status field returns the error code.
124                  */
125                 case BNEP_EVENT_CHANNEL_OPENED:
126                     if (bnep_event_channel_opened_get_status(packet)) {
127                         printf("BNEP channel open failed, status %02x\n", bnep_event_channel_opened_get_status(packet));
128                     } else {
129                         uint16_t uuid_source = bnep_event_channel_opened_get_source_uuid(packet);
130                         uint16_t uuid_dest   = bnep_event_channel_opened_get_destination_uuid(packet);
131                         uint16_t mtu         = bnep_event_channel_opened_get_mtu(packet);
132                         bnep_event_channel_opened_get_remote_address(packet, event_addr);
133                         printf("BNEP connection open succeeded to %s source UUID 0x%04x dest UUID: 0x%04x, max frame size %u\n", bd_addr_to_str(event_addr), uuid_source, uuid_dest, mtu);
134                         printf("Please open 'http://192.168.7.1' in your web browser: \n");
135                     }
136                     break;
137 
138                 /* @text BNEP_EVENT_CHANNEL_CLOSED is received when the connection gets closed.
139                  */
140                 case BNEP_EVENT_CHANNEL_CLOSED:
141                     printf("BNEP channel closed\n");
142                     break;
143 
144                 default:
145                     break;
146             }
147             break;
148         default:
149             break;
150     }
151 }
152 /* LISTING_END */
153 
154 /* @section PAN BNEP Setup
155  *
156  * @text Listing PanBnepSetup shows the setup of the PAN setup
157  */
158 
159 /* LISTING_START(PanBnepSetup): Configure GAP, register PAN NAP servier, register PAN NA SDP record. */
160 static void pan_bnep_setup(void){
161 
162     // Discoverable
163     // Set local name with a template Bluetooth address, that will be automatically
164     // replaced with a actual address once it is available, i.e. when BTstack boots
165     // up and starts talking to a Bluetooth module.
166     gap_set_local_name("PAN HTTP 00:00:00:00:00:00");
167     gap_discoverable_control(1);
168 
169     // register for HCI events
170     hci_event_callback_registration.callback = &packet_handler;
171     hci_add_event_handler(&hci_event_callback_registration);
172 
173     // Initialize L2CAP
174     l2cap_init();
175 
176     // Initialize BNEP
177     bnep_init();
178 
179     // Init SDP
180     sdp_init();
181     memset(pan_sdp_record, 0, sizeof(pan_sdp_record));
182     uint16_t network_packet_types[] = { NETWORK_TYPE_IPv4, NETWORK_TYPE_ARP, 0};    // 0 as end of list
183 
184     // NAP Network Access Type: Other, 1 MB/s
185     pan_create_nap_sdp_record(pan_sdp_record, sdp_create_service_record_handle(), network_packet_types, NULL, NULL, BNEP_SECURITY_NONE, PAN_NET_ACCESS_TYPE_OTHER, 1000000, NULL, NULL);
186     sdp_register_service(pan_sdp_record);
187     printf("SDP service record size: %u\n", de_get_len((uint8_t*) pan_sdp_record));
188 
189     // Init BNEP lwIP Adapter
190     bnep_lwip_init();
191 
192     // Setup NAP Service via BENP lwIP adapter
193     bnep_lwip_register_service(BLUETOOTH_SERVICE_CLASS_NAP, 1691);
194 
195     // register callback - to print state
196     bnep_lwip_register_packet_handler(packet_handler);
197 }
198 /* LISTING_END */
199 
200 
201 /* @section DHCP Server Configuration
202  *
203  * @text Listing DhcpSetup shows the DHCP Server configuration for network 192.168.7.0/8
204  */
205 
206 /* LISTING_START(DhcpSetup): Setup DHCP Server with 3 entries for 192.168.7.0/8. */
207 
208 #define NUM_DHCP_ENTRY 3
209 
210 static dhcp_entry_t entries[NUM_DHCP_ENTRY] =
211 {
212     /* mac    ip address        subnet mask        lease time */
213     { {0}, {192, 168, 7, 2}, {255, 255, 255, 0}, 24 * 60 * 60 },
214     { {0}, {192, 168, 7, 3}, {255, 255, 255, 0}, 24 * 60 * 60 },
215     { {0}, {192, 168, 7, 4}, {255, 255, 255, 0}, 24 * 60 * 60 }
216 };
217 
218 static dhcp_config_t dhcp_config =
219 {
220     {192, 168, 7, 1}, 67, /* server address, port */
221     {0, 0, 0, 0},         /* dns server */
222     NULL,                /* dns suffix */
223     NUM_DHCP_ENTRY,       /* num entry */
224     entries               /* entries */
225 };
226 /* LISTING_END */
227 
228 
229 /* @section Large File Download
230  *
231  * @text Listing LargeFile Shows how a configurable test file for performance tests is generated on the fly.
232  *       The filename is the number of bytes to generate, e.g. /1048576.txt results in a 1MB file.
233  */
234 
235 /* LISTING_START(LargeFile): Provide large file. */
236 
237 int fs_open_custom(struct fs_file *file, const char *name){
238     if (*name != '/') return 0;
239     uint32_t file_size = btstack_atoi(&name[1]);
240     if (file_size > 0) {
241         printf("Serving '%s' with %u bytes\n", name, file_size);
242         /* initialize fs_file correctly */
243         memset(file, 0, sizeof(struct fs_file));
244         file->len = file_size;
245         file->index = 0;
246         file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
247         return 1;
248     }
249     return 0;
250 }
251 
252 static uint16_t cgi_buffer_fill(char * cgi_buffer, uint16_t cgi_buffer_size, uint32_t start_pos){
253     // fill buffer with dots
254     memset(cgi_buffer, (uint8_t) '.', cgi_buffer_size);
255     uint16_t cursor = 10;
256     uint16_t pos = 0;
257     const uint16_t line_length = 64;
258 
259     while  ((pos + line_length ) < cgi_buffer_size){
260         // write position
261         sprintf((char *) &cgi_buffer[pos], "%08"PRIx32, start_pos + pos);
262         cgi_buffer[pos + 8] = '-';
263         // cursor
264         cgi_buffer[pos+cursor] = '+';
265         cursor++;
266         // new line
267         cgi_buffer[pos+line_length-1] = '\n';
268         pos += line_length;
269     }
270 
271     // handle last incomplete line
272     if (pos == 0){
273         const char * last_line_text = "Thank you for evaluating BTstack!";
274         uint16_t bytes_to_copy = btstack_min(strlen(last_line_text), cgi_buffer_size);
275         memcpy(cgi_buffer, last_line_text, bytes_to_copy);
276         pos = cgi_buffer_size;
277     }
278 
279     return pos;
280 }
281 
282 int fs_read_custom(struct fs_file *file, char *buffer, int count)
283 {
284     uint32_t remaining_data = file->len - file->index;
285     if (remaining_data == 0) {
286         // all bytes already read
287         return FS_READ_EOF;
288     }
289 
290     uint32_t bytes_to_fill = remaining_data;
291     if (bytes_to_fill > count){
292         bytes_to_fill = count;
293     }
294 
295     uint32_t bytes_written = cgi_buffer_fill(buffer, bytes_to_fill, file->index);
296     file->index += bytes_written;
297 
298     return bytes_written;
299 }
300 
301 void
302 fs_close_custom(struct fs_file *file){
303 }
304 
305 /* LISTING_END */
306 
307 /* @section DHCP Server Setup
308  *
309  * @text Listing LwipSetup shows the setup of the lwIP network stack and starts the DHCP Server
310  */
311 
312 /* LISTING_START(LwipSetup): Report lwIP version, init lwIP, start DHCP Serverr */
313 
314 static void network_setup(void){
315     printf("lwIP version: " LWIP_VERSION_STRING "\n");
316 
317 #if BYTE_ORDER == LITTLE_ENDIAN
318     // big endian detection not supported by build configuration
319     if (btstack_is_big_endian()){
320         printf("lwIP configured for little endian, but running on big endian. Please set BYTE_ORDER to BIG_ENDIAN in lwiopts.h\n");
321         while (1);
322     }
323 #endif
324 
325     // init lwIP stack
326 #if NO_SYS
327     lwip_init();
328 #else
329     tcpip_init(NULL, NULL);
330 #endif
331 
332     // start DHCP Server
333     dhserv_init(&dhcp_config);
334 
335     // start HTTP Server
336     httpd_init();
337 }
338 /* LISTING_END */
339 
340 
341 /* @section Main
342  *
343  * @text Setup the lwIP network and PAN NAP
344  */
345 
346 /* LISTING_START(Main): Setup lwIP network and PAN NAP */
347 int btstack_main(int argc, const char * argv[]);
348 int btstack_main(int argc, const char * argv[]){
349 
350     (void)argc;
351     (void)argv;
352 
353     // setup lwIP, HTTP, DHCP
354     network_setup();
355 
356     // setup Classic PAN NAP Service
357     pan_bnep_setup();
358 
359     // Turn on the device
360     hci_power_control(HCI_POWER_ON);
361     return 0;
362 }
363 /* LISTING_END */
364 
365 /* EXAMPLE_END */
366