forked from espressif/arduino-esp32
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWiFiClient.cpp
705 lines (631 loc) · 18.9 KB
/
WiFiClient.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
/*
Client.h - Client class for Raspberry Pi
Copyright (c) 2016 Hristo Gochkov All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "WiFiClient.h"
#include "WiFi.h"
#include <lwip/sockets.h>
#include <lwip/netdb.h>
#include <errno.h>
#define WIFI_CLIENT_DEF_CONN_TIMEOUT_MS (3000)
#define WIFI_CLIENT_MAX_WRITE_RETRY (10)
#define WIFI_CLIENT_SELECT_TIMEOUT_US (1000000)
#define WIFI_CLIENT_FLUSH_BUFFER_SIZE (1024)
#undef connect
#undef write
#undef read
class WiFiClientRxBuffer {
private:
size_t _size;
uint8_t *_buffer;
size_t _pos;
size_t _fill;
int _fd;
bool _failed;
size_t r_available()
{
if(_fd < 0){
return 0;
}
int count;
#ifdef ESP_IDF_VERSION_MAJOR
int res = lwip_ioctl(_fd, FIONREAD, &count);
#else
int res = lwip_ioctl_r(_fd, FIONREAD, &count);
#endif
if(res < 0) {
_failed = true;
return 0;
}
return count;
}
size_t fillBuffer()
{
if(!_buffer){
_buffer = (uint8_t *)malloc(_size);
if(!_buffer) {
log_e("Not enough memory to allocate buffer");
_failed = true;
return 0;
}
}
if(_fill && _pos == _fill){
_fill = 0;
_pos = 0;
}
if(!_buffer || _size <= _fill || !r_available()) {
return 0;
}
int res = recv(_fd, _buffer + _fill, _size - _fill, MSG_DONTWAIT);
if(res < 0) {
if(errno != EWOULDBLOCK) {
_failed = true;
}
return 0;
}
_fill += res;
return res;
}
public:
WiFiClientRxBuffer(int fd, size_t size=1436)
:_size(size)
,_buffer(NULL)
,_pos(0)
,_fill(0)
,_fd(fd)
,_failed(false)
{
//_buffer = (uint8_t *)malloc(_size);
}
~WiFiClientRxBuffer()
{
free(_buffer);
}
bool failed(){
return _failed;
}
int read(uint8_t * dst, size_t len){
if(!dst || !len || (_pos == _fill && !fillBuffer())){
return _failed ? -1 : 0;
}
size_t a = _fill - _pos;
if(len <= a || ((len - a) <= (_size - _fill) && fillBuffer() >= (len - a))){
if(len == 1){
*dst = _buffer[_pos];
} else {
memcpy(dst, _buffer + _pos, len);
}
_pos += len;
return len;
}
size_t left = len;
size_t toRead = a;
uint8_t * buf = dst;
memcpy(buf, _buffer + _pos, toRead);
_pos += toRead;
left -= toRead;
buf += toRead;
while(left){
if(!fillBuffer()){
return len - left;
}
a = _fill - _pos;
toRead = (a > left)?left:a;
memcpy(buf, _buffer + _pos, toRead);
_pos += toRead;
left -= toRead;
buf += toRead;
}
return len;
}
int peek(){
if(_pos == _fill && !fillBuffer()){
return -1;
}
return _buffer[_pos];
}
size_t available(){
return _fill - _pos + r_available();
}
};
class WiFiClientSocketHandle {
private:
int sockfd;
public:
WiFiClientSocketHandle(int fd):sockfd(fd)
{
}
~WiFiClientSocketHandle()
{
close(sockfd);
}
int fd()
{
return sockfd;
}
};
WiFiClient::WiFiClient():_connected(false),_timeout(WIFI_CLIENT_DEF_CONN_TIMEOUT_MS),next(NULL)
{
}
WiFiClient::WiFiClient(int fd):_connected(true),_timeout(WIFI_CLIENT_DEF_CONN_TIMEOUT_MS),next(NULL)
{
clientSocketHandle.reset(new WiFiClientSocketHandle(fd));
_rxBuffer.reset(new WiFiClientRxBuffer(fd));
}
WiFiClient::~WiFiClient()
{
stop();
}
WiFiClient & WiFiClient::operator=(const WiFiClient &other)
{
stop();
clientSocketHandle = other.clientSocketHandle;
_rxBuffer = other._rxBuffer;
_connected = other._connected;
return *this;
}
void WiFiClient::stop()
{
clientSocketHandle = NULL;
_rxBuffer = NULL;
_connected = false;
}
int WiFiClient::connect(IPAddress ip, uint16_t port)
{
return connect(ip,port,_timeout);
}
int WiFiClient::connect(IPAddress ip, uint16_t port, int32_t timeout)
{
ip_addr_t dstip;
dstip = IPADDR_ANY_TYPE_INIT;
IP_ADDR4(&dstip, ip[0], ip[1], ip[2], ip[3]);
return connect(dstip, port, timeout);
}
int WiFiClient::connect(ip_addr_t ip, uint16_t port, int32_t timeout)
{
struct sockaddr_storage serveraddr;
_timeout = timeout;
int sockfd = -1;
if (IP_IS_V6(&ip)) {
sockfd = socket(AF_INET6, SOCK_STREAM, 0);
struct sockaddr_in6 *tmpaddr = (struct sockaddr_in6 *)&serveraddr;
memset((char *) tmpaddr, 0, sizeof(struct sockaddr_in6));
tmpaddr->sin6_family = AF_INET6;
inet6_addr_from_ip6addr(&tmpaddr->sin6_addr, ip_2_ip6(&ip));
tmpaddr->sin6_port = htons(port);
}
if (sockfd == -1 && IP_IS_V4(&ip)) {
sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in *tmpaddr = (struct sockaddr_in *)&serveraddr;
memset((char *) tmpaddr, 0, sizeof(struct sockaddr_in));
tmpaddr->sin_family = AF_INET;
tmpaddr->sin_addr.s_addr = ip4_addr_get_u32(&ip.u_addr.ip4);
tmpaddr->sin_port = htons(port);
}
if (sockfd < 0) {
log_e("socket: %d", errno);
return 0;
}
fcntl( sockfd, F_SETFL, fcntl( sockfd, F_GETFL, 0 ) | O_NONBLOCK );
fd_set fdset;
struct timeval tv;
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
tv.tv_sec = _timeout / 1000;
tv.tv_usec = 0;
#ifdef ESP_IDF_VERSION_MAJOR
int res = lwip_connect(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
#else
int res = lwip_connect_r(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
#endif
if (res < 0 && errno != EINPROGRESS) {
log_e("connect on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno));
close(sockfd);
return 0;
}
res = select(sockfd + 1, nullptr, &fdset, nullptr, _timeout<0 ? nullptr : &tv);
if (res < 0) {
log_e("select on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno));
close(sockfd);
return 0;
} else if (res == 0) {
log_i("select returned due to timeout %d ms for fd %d", _timeout, sockfd);
close(sockfd);
return 0;
} else {
int sockerr;
socklen_t len = (socklen_t)sizeof(int);
res = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &sockerr, &len);
if (res < 0) {
log_e("getsockopt on fd %d, errno: %d, \"%s\"", sockfd, errno, strerror(errno));
close(sockfd);
return 0;
}
if (sockerr != 0) {
log_e("socket error on fd %d, errno: %d, \"%s\"", sockfd, sockerr, strerror(sockerr));
close(sockfd);
return 0;
}
}
#define ROE_WIFICLIENT(x,msg) { if (((x)<0)) { log_e("Setsockopt '" msg "'' on fd %d failed. errno: %d, \"%s\"", sockfd, errno, strerror(errno)); return 0; }}
ROE_WIFICLIENT(setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)),"SO_SNDTIMEO");
ROE_WIFICLIENT(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)),"SO_RCVTIMEO");
// These are also set in WiFiClientSecure, should be set here too?
//ROE_WIFICLIENT(setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable)),"TCP_NODELAY");
//ROE_WIFICLIENT (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)),"SO_KEEPALIVE");
fcntl( sockfd, F_SETFL, fcntl( sockfd, F_GETFL, 0 ) & (~O_NONBLOCK) );
clientSocketHandle.reset(new WiFiClientSocketHandle(sockfd));
_rxBuffer.reset(new WiFiClientRxBuffer(sockfd));
_connected = true;
return 1;
}
int WiFiClient::connect(const char *host, uint16_t port)
{
return connect(host,port,_timeout);
}
int WiFiClient::connect(const char *host, uint16_t port, int32_t timeout)
{
if (WiFiGenericClass::getStatusBits() & WIFI_WANT_IP6_BIT) {
ip_addr_t srv6;
if(!WiFiGenericClass::hostByName6(host, srv6)){
return 0;
}
return connect(srv6, port, timeout);
}
IPAddress srv((uint32_t)0);
if(!WiFiGenericClass::hostByName(host, srv)){
return 0;
}
return connect(srv, port, timeout);
}
int WiFiClient::setSocketOption(int option, char* value, size_t len)
{
int res = setsockopt(fd(), SOL_SOCKET, option, value, len);
if(res < 0) {
log_e("%X : %d", option, errno);
}
return res;
}
int WiFiClient::setTimeout(uint32_t seconds)
{
Client::setTimeout(seconds * 1000); // This should be here?
_timeout = seconds * 1000;
if(fd() >= 0) {
struct timeval tv;
tv.tv_sec = seconds;
tv.tv_usec = 0;
if(setSocketOption(SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0) {
return -1;
}
return setSocketOption(SO_SNDTIMEO, (char *)&tv, sizeof(struct timeval));
}
else {
return 0;
}
}
int WiFiClient::setOption(int option, int *value)
{
int res = setsockopt(fd(), IPPROTO_TCP, option, (char *) value, sizeof(int));
if(res < 0) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
}
return res;
}
int WiFiClient::getOption(int option, int *value)
{
socklen_t size = sizeof(int);
int res = getsockopt(fd(), IPPROTO_TCP, option, (char *)value, &size);
if(res < 0) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
}
return res;
}
int WiFiClient::setNoDelay(bool nodelay)
{
int flag = nodelay;
return setOption(TCP_NODELAY, &flag);
}
bool WiFiClient::getNoDelay()
{
int flag = 0;
getOption(TCP_NODELAY, &flag);
return flag;
}
size_t WiFiClient::write(uint8_t data)
{
return write(&data, 1);
}
int WiFiClient::read()
{
uint8_t data = 0;
int res = read(&data, 1);
if(res < 0) {
return res;
}
if (res == 0) { // No data available.
return -1;
}
return data;
}
size_t WiFiClient::write(const uint8_t *buf, size_t size)
{
int res =0;
int retry = WIFI_CLIENT_MAX_WRITE_RETRY;
int socketFileDescriptor = fd();
size_t totalBytesSent = 0;
size_t bytesRemaining = size;
if(!_connected || (socketFileDescriptor < 0)) {
return 0;
}
while(retry) {
//use select to make sure the socket is ready for writing
fd_set set;
struct timeval tv;
FD_ZERO(&set); // empties the set
FD_SET(socketFileDescriptor, &set); // adds FD to the set
tv.tv_sec = 0;
tv.tv_usec = WIFI_CLIENT_SELECT_TIMEOUT_US;
retry--;
if(select(socketFileDescriptor + 1, NULL, &set, NULL, &tv) < 0) {
return 0;
}
if(FD_ISSET(socketFileDescriptor, &set)) {
res = send(socketFileDescriptor, (void*) buf, bytesRemaining, MSG_DONTWAIT);
if(res > 0) {
totalBytesSent += res;
if (totalBytesSent >= size) {
//completed successfully
retry = 0;
} else {
buf += res;
bytesRemaining -= res;
retry = WIFI_CLIENT_MAX_WRITE_RETRY;
}
}
else if(res < 0) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
if(errno != EAGAIN) {
//if resource was busy, can try again, otherwise give up
stop();
res = 0;
retry = 0;
}
}
else {
// Try again
}
}
}
return totalBytesSent;
}
size_t WiFiClient::write_P(PGM_P buf, size_t size)
{
return write(buf, size);
}
size_t WiFiClient::write(Stream &stream)
{
uint8_t * buf = (uint8_t *)malloc(1360);
if(!buf){
return 0;
}
size_t toRead = 0, toWrite = 0, written = 0;
size_t available = stream.available();
while(available){
toRead = (available > 1360)?1360:available;
toWrite = stream.readBytes(buf, toRead);
written += write(buf, toWrite);
available = stream.available();
}
free(buf);
return written;
}
int WiFiClient::read(uint8_t *buf, size_t size)
{
int res = -1;
if (_rxBuffer) {
res = _rxBuffer->read(buf, size);
if(_rxBuffer->failed()) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
}
}
return res;
}
int WiFiClient::peek()
{
int res = -1;
if (_rxBuffer) {
res = _rxBuffer->peek();
if(_rxBuffer->failed()) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
}
}
return res;
}
int WiFiClient::available()
{
if(!_rxBuffer)
{
return 0;
}
int res = _rxBuffer->available();
if(_rxBuffer->failed()) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
}
return res;
}
// Though flushing means to send all pending data,
// seems that in Arduino it also means to clear RX
void WiFiClient::flush() {
int res;
size_t a = available(), toRead = 0;
if(!a){
return;//nothing to flush
}
uint8_t * buf = (uint8_t *)malloc(WIFI_CLIENT_FLUSH_BUFFER_SIZE);
if(!buf){
return;//memory error
}
while(a){
toRead = (a>WIFI_CLIENT_FLUSH_BUFFER_SIZE)?WIFI_CLIENT_FLUSH_BUFFER_SIZE:a;
res = recv(fd(), buf, toRead, MSG_DONTWAIT);
if(res < 0) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
break;
}
a -= res;
}
free(buf);
}
uint8_t WiFiClient::connected()
{
if (_connected) {
uint8_t dummy;
int res = recv(fd(), &dummy, 0, MSG_DONTWAIT);
// avoid unused var warning by gcc
(void)res;
// recv only sets errno if res is <= 0
if (res <= 0){
switch (errno) {
case EWOULDBLOCK:
case ENOENT: //caused by vfs
_connected = true;
break;
case ENOTCONN:
case EPIPE:
case ECONNRESET:
case ECONNREFUSED:
case ECONNABORTED:
_connected = false;
log_d("Disconnected: RES: %d, ERR: %d", res, errno);
break;
default:
log_i("Unexpected: RES: %d, ERR: %d", res, errno);
_connected = true;
break;
}
} else {
_connected = true;
}
}
return _connected;
}
IPAddress WiFiClient::remoteIP(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getpeername(fd, (struct sockaddr*)&addr, &len);
// Old way, IPv4
if (((struct sockaddr*)&addr)->sa_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
return IPAddress((uint32_t)(s->sin_addr.s_addr));
}
// IPv6, but it might be IPv4 mapped address
if (((struct sockaddr*)&addr)->sa_family == AF_INET6) {
struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)&addr;
if (IN6_IS_ADDR_V4MAPPED(saddr6->sin6_addr.un.u32_addr)) {
struct sockaddr_in addr4;
memset(&addr4, 0, sizeof(addr4));
addr4.sin_family = AF_INET;
addr4.sin_port = saddr6->sin6_port;
memcpy(&addr4.sin_addr.s_addr, saddr6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
return IPAddress((uint32_t)(addr4.sin_addr.s_addr));
}
log_e("WiFiClient::remoteIP IPv6 to IPv4 cannot convert");
return (IPAddress(0,0,0,0));
}
log_e("WiFiClient::remoteIP Not AF_INET or AF_INET6?");
return (IPAddress(0,0,0,0));
}
IPv6Address WiFiClient::remoteIP6(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getpeername(fd, (struct sockaddr*)&addr, &len);
// IPv4 socket we can print as IPv6 mapped
if (((struct sockaddr*)&addr)->sa_family == AF_INET) {
uint8_t buffer[16] = { 0 };
buffer[10] = 0xFF;
buffer[11] = 0xFF;
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
memcpy(&buffer[12], (uint8_t*)&s->sin_addr.s_addr, 4);
return IPv6Address(buffer);
}
// IPv6
if (((struct sockaddr*)&addr)->sa_family == AF_INET6) {
struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)&addr;
return (IPv6Address(saddr6->sin6_addr.s6_addr));
}
log_e("WiFiClient::remoteIP Not AF_INET or AF_INET6?");
return (IPv6Address());
}
uint16_t WiFiClient::remotePort(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getpeername(fd, (struct sockaddr*)&addr, &len);
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
return ntohs(s->sin_port);
}
IPAddress WiFiClient::remoteIP() const
{
return remoteIP(fd());
}
IPv6Address WiFiClient::remoteIP6() const
{
return remoteIP6(fd());
}
uint16_t WiFiClient::remotePort() const
{
return remotePort(fd());
}
IPAddress WiFiClient::localIP(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getsockname(fd, (struct sockaddr*)&addr, &len);
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
return IPAddress((uint32_t)(s->sin_addr.s_addr));
}
uint16_t WiFiClient::localPort(int fd) const
{
struct sockaddr_storage addr;
socklen_t len = sizeof addr;
getsockname(fd, (struct sockaddr*)&addr, &len);
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
return ntohs(s->sin_port);
}
IPAddress WiFiClient::localIP() const
{
return localIP(fd());
}
uint16_t WiFiClient::localPort() const
{
return localPort(fd());
}
bool WiFiClient::operator==(const WiFiClient& rhs)
{
return clientSocketHandle == rhs.clientSocketHandle && remotePort() == rhs.remotePort() && remoteIP() == rhs.remoteIP();
}
int WiFiClient::fd() const
{
if (clientSocketHandle == NULL) {
return -1;
} else {
return clientSocketHandle->fd();
}
}