xref: /btstack/example/pan_lwip_http_server.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
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 - 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 %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     // Initialize BNEP
179     bnep_init();
180 
181     // Init SDP
182     sdp_init();
183     memset(pan_sdp_record, 0, sizeof(pan_sdp_record));
184     uint16_t network_packet_types[] = { NETWORK_TYPE_IPv4, NETWORK_TYPE_ARP, 0};    // 0 as end of list
185 
186     // NAP Network Access Type: Other, 1 MB/s
187     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);
188     sdp_register_service(pan_sdp_record);
189     printf("SDP service record size: %u\n", de_get_len((uint8_t*) pan_sdp_record));
190 
191     // Init BNEP lwIP Adapter
192     bnep_lwip_init();
193 
194     // Setup NAP Service via BENP lwIP adapter
195     bnep_lwip_register_service(BLUETOOTH_SERVICE_CLASS_NAP, 1691);
196 
197     // register callback - to print state
198     bnep_lwip_register_packet_handler(packet_handler);
199 }
200 /* LISTING_END */
201 
202 
203 /* @section DHCP Server Configuration
204  *
205  * @text Listing DhcpSetup shows the DHCP Server configuration for network 192.168.7.0/8
206  */
207 
208 /* LISTING_START(DhcpSetup): Setup DHCP Server with 3 entries for 192.168.7.0/8. */
209 
210 #define NUM_DHCP_ENTRY 3
211 
212 static dhcp_entry_t entries[NUM_DHCP_ENTRY] =
213 {
214     /* mac    ip address        subnet mask        lease time */
215     { {0}, {192, 168, 7, 2}, {255, 255, 255, 0}, 24 * 60 * 60 },
216     { {0}, {192, 168, 7, 3}, {255, 255, 255, 0}, 24 * 60 * 60 },
217     { {0}, {192, 168, 7, 4}, {255, 255, 255, 0}, 24 * 60 * 60 }
218 };
219 
220 static dhcp_config_t dhcp_config =
221 {
222     {192, 168, 7, 1}, 67, /* server address, port */
223     {0, 0, 0, 0},         /* dns server */
224     NULL,                /* dns suffix */
225     NUM_DHCP_ENTRY,       /* num entry */
226     entries               /* entries */
227 };
228 /* LISTING_END */
229 
230 #ifdef ENABLE_TEST_FILE_DOWNLOAD
231 
232 /* @section Large File Download
233  *
234  * @text Listing LargeFile Shows how a configurable test file for performance tests is generated on the fly.
235  *       The filename is the number of bytes to generate, e.g. /1048576.txt results in a 1MB file.
236  */
237 
238 /* LISTING_START(LargeFile): Provide large file. */
239 
240 int fs_open_custom(struct fs_file *file, const char *name);
241 int fs_open_custom(struct fs_file *file, const char *name){
242     if (*name != '/') return 0;
243     uint32_t file_size = btstack_atoi(&name[1]);
244     if (file_size > 0) {
245         printf("Serving '%s' with %u bytes\n", name, file_size);
246         /* initialize fs_file correctly */
247         memset(file, 0, sizeof(struct fs_file));
248         file->len = file_size;
249         file->index = 0;
250         file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;
251         return 1;
252     }
253     return 0;
254 }
255 
256 static uint16_t cgi_buffer_fill(char * cgi_buffer, uint16_t cgi_buffer_size, uint32_t start_pos){
257     // fill buffer with dots
258     memset(cgi_buffer, (uint8_t) '.', cgi_buffer_size);
259     uint16_t cursor = 10;
260     uint16_t pos = 0;
261     const uint16_t line_length = 64;
262 
263     while  ((pos + line_length ) < cgi_buffer_size){
264         // write position
265         sprintf((char *) &cgi_buffer[pos], "%08"PRIx32, start_pos + pos);
266         cgi_buffer[pos + 8] = '-';
267         // cursor
268         cgi_buffer[pos+cursor] = '+';
269         cursor++;
270         // new line
271         cgi_buffer[pos+line_length-1] = '\n';
272         pos += line_length;
273     }
274 
275     // handle last incomplete line
276     if (pos == 0){
277         const char * last_line_text = "Thank you for evaluating BTstack!";
278         uint16_t bytes_to_copy = btstack_min(strlen(last_line_text), cgi_buffer_size);
279         memcpy(cgi_buffer, last_line_text, bytes_to_copy);
280         pos = cgi_buffer_size;
281     }
282 
283     return pos;
284 }
285 
286 int fs_read_custom(struct fs_file *file, char *buffer, int count);
287 int fs_read_custom(struct fs_file *file, char *buffer, int count)
288 {
289     uint32_t remaining_data = file->len - file->index;
290     if (remaining_data == 0) {
291         // all bytes already read
292         return FS_READ_EOF;
293     }
294 
295     uint32_t bytes_to_fill = remaining_data;
296     if (bytes_to_fill > (uint32_t) count){
297         bytes_to_fill = count;
298     }
299 
300     uint32_t bytes_written = cgi_buffer_fill(buffer, bytes_to_fill, file->index);
301     file->index += bytes_written;
302 
303     return bytes_written;
304 }
305 
306 void fs_close_custom(struct fs_file *file);
307 void fs_close_custom(struct fs_file *file){
308     UNUSED(file);
309 }
310 #endif
311 /* LISTING_END */
312 
313 /* @section DHCP Server Setup
314  *
315  * @text Listing LwipSetup shows the setup of the lwIP network stack and starts the DHCP Server
316  */
317 
318 /* LISTING_START(LwipSetup): Report lwIP version, init lwIP, start DHCP Serverr */
319 
320 static void network_setup(void){
321     printf("lwIP version: " LWIP_VERSION_STRING "\n");
322 
323 #if BYTE_ORDER == LITTLE_ENDIAN
324     // big endian detection not supported by build configuration
325     if (btstack_is_big_endian()){
326         printf("lwIP configured for little endian, but running on big endian. Please set BYTE_ORDER to BIG_ENDIAN in lwiopts.h\n");
327         while (1);
328     }
329 #endif
330 
331     // init lwIP stack
332 #if NO_SYS
333     lwip_init();
334 #else
335     tcpip_init(NULL, NULL);
336 #endif
337 
338     // start DHCP Server
339     dhserv_init(&dhcp_config);
340 
341     // start HTTP Server
342     httpd_init();
343 }
344 /* LISTING_END */
345 
346 
347 /* @section Main
348  *
349  * @text Setup the lwIP network and PAN NAP
350  */
351 
352 /* LISTING_START(Main): Setup lwIP network and PAN NAP */
353 int btstack_main(int argc, const char * argv[]);
354 int btstack_main(int argc, const char * argv[]){
355 
356     (void)argc;
357     (void)argv;
358 
359     // setup lwIP, HTTP, DHCP
360     network_setup();
361 
362     // setup Classic PAN NAP Service
363     pan_bnep_setup();
364 
365     // Turn on the device
366     hci_power_control(HCI_POWER_ON);
367     return 0;
368 }
369 /* LISTING_END */
370 
371 /* EXAMPLE_END */
372