xref: /btstack/example/pan_lwip_http_server.c (revision 6897da5c53aac5b1f90f41b5b15d0bd43d61dfff)
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 BLUEKITCHEN
24  * GMBH 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 - lwIP HTTP and DHCP Server
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 defined(LWIP_HTTPD_CUSTOM_FILES) && defined(LWIP_HTTPD_DYNAMIC_HEADERS)
75 #define ENABLE_TEST_FILE_DOWNLOAD
76 #else
77 #warning "Test file download requires LWIP_HTTPD_CUSTOM_FILES and LWIP_HTTPD_DYNAMIC_HEADERS to be defined. Not supported currently."
78 #endif
79 
80 // network types
81 #define NETWORK_TYPE_IPv4       0x0800
82 #define NETWORK_TYPE_ARP        0x0806
83 #define NETWORK_TYPE_IPv6       0x86DD
84 
85 static uint8_t pan_sdp_record[220];
86 
87 static btstack_packet_callback_registration_t hci_event_callback_registration;
88 
89 /*
90  * @section Packet Handler
91  *
92  * @text All BNEP events are handled in the platform/bnep_lwip.c BNEP-LWIP Adapter.
93  *       Here, we only print status information and handle pairing requests.
94  */
95 
96 /* LISTING_START(packetHandler): Packet Handler */
97 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
98     /* LISTING_PAUSE */
99     UNUSED(channel);
100     UNUSED(size);
101 
102     bd_addr_t event_addr;
103 
104     switch (packet_type) {
105         case HCI_EVENT_PACKET:
106             switch (hci_event_packet_get_type(packet)) {
107 
108                 case HCI_EVENT_PIN_CODE_REQUEST:
109                     // inform about pin code request
110                     printf("Pin code request - using '0000'\n");
111                     hci_event_pin_code_request_get_bd_addr(packet, event_addr);
112                     gap_pin_code_response(event_addr, "0000");
113                     break;
114 
115                 case HCI_EVENT_USER_CONFIRMATION_REQUEST:
116                     // inform about user confirmation request
117                     printf("SSP User Confirmation Auto accept\n");
118                     hci_event_user_confirmation_request_get_bd_addr(packet, event_addr);
119                     break;
120 
121                 /* @text BNEP_EVENT_CHANNEL_OPENED is received after a BNEP connection was established or
122                  * or when the connection fails. The status field returns the error code.
123                  */
124                 case BNEP_EVENT_CHANNEL_OPENED:
125                     if (bnep_event_channel_opened_get_status(packet)) {
126                         printf("BNEP channel open failed, status 0x%02x\n", bnep_event_channel_opened_get_status(packet));
127                     } else {
128                         uint16_t uuid_source = bnep_event_channel_opened_get_source_uuid(packet);
129                         uint16_t uuid_dest   = bnep_event_channel_opened_get_destination_uuid(packet);
130                         uint16_t mtu         = bnep_event_channel_opened_get_mtu(packet);
131                         bnep_event_channel_opened_get_remote_address(packet, event_addr);
132                         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);
133                         printf("Please open 'http://192.168.7.1' in your web browser: \n");
134                     }
135                     break;
136 
137                 /* @text BNEP_EVENT_CHANNEL_CLOSED is received when the connection gets closed.
138                  */
139                 case BNEP_EVENT_CHANNEL_CLOSED:
140                     printf("BNEP channel closed\n");
141                     break;
142 
143                 default:
144                     break;
145             }
146             break;
147         default:
148             break;
149     }
150 }
151 /* LISTING_END */
152 
153 /* @section PAN BNEP Setup
154  *
155  * @text Listing PanBnepSetup shows the setup of the PAN setup
156  */
157 
158 /* LISTING_START(PanBnepSetup): Configure GAP, register PAN NAP servier, register PAN NA SDP record. */
159 static void pan_bnep_setup(void){
160 
161     // Discoverable
162     // Set local name with a template Bluetooth address, that will be automatically
163     // replaced with a actual address once it is available, i.e. when BTstack boots
164     // up and starts talking to a Bluetooth module.
165     gap_set_local_name("PAN HTTP 00:00:00:00:00:00");
166     gap_discoverable_control(1);
167 
168     // Major: Networking Device, Minor: Networ Access Point
169     gap_set_class_of_device(0x20300);
170 
171     // register for HCI events
172     hci_event_callback_registration.callback = &packet_handler;
173     hci_add_event_handler(&hci_event_callback_registration);
174 
175     // Initialize L2CAP
176     l2cap_init();
177 
178 #ifdef ENABLE_BLE
179     // Initialize LE Security Manager. Needed for cross-transport key derivation
180     sm_init();
181 #endif
182 
183     // Initialize BNEP
184     bnep_init();
185 
186     // Init SDP
187     sdp_init();
188     memset(pan_sdp_record, 0, sizeof(pan_sdp_record));
189     uint16_t network_packet_types[] = { NETWORK_TYPE_IPv4, NETWORK_TYPE_ARP, 0};    // 0 as end of list
190 
191     // NAP Network Access Type: Other, 1 MB/s
192     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);
193     btstack_assert(de_get_len( pan_sdp_record) <= sizeof(pan_sdp_record));
194     sdp_register_service(pan_sdp_record);
195 
196     // Init BNEP lwIP Adapter
197     bnep_lwip_init();
198 
199     // Setup NAP Service via BENP lwIP adapter
200     bnep_lwip_register_service(BLUETOOTH_SERVICE_CLASS_NAP, 1691);
201 
202     // register callback - to print state
203     bnep_lwip_register_packet_handler(packet_handler);
204 }
205 /* LISTING_END */
206 
207 
208 /* @section DHCP Server Configuration
209  *
210  * @text Listing DhcpSetup shows the DHCP Server configuration for network 192.168.7.0/8
211  */
212 
213 /* LISTING_START(DhcpSetup): Setup DHCP Server with 3 entries for 192.168.7.0/8. */
214 
215 #define NUM_DHCP_ENTRY 3
216 
217 static dhcp_entry_t entries[NUM_DHCP_ENTRY] =
218 {
219     /* mac    ip address        subnet mask        lease time */
220     { {0}, {192, 168, 7, 2}, {255, 255, 255, 0}, 24 * 60 * 60 },
221     { {0}, {192, 168, 7, 3}, {255, 255, 255, 0}, 24 * 60 * 60 },
222     { {0}, {192, 168, 7, 4}, {255, 255, 255, 0}, 24 * 60 * 60 }
223 };
224 
225 static dhcp_config_t dhcp_config =
226 {
227     {192, 168, 7, 1}, 67, /* server address, port */
228     {0, 0, 0, 0},         /* dns server */
229     NULL,                /* dns suffix */
230     NUM_DHCP_ENTRY,       /* num entry */
231     entries               /* entries */
232 };
233 /* LISTING_END */
234 
235 #ifdef ENABLE_TEST_FILE_DOWNLOAD
236 
237 /* @section Large File Download
238  *
239  * @text Listing LargeFile Shows how a configurable test file for performance tests is generated on the fly.
240  *       The filename is the number of bytes to generate, e.g. /1048576.txt results in a 1MB file.
241  */
242 
243 /* LISTING_START(LargeFile): Provide large file. */
244 
245 int fs_open_custom(struct fs_file *file, const char *name);
246 int fs_open_custom(struct fs_file *file, const char *name){
247     if (*name != '/') return 0;
248     uint32_t file_size = btstack_atoi(&name[1]);
249     if (file_size > 0) {
250         printf("Serving '%s' with %"PRIu32" bytes\n", name, file_size);
251         /* initialize fs_file correctly */
252         memset(file, 0, sizeof(struct fs_file));
253         file->len = file_size;
254         file->index = 0;
255         file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
256         return 1;
257     }
258     return 0;
259 }
260 
261 static uint16_t cgi_buffer_fill(char * cgi_buffer, uint16_t cgi_buffer_size, uint32_t start_pos){
262     // fill buffer with dots
263     memset(cgi_buffer, (uint8_t) '.', cgi_buffer_size);
264     uint16_t cursor = 10;
265     uint16_t pos = 0;
266     const uint16_t line_length = 64;
267 
268     while  ((pos + line_length ) < cgi_buffer_size){
269         // write position
270         sprintf((char *) &cgi_buffer[pos], "%08"PRIx32, start_pos + pos);
271         cgi_buffer[pos + 8] = '-';
272         // cursor
273         cgi_buffer[pos+cursor] = '+';
274         cursor++;
275         // new line
276         cgi_buffer[pos+line_length-1] = '\n';
277         pos += line_length;
278     }
279 
280     // handle last incomplete line
281     if (pos == 0){
282         const char * last_line_text = "Thank you for evaluating BTstack!";
283         uint16_t bytes_to_copy = btstack_min(strlen(last_line_text), cgi_buffer_size);
284         memcpy(cgi_buffer, last_line_text, bytes_to_copy);
285         pos = cgi_buffer_size;
286     }
287 
288     return pos;
289 }
290 
291 int fs_read_custom(struct fs_file *file, char *buffer, int count);
292 int fs_read_custom(struct fs_file *file, char *buffer, int count)
293 {
294     uint32_t remaining_data = file->len - file->index;
295     if (remaining_data == 0) {
296         // all bytes already read
297         return FS_READ_EOF;
298     }
299 
300     uint32_t bytes_to_fill = remaining_data;
301     if (bytes_to_fill > (uint32_t) count){
302         bytes_to_fill = count;
303     }
304 
305     uint32_t bytes_written = cgi_buffer_fill(buffer, bytes_to_fill, file->index);
306     file->index += bytes_written;
307 
308     return bytes_written;
309 }
310 
311 void fs_close_custom(struct fs_file *file);
312 void fs_close_custom(struct fs_file *file){
313     UNUSED(file);
314 }
315 #endif
316 /* LISTING_END */
317 
318 /* @section DHCP Server Setup
319  *
320  * @text Listing LwipSetup shows the setup of the lwIP network stack and starts the DHCP Server
321  */
322 
323 /* LISTING_START(LwipSetup): Report lwIP version, init lwIP, start DHCP Serverr */
324 
325 static void network_setup(void){
326     printf("lwIP version: " LWIP_VERSION_STRING "\n");
327 
328 #if BYTE_ORDER == LITTLE_ENDIAN
329     // big endian detection not supported by build configuration
330     if (btstack_is_big_endian()){
331         printf("lwIP configured for little endian, but running on big endian. Please set BYTE_ORDER to BIG_ENDIAN in lwiopts.h\n");
332         while (1);
333     }
334 #endif
335 
336 #ifndef HAVE_LWIP
337     // init lwIP stack
338 #if NO_SYS
339     lwip_init();
340 #else
341     tcpip_init(NULL, NULL);
342 #endif
343 #endif
344 
345     // start DHCP Server
346     dhserv_init(&dhcp_config);
347 
348     // start HTTP Server
349     httpd_init();
350 }
351 /* LISTING_END */
352 
353 
354 /* @section Main
355  *
356  * @text Setup the lwIP network and PAN NAP
357  */
358 
359 /* LISTING_START(Main): Setup lwIP network and PAN NAP */
360 int btstack_main(int argc, const char * argv[]);
361 int btstack_main(int argc, const char * argv[]){
362 
363     (void)argc;
364     (void)argv;
365 
366     // setup lwIP, HTTP, DHCP
367     network_setup();
368 
369     // setup Classic PAN NAP Service
370     pan_bnep_setup();
371 
372     // Turn on the device
373     hci_power_control(HCI_POWER_ON);
374     return 0;
375 }
376 /* LISTING_END */
377 
378 /* EXAMPLE_END */
379