1 /**
2  * @file
3  * Sequential API Internal module
4  *
5  */
6 
7 /*
8  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright notice,
15  *    this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright notice,
17  *    this list of conditions and the following disclaimer in the documentation
18  *    and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
23  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
27  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
31  * OF SUCH DAMAGE.
32  *
33  * This file is part of the lwIP TCP/IP stack.
34  *
35  * Author: Adam Dunkels <adam@sics.se>
36  *
37  */
38 
39 #include "lwip/opt.h"
40 
41 #if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */
42 
43 #include "lwip/api_msg.h"
44 
45 #include "lwip/ip.h"
46 #include "lwip/udp.h"
47 #include "lwip/tcp.h"
48 #include "lwip/raw.h"
49 
50 #include "lwip/memp.h"
51 #include "lwip/tcpip.h"
52 #include "lwip/igmp.h"
53 #include "lwip/dns.h"
54 
55 #include <string.h>
56 
57 #define SET_NONBLOCKING_CONNECT(conn, val)  do { if(val) { \
58   (conn)->flags |= NETCONN_FLAG_IN_NONBLOCKING_CONNECT; \
59 } else { \
60   (conn)->flags &= ~ NETCONN_FLAG_IN_NONBLOCKING_CONNECT; }} while(0)
61 #define IN_NONBLOCKING_CONNECT(conn) (((conn)->flags & NETCONN_FLAG_IN_NONBLOCKING_CONNECT) != 0)
62 
63 /* forward declarations */
64 #if LWIP_TCP
65 static err_t do_writemore(struct netconn *conn);
66 static void do_close_internal(struct netconn *conn);
67 #endif
68 
69 #if LWIP_RAW
70 /**
71  * Receive callback function for RAW netconns.
72  * Doesn't 'eat' the packet, only references it and sends it to
73  * conn->recvmbox
74  *
75  * @see raw.h (struct raw_pcb.recv) for parameters and return value
76  */
77 static u8_t
78 recv_raw(void *arg, struct raw_pcb *pcb, struct pbuf *p,
79     ip_addr_t *addr)
80 {
81   struct pbuf *q;
82   struct netbuf *buf;
83   struct netconn *conn;
84 
85   LWIP_UNUSED_ARG(addr);
86   conn = (struct netconn *)arg;
87 
88   if ((conn != NULL) && sys_mbox_valid(&conn->recvmbox)) {
89 #if LWIP_SO_RCVBUF
90     int recv_avail;
91     SYS_ARCH_GET(conn->recv_avail, recv_avail);
92     if ((recv_avail + (int)(p->tot_len)) > conn->recv_bufsize) {
93       return 0;
94     }
95 #endif /* LWIP_SO_RCVBUF */
96     /* copy the whole packet into new pbufs */
97     q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
98     if(q != NULL) {
99       if (pbuf_copy(q, p) != ERR_OK) {
100         pbuf_free(q);
101         q = NULL;
102       }
103     }
104 
105     if (q != NULL) {
106       u16_t len;
107       buf = (struct netbuf *)memp_malloc(MEMP_NETBUF);
108       if (buf == NULL) {
109         pbuf_free(q);
110         return 0;
111       }
112 
113       buf->p = q;
114       buf->ptr = q;
115       ip_addr_copy(buf->addr, *ip_current_src_addr());
116       buf->port = pcb->protocol;
117 
118       len = q->tot_len;
119       if (sys_mbox_trypost(&conn->recvmbox, buf) != ERR_OK) {
120         netbuf_delete(buf);
121         return 0;
122       } else {
123 #if LWIP_SO_RCVBUF
124         SYS_ARCH_INC(conn->recv_avail, len);
125 #endif /* LWIP_SO_RCVBUF */
126         /* Register event with callback */
127         API_EVENT(conn, NETCONN_EVT_RCVPLUS, len);
128       }
129     }
130   }
131 
132   return 0; /* do not eat the packet */
133 }
134 #endif /* LWIP_RAW*/
135 
136 #if LWIP_UDP
137 /**
138  * Receive callback function for UDP netconns.
139  * Posts the packet to conn->recvmbox or deletes it on memory error.
140  *
141  * @see udp.h (struct udp_pcb.recv) for parameters
142  */
143 static void
144 recv_udp(void *arg, struct udp_pcb *pcb, struct pbuf *p,
145    ip_addr_t *addr, u16_t port)
146 {
147   struct netbuf *buf;
148   struct netconn *conn;
149   u16_t len;
150 #if LWIP_SO_RCVBUF
151   int recv_avail;
152 #endif /* LWIP_SO_RCVBUF */
153 
154   LWIP_UNUSED_ARG(pcb); /* only used for asserts... */
155   LWIP_ASSERT("recv_udp must have a pcb argument", pcb != NULL);
156   LWIP_ASSERT("recv_udp must have an argument", arg != NULL);
157   conn = (struct netconn *)arg;
158   LWIP_ASSERT("recv_udp: recv for wrong pcb!", conn->pcb.udp == pcb);
159 
160 #if LWIP_SO_RCVBUF
161   SYS_ARCH_GET(conn->recv_avail, recv_avail);
162   if ((conn == NULL) || !sys_mbox_valid(&conn->recvmbox) ||
163       ((recv_avail + (int)(p->tot_len)) > conn->recv_bufsize)) {
164 #else  /* LWIP_SO_RCVBUF */
165   if ((conn == NULL) || !sys_mbox_valid(&conn->recvmbox)) {
166 #endif /* LWIP_SO_RCVBUF */
167     pbuf_free(p);
168     return;
169   }
170 
171   buf = (struct netbuf *)memp_malloc(MEMP_NETBUF);
172   if (buf == NULL) {
173     pbuf_free(p);
174     return;
175   } else {
176     buf->p = p;
177     buf->ptr = p;
178     ip_addr_set(&buf->addr, addr);
179     buf->port = port;
180 #if LWIP_NETBUF_RECVINFO
181     {
182       const struct ip_hdr* iphdr = ip_current_header();
183       /* get the UDP header - always in the first pbuf, ensured by udp_input */
184       const struct udp_hdr* udphdr = (void*)(((char*)iphdr) + IPH_LEN(iphdr));
185 #if LWIP_CHECKSUM_ON_COPY
186       buf->flags = NETBUF_FLAG_DESTADDR;
187 #endif /* LWIP_CHECKSUM_ON_COPY */
188       ip_addr_set(&buf->toaddr, ip_current_dest_addr());
189       buf->toport_chksum = udphdr->dest;
190     }
191 #endif /* LWIP_NETBUF_RECVINFO */
192   }
193 
194   len = p->tot_len;
195   if (sys_mbox_trypost(&conn->recvmbox, buf) != ERR_OK) {
196     netbuf_delete(buf);
197     return;
198   } else {
199 #if LWIP_SO_RCVBUF
200     SYS_ARCH_INC(conn->recv_avail, len);
201 #endif /* LWIP_SO_RCVBUF */
202     /* Register event with callback */
203     API_EVENT(conn, NETCONN_EVT_RCVPLUS, len);
204   }
205 }
206 #endif /* LWIP_UDP */
207 
208 #if LWIP_TCP
209 /**
210  * Receive callback function for TCP netconns.
211  * Posts the packet to conn->recvmbox, but doesn't delete it on errors.
212  *
213  * @see tcp.h (struct tcp_pcb.recv) for parameters and return value
214  */
215 static err_t
216 recv_tcp(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
217 {
218   struct netconn *conn;
219   u16_t len;
220 
221   LWIP_UNUSED_ARG(pcb);
222   LWIP_ASSERT("recv_tcp must have a pcb argument", pcb != NULL);
223   LWIP_ASSERT("recv_tcp must have an argument", arg != NULL);
224   conn = (struct netconn *)arg;
225   LWIP_ASSERT("recv_tcp: recv for wrong pcb!", conn->pcb.tcp == pcb);
226 
227   if (conn == NULL) {
228     return ERR_VAL;
229   }
230   if (!sys_mbox_valid(&conn->recvmbox)) {
231     /* recvmbox already deleted */
232     if (p != NULL) {
233       tcp_recved(pcb, p->tot_len);
234       pbuf_free(p);
235     }
236     return ERR_OK;
237   }
238   /* Unlike for UDP or RAW pcbs, don't check for available space
239      using recv_avail since that could break the connection
240      (data is already ACKed) */
241 
242   /* don't overwrite fatal errors! */
243   NETCONN_SET_SAFE_ERR(conn, err);
244 
245   if (p != NULL) {
246     len = p->tot_len;
247   } else {
248     len = 0;
249   }
250 
251   if (sys_mbox_trypost(&conn->recvmbox, p) != ERR_OK) {
252     /* don't deallocate p: it is presented to us later again from tcp_fasttmr! */
253     return ERR_MEM;
254   } else {
255 #if LWIP_SO_RCVBUF
256     SYS_ARCH_INC(conn->recv_avail, len);
257 #endif /* LWIP_SO_RCVBUF */
258     /* Register event with callback */
259     API_EVENT(conn, NETCONN_EVT_RCVPLUS, len);
260   }
261 
262   return ERR_OK;
263 }
264 
265 /**
266  * Poll callback function for TCP netconns.
267  * Wakes up an application thread that waits for a connection to close
268  * or data to be sent. The application thread then takes the
269  * appropriate action to go on.
270  *
271  * Signals the conn->sem.
272  * netconn_close waits for conn->sem if closing failed.
273  *
274  * @see tcp.h (struct tcp_pcb.poll) for parameters and return value
275  */
276 static err_t
277 poll_tcp(void *arg, struct tcp_pcb *pcb)
278 {
279   struct netconn *conn = (struct netconn *)arg;
280 
281   LWIP_UNUSED_ARG(pcb);
282   LWIP_ASSERT("conn != NULL", (conn != NULL));
283 
284   if (conn->state == NETCONN_WRITE) {
285     do_writemore(conn);
286   } else if (conn->state == NETCONN_CLOSE) {
287     do_close_internal(conn);
288   }
289   /* @todo: implement connect timeout here? */
290 
291   /* Did a nonblocking write fail before? Then check available write-space. */
292   if (conn->flags & NETCONN_FLAG_CHECK_WRITESPACE) {
293     /* If the queued byte- or pbuf-count drops below the configured low-water limit,
294        let select mark this pcb as writable again. */
295     if ((conn->pcb.tcp != NULL) && (tcp_sndbuf(conn->pcb.tcp) > TCP_SNDLOWAT) &&
296       (tcp_sndqueuelen(conn->pcb.tcp) < TCP_SNDQUEUELOWAT)) {
297       conn->flags &= ~NETCONN_FLAG_CHECK_WRITESPACE;
298       API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0);
299     }
300   }
301 
302   return ERR_OK;
303 }
304 
305 /**
306  * Sent callback function for TCP netconns.
307  * Signals the conn->sem and calls API_EVENT.
308  * netconn_write waits for conn->sem if send buffer is low.
309  *
310  * @see tcp.h (struct tcp_pcb.sent) for parameters and return value
311  */
312 static err_t
313 sent_tcp(void *arg, struct tcp_pcb *pcb, u16_t len)
314 {
315   struct netconn *conn = (struct netconn *)arg;
316 
317   LWIP_UNUSED_ARG(pcb);
318   LWIP_ASSERT("conn != NULL", (conn != NULL));
319 
320   if (conn->state == NETCONN_WRITE) {
321     do_writemore(conn);
322   } else if (conn->state == NETCONN_CLOSE) {
323     do_close_internal(conn);
324   }
325 
326   if (conn) {
327     /* If the queued byte- or pbuf-count drops below the configured low-water limit,
328        let select mark this pcb as writable again. */
329     if ((conn->pcb.tcp != NULL) && (tcp_sndbuf(conn->pcb.tcp) > TCP_SNDLOWAT) &&
330       (tcp_sndqueuelen(conn->pcb.tcp) < TCP_SNDQUEUELOWAT)) {
331       conn->flags &= ~NETCONN_FLAG_CHECK_WRITESPACE;
332       API_EVENT(conn, NETCONN_EVT_SENDPLUS, len);
333     }
334   }
335 
336   return ERR_OK;
337 }
338 
339 /**
340  * Error callback function for TCP netconns.
341  * Signals conn->sem, posts to all conn mboxes and calls API_EVENT.
342  * The application thread has then to decide what to do.
343  *
344  * @see tcp.h (struct tcp_pcb.err) for parameters
345  */
346 static void
347 err_tcp(void *arg, err_t err)
348 {
349   struct netconn *conn;
350   enum netconn_state old_state;
351   SYS_ARCH_DECL_PROTECT(lev);
352 
353   conn = (struct netconn *)arg;
354   LWIP_ASSERT("conn != NULL", (conn != NULL));
355 
356   conn->pcb.tcp = NULL;
357 
358   /* no check since this is always fatal! */
359   SYS_ARCH_PROTECT(lev);
360   conn->last_err = err;
361   SYS_ARCH_UNPROTECT(lev);
362 
363   /* reset conn->state now before waking up other threads */
364   old_state = conn->state;
365   conn->state = NETCONN_NONE;
366 
367   /* Notify the user layer about a connection error. Used to signal
368      select. */
369   API_EVENT(conn, NETCONN_EVT_ERROR, 0);
370   /* Try to release selects pending on 'read' or 'write', too.
371      They will get an error if they actually try to read or write. */
372   API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0);
373   API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0);
374 
375   /* pass NULL-message to recvmbox to wake up pending recv */
376   if (sys_mbox_valid(&conn->recvmbox)) {
377     /* use trypost to prevent deadlock */
378     sys_mbox_trypost(&conn->recvmbox, NULL);
379   }
380   /* pass NULL-message to acceptmbox to wake up pending accept */
381   if (sys_mbox_valid(&conn->acceptmbox)) {
382     /* use trypost to preven deadlock */
383     sys_mbox_trypost(&conn->acceptmbox, NULL);
384   }
385 
386   if ((old_state == NETCONN_WRITE) || (old_state == NETCONN_CLOSE) ||
387       (old_state == NETCONN_CONNECT)) {
388     /* calling do_writemore/do_close_internal is not necessary
389        since the pcb has already been deleted! */
390     int was_nonblocking_connect = IN_NONBLOCKING_CONNECT(conn);
391     SET_NONBLOCKING_CONNECT(conn, 0);
392 
393     if (!was_nonblocking_connect) {
394       /* set error return code */
395       LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL);
396       conn->current_msg->err = err;
397       conn->current_msg = NULL;
398       /* wake up the waiting task */
399       sys_sem_signal(&conn->op_completed);
400     }
401   } else {
402     LWIP_ASSERT("conn->current_msg == NULL", conn->current_msg == NULL);
403   }
404 }
405 
406 /**
407  * Setup a tcp_pcb with the correct callback function pointers
408  * and their arguments.
409  *
410  * @param conn the TCP netconn to setup
411  */
412 static void
413 setup_tcp(struct netconn *conn)
414 {
415   struct tcp_pcb *pcb;
416 
417   pcb = conn->pcb.tcp;
418   tcp_arg(pcb, conn);
419   tcp_recv(pcb, recv_tcp);
420   tcp_sent(pcb, sent_tcp);
421   tcp_poll(pcb, poll_tcp, 4);
422   tcp_err(pcb, err_tcp);
423 }
424 
425 /**
426  * Accept callback function for TCP netconns.
427  * Allocates a new netconn and posts that to conn->acceptmbox.
428  *
429  * @see tcp.h (struct tcp_pcb_listen.accept) for parameters and return value
430  */
431 static err_t
432 accept_function(void *arg, struct tcp_pcb *newpcb, err_t err)
433 {
434   struct netconn *newconn;
435   struct netconn *conn = (struct netconn *)arg;
436 
437   LWIP_DEBUGF(API_MSG_DEBUG, ("accept_function: newpcb->tate: %s\n", tcp_debug_state_str(newpcb->state)));
438 
439   if (!sys_mbox_valid(&conn->acceptmbox)) {
440     LWIP_DEBUGF(API_MSG_DEBUG, ("accept_function: acceptmbox already deleted\n"));
441     return ERR_VAL;
442   }
443 
444   /* We have to set the callback here even though
445    * the new socket is unknown. conn->socket is marked as -1. */
446   newconn = netconn_alloc(conn->type, conn->callback);
447   if (newconn == NULL) {
448     return ERR_MEM;
449   }
450   newconn->pcb.tcp = newpcb;
451   setup_tcp(newconn);
452   /* no protection: when creating the pcb, the netconn is not yet known
453      to the application thread */
454   newconn->last_err = err;
455 
456   if (sys_mbox_trypost(&conn->acceptmbox, newconn) != ERR_OK) {
457     /* When returning != ERR_OK, the pcb is aborted in tcp_process(),
458        so do nothing here! */
459     /* remove all references to this netconn from the pcb */
460     struct tcp_pcb* pcb = newconn->pcb.tcp;
461     tcp_arg(pcb, NULL);
462     tcp_recv(pcb, NULL);
463     tcp_sent(pcb, NULL);
464     tcp_poll(pcb, NULL, 4);
465     tcp_err(pcb, NULL);
466     /* remove reference from to the pcb from this netconn */
467     newconn->pcb.tcp = NULL;
468     /* no need to drain since we know the recvmbox is empty. */
469     sys_mbox_free(&newconn->recvmbox);
470     sys_mbox_set_invalid(&newconn->recvmbox);
471     netconn_free(newconn);
472     return ERR_MEM;
473   } else {
474     /* Register event with callback */
475     API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0);
476   }
477 
478   return ERR_OK;
479 }
480 #endif /* LWIP_TCP */
481 
482 /**
483  * Create a new pcb of a specific type.
484  * Called from do_newconn().
485  *
486  * @param msg the api_msg_msg describing the connection type
487  * @return msg->conn->err, but the return value is currently ignored
488  */
489 static void
490 pcb_new(struct api_msg_msg *msg)
491 {
492   LWIP_ASSERT("pcb_new: pcb already allocated", msg->conn->pcb.tcp == NULL);
493 
494   /* Allocate a PCB for this connection */
495   switch(NETCONNTYPE_GROUP(msg->conn->type)) {
496 #if LWIP_RAW
497   case NETCONN_RAW:
498     msg->conn->pcb.raw = raw_new(msg->msg.n.proto);
499     if(msg->conn->pcb.raw == NULL) {
500       msg->err = ERR_MEM;
501       break;
502     }
503     raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn);
504     break;
505 #endif /* LWIP_RAW */
506 #if LWIP_UDP
507   case NETCONN_UDP:
508     msg->conn->pcb.udp = udp_new();
509     if(msg->conn->pcb.udp == NULL) {
510       msg->err = ERR_MEM;
511       break;
512     }
513 #if LWIP_UDPLITE
514     if (msg->conn->type==NETCONN_UDPLITE) {
515       udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE);
516     }
517 #endif /* LWIP_UDPLITE */
518     if (msg->conn->type==NETCONN_UDPNOCHKSUM) {
519       udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM);
520     }
521     udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
522     break;
523 #endif /* LWIP_UDP */
524 #if LWIP_TCP
525   case NETCONN_TCP:
526     msg->conn->pcb.tcp = tcp_new();
527     if(msg->conn->pcb.tcp == NULL) {
528       msg->err = ERR_MEM;
529       break;
530     }
531     setup_tcp(msg->conn);
532     break;
533 #endif /* LWIP_TCP */
534   default:
535     /* Unsupported netconn type, e.g. protocol disabled */
536     msg->err = ERR_VAL;
537     break;
538   }
539 }
540 
541 /**
542  * Create a new pcb of a specific type inside a netconn.
543  * Called from netconn_new_with_proto_and_callback.
544  *
545  * @param msg the api_msg_msg describing the connection type
546  */
547 void
548 do_newconn(struct api_msg_msg *msg)
549 {
550   msg->err = ERR_OK;
551   if(msg->conn->pcb.tcp == NULL) {
552     pcb_new(msg);
553   }
554   /* Else? This "new" connection already has a PCB allocated. */
555   /* Is this an error condition? Should it be deleted? */
556   /* We currently just are happy and return. */
557 
558   TCPIP_APIMSG_ACK(msg);
559 }
560 
561 /**
562  * Create a new netconn (of a specific type) that has a callback function.
563  * The corresponding pcb is NOT created!
564  *
565  * @param t the type of 'connection' to create (@see enum netconn_type)
566  * @param proto the IP protocol for RAW IP pcbs
567  * @param callback a function to call on status changes (RX available, TX'ed)
568  * @return a newly allocated struct netconn or
569  *         NULL on memory error
570  */
571 struct netconn*
572 netconn_alloc(enum netconn_type t, netconn_callback callback)
573 {
574   struct netconn *conn;
575   int size;
576 
577   conn = (struct netconn *)memp_malloc(MEMP_NETCONN);
578   if (conn == NULL) {
579     return NULL;
580   }
581 
582   conn->last_err = ERR_OK;
583   conn->type = t;
584   conn->pcb.tcp = NULL;
585 
586 #if (DEFAULT_RAW_RECVMBOX_SIZE == DEFAULT_UDP_RECVMBOX_SIZE) && \
587     (DEFAULT_RAW_RECVMBOX_SIZE == DEFAULT_TCP_RECVMBOX_SIZE)
588   size = DEFAULT_RAW_RECVMBOX_SIZE;
589 #else
590   switch(NETCONNTYPE_GROUP(t)) {
591 #if LWIP_RAW
592   case NETCONN_RAW:
593     size = DEFAULT_RAW_RECVMBOX_SIZE;
594     break;
595 #endif /* LWIP_RAW */
596 #if LWIP_UDP
597   case NETCONN_UDP:
598     size = DEFAULT_UDP_RECVMBOX_SIZE;
599     break;
600 #endif /* LWIP_UDP */
601 #if LWIP_TCP
602   case NETCONN_TCP:
603     size = DEFAULT_TCP_RECVMBOX_SIZE;
604     break;
605 #endif /* LWIP_TCP */
606   default:
607     LWIP_ASSERT("netconn_alloc: undefined netconn_type", 0);
608     goto free_and_return;
609   }
610 #endif
611 
612   if (sys_sem_new(&conn->op_completed, 0) != ERR_OK) {
613     goto free_and_return;
614   }
615   if (sys_mbox_new(&conn->recvmbox, size) != ERR_OK) {
616     sys_sem_free(&conn->op_completed);
617     goto free_and_return;
618   }
619 
620 #if LWIP_TCP
621   sys_mbox_set_invalid(&conn->acceptmbox);
622 #endif
623   conn->state        = NETCONN_NONE;
624 #if LWIP_SOCKET
625   /* initialize socket to -1 since 0 is a valid socket */
626   conn->socket       = -1;
627 #endif /* LWIP_SOCKET */
628   conn->callback     = callback;
629 #if LWIP_TCP
630   conn->current_msg  = NULL;
631   conn->write_offset = 0;
632 #endif /* LWIP_TCP */
633 #if LWIP_SO_SNDTIMEO
634   conn->send_timeout = 0;
635 #endif /* LWIP_SO_SNDTIMEO */
636 #if LWIP_SO_RCVTIMEO
637   conn->recv_timeout = 0;
638 #endif /* LWIP_SO_RCVTIMEO */
639 #if LWIP_SO_RCVBUF
640   conn->recv_bufsize = RECV_BUFSIZE_DEFAULT;
641   conn->recv_avail   = 0;
642 #endif /* LWIP_SO_RCVBUF */
643   conn->flags = 0;
644   return conn;
645 free_and_return:
646   memp_free(MEMP_NETCONN, conn);
647   return NULL;
648 }
649 
650 /**
651  * Delete a netconn and all its resources.
652  * The pcb is NOT freed (since we might not be in the right thread context do this).
653  *
654  * @param conn the netconn to free
655  */
656 void
657 netconn_free(struct netconn *conn)
658 {
659   LWIP_ASSERT("PCB must be deallocated outside this function", conn->pcb.tcp == NULL);
660   LWIP_ASSERT("recvmbox must be deallocated before calling this function",
661     !sys_mbox_valid(&conn->recvmbox));
662 #if LWIP_TCP
663   LWIP_ASSERT("acceptmbox must be deallocated before calling this function",
664     !sys_mbox_valid(&conn->acceptmbox));
665 #endif /* LWIP_TCP */
666 
667   sys_sem_free(&conn->op_completed);
668   sys_sem_set_invalid(&conn->op_completed);
669 
670   memp_free(MEMP_NETCONN, conn);
671 }
672 
673 /**
674  * Delete rcvmbox and acceptmbox of a netconn and free the left-over data in
675  * these mboxes
676  *
677  * @param conn the netconn to free
678  * @bytes_drained bytes drained from recvmbox
679  * @accepts_drained pending connections drained from acceptmbox
680  */
681 static void
682 netconn_drain(struct netconn *conn)
683 {
684   void *mem;
685 #if LWIP_TCP
686   struct pbuf *p;
687 #endif /* LWIP_TCP */
688 
689   /* This runs in tcpip_thread, so we don't need to lock against rx packets */
690 
691   /* Delete and drain the recvmbox. */
692   if (sys_mbox_valid(&conn->recvmbox)) {
693     while (sys_mbox_tryfetch(&conn->recvmbox, &mem) != SYS_MBOX_EMPTY) {
694 #if LWIP_TCP
695       if (conn->type == NETCONN_TCP) {
696         if(mem != NULL) {
697           p = (struct pbuf*)mem;
698           /* pcb might be set to NULL already by err_tcp() */
699           if (conn->pcb.tcp != NULL) {
700             tcp_recved(conn->pcb.tcp, p->tot_len);
701           }
702           pbuf_free(p);
703         }
704       } else
705 #endif /* LWIP_TCP */
706       {
707         netbuf_delete((struct netbuf *)mem);
708       }
709     }
710     sys_mbox_free(&conn->recvmbox);
711     sys_mbox_set_invalid(&conn->recvmbox);
712   }
713 
714   /* Delete and drain the acceptmbox. */
715 #if LWIP_TCP
716   if (sys_mbox_valid(&conn->acceptmbox)) {
717     while (sys_mbox_tryfetch(&conn->acceptmbox, &mem) != SYS_MBOX_EMPTY) {
718       struct netconn *newconn = (struct netconn *)mem;
719       /* Only tcp pcbs have an acceptmbox, so no need to check conn->type */
720       /* pcb might be set to NULL already by err_tcp() */
721       if (conn->pcb.tcp != NULL) {
722         tcp_accepted(conn->pcb.tcp);
723       }
724       /* drain recvmbox */
725       netconn_drain(newconn);
726       if (newconn->pcb.tcp != NULL) {
727         tcp_abort(newconn->pcb.tcp);
728         newconn->pcb.tcp = NULL;
729       }
730       netconn_free(newconn);
731     }
732     sys_mbox_free(&conn->acceptmbox);
733     sys_mbox_set_invalid(&conn->acceptmbox);
734   }
735 #endif /* LWIP_TCP */
736 }
737 
738 #if LWIP_TCP
739 /**
740  * Internal helper function to close a TCP netconn: since this sometimes
741  * doesn't work at the first attempt, this function is called from multiple
742  * places.
743  *
744  * @param conn the TCP netconn to close
745  */
746 static void
747 do_close_internal(struct netconn *conn)
748 {
749   err_t err;
750   u8_t shut, shut_rx, shut_tx, close;
751 
752   LWIP_ASSERT("invalid conn", (conn != NULL));
753   LWIP_ASSERT("this is for tcp netconns only", (conn->type == NETCONN_TCP));
754   LWIP_ASSERT("conn must be in state NETCONN_CLOSE", (conn->state == NETCONN_CLOSE));
755   LWIP_ASSERT("pcb already closed", (conn->pcb.tcp != NULL));
756   LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL);
757 
758   shut = conn->current_msg->msg.sd.shut;
759   shut_rx = shut & NETCONN_SHUT_RD;
760   shut_tx = shut & NETCONN_SHUT_WR;
761   /* shutting down both ends is the same as closing */
762   close = shut == NETCONN_SHUT_RDWR;
763 
764   /* Set back some callback pointers */
765   if (close) {
766     tcp_arg(conn->pcb.tcp, NULL);
767   }
768   if (conn->pcb.tcp->state == LISTEN) {
769     tcp_accept(conn->pcb.tcp, NULL);
770   } else {
771     /* some callbacks have to be reset if tcp_close is not successful */
772     if (shut_rx) {
773       tcp_recv(conn->pcb.tcp, NULL);
774       tcp_accept(conn->pcb.tcp, NULL);
775     }
776     if (shut_tx) {
777       tcp_sent(conn->pcb.tcp, NULL);
778     }
779     if (close) {
780       tcp_poll(conn->pcb.tcp, NULL, 4);
781       tcp_err(conn->pcb.tcp, NULL);
782     }
783   }
784   /* Try to close the connection */
785   if (close) {
786     err = tcp_close(conn->pcb.tcp);
787   } else {
788     err = tcp_shutdown(conn->pcb.tcp, shut_rx, shut_tx);
789   }
790   if (err == ERR_OK) {
791     /* Closing succeeded */
792     conn->current_msg->err = ERR_OK;
793     conn->current_msg = NULL;
794     conn->state = NETCONN_NONE;
795     if (close) {
796       /* Set back some callback pointers as conn is going away */
797       conn->pcb.tcp = NULL;
798       /* Trigger select() in socket layer. Make sure everybody notices activity
799        on the connection, error first! */
800       API_EVENT(conn, NETCONN_EVT_ERROR, 0);
801     }
802     if (shut_rx) {
803       API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0);
804     }
805     if (shut_tx) {
806       API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0);
807     }
808     /* wake up the application task */
809     sys_sem_signal(&conn->op_completed);
810   } else {
811     /* Closing failed, restore some of the callbacks */
812     /* Closing of listen pcb will never fail! */
813     LWIP_ASSERT("Closing a listen pcb may not fail!", (conn->pcb.tcp->state != LISTEN));
814     tcp_sent(conn->pcb.tcp, sent_tcp);
815     tcp_poll(conn->pcb.tcp, poll_tcp, 4);
816     tcp_err(conn->pcb.tcp, err_tcp);
817     tcp_arg(conn->pcb.tcp, conn);
818     /* don't restore recv callback: we don't want to receive any more data */
819   }
820   /* If closing didn't succeed, we get called again either
821      from poll_tcp or from sent_tcp */
822 }
823 #endif /* LWIP_TCP */
824 
825 /**
826  * Delete the pcb inside a netconn.
827  * Called from netconn_delete.
828  *
829  * @param msg the api_msg_msg pointing to the connection
830  */
831 void
832 do_delconn(struct api_msg_msg *msg)
833 {
834   /* @todo TCP: abort running write/connect? */
835  if ((msg->conn->state != NETCONN_NONE) &&
836      (msg->conn->state != NETCONN_LISTEN) &&
837      (msg->conn->state != NETCONN_CONNECT)) {
838     /* this only happens for TCP netconns */
839     LWIP_ASSERT("msg->conn->type == NETCONN_TCP", msg->conn->type == NETCONN_TCP);
840     msg->err = ERR_INPROGRESS;
841   } else {
842     LWIP_ASSERT("blocking connect in progress",
843       (msg->conn->state != NETCONN_CONNECT) || IN_NONBLOCKING_CONNECT(msg->conn));
844     /* Drain and delete mboxes */
845     netconn_drain(msg->conn);
846 
847     if (msg->conn->pcb.tcp != NULL) {
848 
849       switch (NETCONNTYPE_GROUP(msg->conn->type)) {
850 #if LWIP_RAW
851       case NETCONN_RAW:
852         raw_remove(msg->conn->pcb.raw);
853         break;
854 #endif /* LWIP_RAW */
855 #if LWIP_UDP
856       case NETCONN_UDP:
857         msg->conn->pcb.udp->recv_arg = NULL;
858         udp_remove(msg->conn->pcb.udp);
859         break;
860 #endif /* LWIP_UDP */
861 #if LWIP_TCP
862       case NETCONN_TCP:
863         LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL &&
864           msg->conn->write_offset == 0);
865         msg->conn->state = NETCONN_CLOSE;
866         msg->msg.sd.shut = NETCONN_SHUT_RDWR;
867         msg->conn->current_msg = msg;
868         do_close_internal(msg->conn);
869         /* API_EVENT is called inside do_close_internal, before releasing
870            the application thread, so we can return at this point! */
871         return;
872 #endif /* LWIP_TCP */
873       default:
874         break;
875       }
876       msg->conn->pcb.tcp = NULL;
877     }
878     /* tcp netconns don't come here! */
879 
880     /* @todo: this lets select make the socket readable and writable,
881        which is wrong! errfd instead? */
882     API_EVENT(msg->conn, NETCONN_EVT_RCVPLUS, 0);
883     API_EVENT(msg->conn, NETCONN_EVT_SENDPLUS, 0);
884   }
885   if (sys_sem_valid(&msg->conn->op_completed)) {
886     sys_sem_signal(&msg->conn->op_completed);
887   }
888 }
889 
890 /**
891  * Bind a pcb contained in a netconn
892  * Called from netconn_bind.
893  *
894  * @param msg the api_msg_msg pointing to the connection and containing
895  *            the IP address and port to bind to
896  */
897 void
898 do_bind(struct api_msg_msg *msg)
899 {
900   if (ERR_IS_FATAL(msg->conn->last_err)) {
901     msg->err = msg->conn->last_err;
902   } else {
903     msg->err = ERR_VAL;
904     if (msg->conn->pcb.tcp != NULL) {
905       switch (NETCONNTYPE_GROUP(msg->conn->type)) {
906 #if LWIP_RAW
907       case NETCONN_RAW:
908         msg->err = raw_bind(msg->conn->pcb.raw, msg->msg.bc.ipaddr);
909         break;
910 #endif /* LWIP_RAW */
911 #if LWIP_UDP
912       case NETCONN_UDP:
913         msg->err = udp_bind(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port);
914         break;
915 #endif /* LWIP_UDP */
916 #if LWIP_TCP
917       case NETCONN_TCP:
918         msg->err = tcp_bind(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, msg->msg.bc.port);
919         break;
920 #endif /* LWIP_TCP */
921       default:
922         break;
923       }
924     }
925   }
926   TCPIP_APIMSG_ACK(msg);
927 }
928 
929 #if LWIP_TCP
930 /**
931  * TCP callback function if a connection (opened by tcp_connect/do_connect) has
932  * been established (or reset by the remote host).
933  *
934  * @see tcp.h (struct tcp_pcb.connected) for parameters and return values
935  */
936 static err_t
937 do_connected(void *arg, struct tcp_pcb *pcb, err_t err)
938 {
939   struct netconn *conn;
940   int was_blocking;
941 
942   LWIP_UNUSED_ARG(pcb);
943 
944   conn = (struct netconn *)arg;
945 
946   if (conn == NULL) {
947     return ERR_VAL;
948   }
949 
950   LWIP_ASSERT("conn->state == NETCONN_CONNECT", conn->state == NETCONN_CONNECT);
951   LWIP_ASSERT("(conn->current_msg != NULL) || conn->in_non_blocking_connect",
952     (conn->current_msg != NULL) || IN_NONBLOCKING_CONNECT(conn));
953 
954   if (conn->current_msg != NULL) {
955     conn->current_msg->err = err;
956   }
957   if ((conn->type == NETCONN_TCP) && (err == ERR_OK)) {
958     setup_tcp(conn);
959   }
960   was_blocking = !IN_NONBLOCKING_CONNECT(conn);
961   SET_NONBLOCKING_CONNECT(conn, 0);
962   conn->current_msg = NULL;
963   conn->state = NETCONN_NONE;
964   if (!was_blocking) {
965     NETCONN_SET_SAFE_ERR(conn, ERR_OK);
966   }
967   API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0);
968 
969   if (was_blocking) {
970     sys_sem_signal(&conn->op_completed);
971   }
972   return ERR_OK;
973 }
974 #endif /* LWIP_TCP */
975 
976 /**
977  * Connect a pcb contained inside a netconn
978  * Called from netconn_connect.
979  *
980  * @param msg the api_msg_msg pointing to the connection and containing
981  *            the IP address and port to connect to
982  */
983 void
984 do_connect(struct api_msg_msg *msg)
985 {
986   if (msg->conn->pcb.tcp == NULL) {
987     /* This may happen when calling netconn_connect() a second time */
988     msg->err = ERR_CLSD;
989   } else {
990     switch (NETCONNTYPE_GROUP(msg->conn->type)) {
991 #if LWIP_RAW
992   case NETCONN_RAW:
993     msg->err = raw_connect(msg->conn->pcb.raw, msg->msg.bc.ipaddr);
994     break;
995 #endif /* LWIP_RAW */
996 #if LWIP_UDP
997   case NETCONN_UDP:
998     msg->err = udp_connect(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port);
999     break;
1000 #endif /* LWIP_UDP */
1001 #if LWIP_TCP
1002   case NETCONN_TCP:
1003     /* Prevent connect while doing any other action. */
1004     if (msg->conn->state != NETCONN_NONE) {
1005       msg->err = ERR_ISCONN;
1006     } else {
1007       setup_tcp(msg->conn);
1008       msg->err = tcp_connect(msg->conn->pcb.tcp, msg->msg.bc.ipaddr,
1009         msg->msg.bc.port, do_connected);
1010       if (msg->err == ERR_OK) {
1011         u8_t non_blocking = netconn_is_nonblocking(msg->conn);
1012         msg->conn->state = NETCONN_CONNECT;
1013         SET_NONBLOCKING_CONNECT(msg->conn, non_blocking);
1014         if (non_blocking) {
1015           msg->err = ERR_INPROGRESS;
1016         } else {
1017           msg->conn->current_msg = msg;
1018           /* sys_sem_signal() is called from do_connected (or err_tcp()),
1019           * when the connection is established! */
1020           return;
1021         }
1022       }
1023     }
1024     break;
1025 #endif /* LWIP_TCP */
1026   default:
1027     LWIP_ERROR("Invalid netconn type", 0, do{ msg->err = ERR_VAL; }while(0));
1028     break;
1029     }
1030   }
1031   sys_sem_signal(&msg->conn->op_completed);
1032 }
1033 
1034 /**
1035  * Connect a pcb contained inside a netconn
1036  * Only used for UDP netconns.
1037  * Called from netconn_disconnect.
1038  *
1039  * @param msg the api_msg_msg pointing to the connection to disconnect
1040  */
1041 void
1042 do_disconnect(struct api_msg_msg *msg)
1043 {
1044 #if LWIP_UDP
1045   if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_UDP) {
1046     udp_disconnect(msg->conn->pcb.udp);
1047     msg->err = ERR_OK;
1048   } else
1049 #endif /* LWIP_UDP */
1050   {
1051     msg->err = ERR_VAL;
1052   }
1053   TCPIP_APIMSG_ACK(msg);
1054 }
1055 
1056 #if LWIP_TCP
1057 /**
1058  * Set a TCP pcb contained in a netconn into listen mode
1059  * Called from netconn_listen.
1060  *
1061  * @param msg the api_msg_msg pointing to the connection
1062  */
1063 void
1064 do_listen(struct api_msg_msg *msg)
1065 {
1066   if (ERR_IS_FATAL(msg->conn->last_err)) {
1067     msg->err = msg->conn->last_err;
1068   } else {
1069     msg->err = ERR_CONN;
1070     if (msg->conn->pcb.tcp != NULL) {
1071       if (msg->conn->type == NETCONN_TCP) {
1072         if (msg->conn->state == NETCONN_NONE) {
1073 #if TCP_LISTEN_BACKLOG
1074           struct tcp_pcb* lpcb = tcp_listen_with_backlog(msg->conn->pcb.tcp, msg->msg.lb.backlog);
1075 #else  /* TCP_LISTEN_BACKLOG */
1076           struct tcp_pcb* lpcb = tcp_listen(msg->conn->pcb.tcp);
1077 #endif /* TCP_LISTEN_BACKLOG */
1078           if (lpcb == NULL) {
1079             /* in this case, the old pcb is still allocated */
1080             msg->err = ERR_MEM;
1081           } else {
1082             /* delete the recvmbox and allocate the acceptmbox */
1083             if (sys_mbox_valid(&msg->conn->recvmbox)) {
1084               /** @todo: should we drain the recvmbox here? */
1085               sys_mbox_free(&msg->conn->recvmbox);
1086               sys_mbox_set_invalid(&msg->conn->recvmbox);
1087             }
1088             msg->err = ERR_OK;
1089             if (!sys_mbox_valid(&msg->conn->acceptmbox)) {
1090               msg->err = sys_mbox_new(&msg->conn->acceptmbox, DEFAULT_ACCEPTMBOX_SIZE);
1091             }
1092             if (msg->err == ERR_OK) {
1093               msg->conn->state = NETCONN_LISTEN;
1094               msg->conn->pcb.tcp = lpcb;
1095               tcp_arg(msg->conn->pcb.tcp, msg->conn);
1096               tcp_accept(msg->conn->pcb.tcp, accept_function);
1097             } else {
1098               /* since the old pcb is already deallocated, free lpcb now */
1099               tcp_close(lpcb);
1100               msg->conn->pcb.tcp = NULL;
1101             }
1102           }
1103         }
1104       } else {
1105         msg->err = ERR_ARG;
1106       }
1107     }
1108   }
1109   TCPIP_APIMSG_ACK(msg);
1110 }
1111 #endif /* LWIP_TCP */
1112 
1113 /**
1114  * Send some data on a RAW or UDP pcb contained in a netconn
1115  * Called from netconn_send
1116  *
1117  * @param msg the api_msg_msg pointing to the connection
1118  */
1119 void
1120 do_send(struct api_msg_msg *msg)
1121 {
1122   if (ERR_IS_FATAL(msg->conn->last_err)) {
1123     msg->err = msg->conn->last_err;
1124   } else {
1125     msg->err = ERR_CONN;
1126     if (msg->conn->pcb.tcp != NULL) {
1127       switch (NETCONNTYPE_GROUP(msg->conn->type)) {
1128 #if LWIP_RAW
1129       case NETCONN_RAW:
1130         if (ip_addr_isany(&msg->msg.b->addr)) {
1131           msg->err = raw_send(msg->conn->pcb.raw, msg->msg.b->p);
1132         } else {
1133           msg->err = raw_sendto(msg->conn->pcb.raw, msg->msg.b->p, &msg->msg.b->addr);
1134         }
1135         break;
1136 #endif
1137 #if LWIP_UDP
1138       case NETCONN_UDP:
1139 #if LWIP_CHECKSUM_ON_COPY
1140         if (ip_addr_isany(&msg->msg.b->addr)) {
1141           msg->err = udp_send_chksum(msg->conn->pcb.udp, msg->msg.b->p,
1142             msg->msg.b->flags & NETBUF_FLAG_CHKSUM, msg->msg.b->toport_chksum);
1143         } else {
1144           msg->err = udp_sendto_chksum(msg->conn->pcb.udp, msg->msg.b->p,
1145             &msg->msg.b->addr, msg->msg.b->port,
1146             msg->msg.b->flags & NETBUF_FLAG_CHKSUM, msg->msg.b->toport_chksum);
1147         }
1148 #else /* LWIP_CHECKSUM_ON_COPY */
1149         if (ip_addr_isany(&msg->msg.b->addr)) {
1150           msg->err = udp_send(msg->conn->pcb.udp, msg->msg.b->p);
1151         } else {
1152           msg->err = udp_sendto(msg->conn->pcb.udp, msg->msg.b->p, &msg->msg.b->addr, msg->msg.b->port);
1153         }
1154 #endif /* LWIP_CHECKSUM_ON_COPY */
1155         break;
1156 #endif /* LWIP_UDP */
1157       default:
1158         break;
1159       }
1160     }
1161   }
1162   TCPIP_APIMSG_ACK(msg);
1163 }
1164 
1165 #if LWIP_TCP
1166 /**
1167  * Indicate data has been received from a TCP pcb contained in a netconn
1168  * Called from netconn_recv
1169  *
1170  * @param msg the api_msg_msg pointing to the connection
1171  */
1172 void
1173 do_recv(struct api_msg_msg *msg)
1174 {
1175   msg->err = ERR_OK;
1176   if (msg->conn->pcb.tcp != NULL) {
1177     if (msg->conn->type == NETCONN_TCP) {
1178 #if TCP_LISTEN_BACKLOG
1179       if (msg->conn->pcb.tcp->state == LISTEN) {
1180         tcp_accepted(msg->conn->pcb.tcp);
1181       } else
1182 #endif /* TCP_LISTEN_BACKLOG */
1183       {
1184         u32_t remaining = msg->msg.r.len;
1185         do {
1186           u16_t recved = (remaining > 0xffff) ? 0xffff : (u16_t)remaining;
1187           tcp_recved(msg->conn->pcb.tcp, recved);
1188           remaining -= recved;
1189         }while(remaining != 0);
1190       }
1191     }
1192   }
1193   TCPIP_APIMSG_ACK(msg);
1194 }
1195 
1196 /**
1197  * See if more data needs to be written from a previous call to netconn_write.
1198  * Called initially from do_write. If the first call can't send all data
1199  * (because of low memory or empty send-buffer), this function is called again
1200  * from sent_tcp() or poll_tcp() to send more data. If all data is sent, the
1201  * blocking application thread (waiting in netconn_write) is released.
1202  *
1203  * @param conn netconn (that is currently in state NETCONN_WRITE) to process
1204  * @return ERR_OK
1205  *         ERR_MEM if LWIP_TCPIP_CORE_LOCKING=1 and sending hasn't yet finished
1206  */
1207 static err_t
1208 do_writemore(struct netconn *conn)
1209 {
1210   err_t err;
1211   void *dataptr;
1212   u16_t len, available;
1213   u8_t write_finished = 0;
1214   size_t diff;
1215   u8_t dontblock = netconn_is_nonblocking(conn) ||
1216        (conn->current_msg->msg.w.apiflags & NETCONN_DONTBLOCK);
1217   u8_t apiflags = conn->current_msg->msg.w.apiflags;
1218 
1219   LWIP_ASSERT("conn != NULL", conn != NULL);
1220   LWIP_ASSERT("conn->state == NETCONN_WRITE", (conn->state == NETCONN_WRITE));
1221   LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL);
1222   LWIP_ASSERT("conn->pcb.tcp != NULL", conn->pcb.tcp != NULL);
1223   LWIP_ASSERT("conn->write_offset < conn->current_msg->msg.w.len",
1224     conn->write_offset < conn->current_msg->msg.w.len);
1225 
1226 #if LWIP_SO_SNDTIMEO
1227   if ((conn->send_timeout != 0) &&
1228       ((s32_t)(sys_now() - conn->current_msg->msg.w.time_started) >= conn->send_timeout)) {
1229     write_finished = 1;
1230     if (conn->write_offset == 0) {
1231       /* nothing has been written */
1232       err = ERR_WOULDBLOCK;
1233       conn->current_msg->msg.w.len = 0;
1234     } else {
1235       /* partial write */
1236       err = ERR_OK;
1237       conn->current_msg->msg.w.len = conn->write_offset;
1238     }
1239   } else
1240 #endif /* LWIP_SO_SNDTIMEO */
1241   {
1242     dataptr = (u8_t*)conn->current_msg->msg.w.dataptr + conn->write_offset;
1243     diff = conn->current_msg->msg.w.len - conn->write_offset;
1244     if (diff > 0xffffUL) { /* max_u16_t */
1245       len = 0xffff;
1246 #if LWIP_TCPIP_CORE_LOCKING
1247       conn->flags |= NETCONN_FLAG_WRITE_DELAYED;
1248 #endif
1249       apiflags |= TCP_WRITE_FLAG_MORE;
1250     } else {
1251       len = (u16_t)diff;
1252     }
1253     available = tcp_sndbuf(conn->pcb.tcp);
1254     if (available < len) {
1255       /* don't try to write more than sendbuf */
1256       len = available;
1257       if (dontblock){
1258         if (!len) {
1259           err = ERR_WOULDBLOCK;
1260           goto err_mem;
1261         }
1262       } else {
1263 #if LWIP_TCPIP_CORE_LOCKING
1264         conn->flags |= NETCONN_FLAG_WRITE_DELAYED;
1265 #endif
1266         apiflags |= TCP_WRITE_FLAG_MORE;
1267       }
1268     }
1269     LWIP_ASSERT("do_writemore: invalid length!", ((conn->write_offset + len) <= conn->current_msg->msg.w.len));
1270     err = tcp_write(conn->pcb.tcp, dataptr, len, apiflags);
1271     /* if OK or memory error, check available space */
1272     if ((err == ERR_OK) || (err == ERR_MEM)) {
1273 err_mem:
1274       if (dontblock && (len < conn->current_msg->msg.w.len)) {
1275         /* non-blocking write did not write everything: mark the pcb non-writable
1276            and let poll_tcp check writable space to mark the pcb writable again */
1277         API_EVENT(conn, NETCONN_EVT_SENDMINUS, len);
1278         conn->flags |= NETCONN_FLAG_CHECK_WRITESPACE;
1279       } else if ((tcp_sndbuf(conn->pcb.tcp) <= TCP_SNDLOWAT) ||
1280                  (tcp_sndqueuelen(conn->pcb.tcp) >= TCP_SNDQUEUELOWAT)) {
1281         /* The queued byte- or pbuf-count exceeds the configured low-water limit,
1282            let select mark this pcb as non-writable. */
1283         API_EVENT(conn, NETCONN_EVT_SENDMINUS, len);
1284       }
1285     }
1286 
1287     if (err == ERR_OK) {
1288       conn->write_offset += len;
1289       if ((conn->write_offset == conn->current_msg->msg.w.len) || dontblock) {
1290         /* return sent length */
1291         conn->current_msg->msg.w.len = conn->write_offset;
1292         /* everything was written */
1293         write_finished = 1;
1294         conn->write_offset = 0;
1295       }
1296       tcp_output(conn->pcb.tcp);
1297     } else if ((err == ERR_MEM) && !dontblock) {
1298       /* If ERR_MEM, we wait for sent_tcp or poll_tcp to be called
1299          we do NOT return to the application thread, since ERR_MEM is
1300          only a temporary error! */
1301 
1302       /* tcp_write returned ERR_MEM, try tcp_output anyway */
1303       tcp_output(conn->pcb.tcp);
1304 
1305 #if LWIP_TCPIP_CORE_LOCKING
1306       conn->flags |= NETCONN_FLAG_WRITE_DELAYED;
1307 #endif
1308     } else {
1309       /* On errors != ERR_MEM, we don't try writing any more but return
1310          the error to the application thread. */
1311       write_finished = 1;
1312       conn->current_msg->msg.w.len = 0;
1313     }
1314   }
1315   if (write_finished) {
1316     /* everything was written: set back connection state
1317        and back to application task */
1318     conn->current_msg->err = err;
1319     conn->current_msg = NULL;
1320     conn->state = NETCONN_NONE;
1321 #if LWIP_TCPIP_CORE_LOCKING
1322     if ((conn->flags & NETCONN_FLAG_WRITE_DELAYED) != 0)
1323 #endif
1324     {
1325       sys_sem_signal(&conn->op_completed);
1326     }
1327   }
1328 #if LWIP_TCPIP_CORE_LOCKING
1329   else
1330     return ERR_MEM;
1331 #endif
1332   return ERR_OK;
1333 }
1334 #endif /* LWIP_TCP */
1335 
1336 /**
1337  * Send some data on a TCP pcb contained in a netconn
1338  * Called from netconn_write
1339  *
1340  * @param msg the api_msg_msg pointing to the connection
1341  */
1342 void
1343 do_write(struct api_msg_msg *msg)
1344 {
1345   if (ERR_IS_FATAL(msg->conn->last_err)) {
1346     msg->err = msg->conn->last_err;
1347   } else {
1348     if (msg->conn->type == NETCONN_TCP) {
1349 #if LWIP_TCP
1350       if (msg->conn->state != NETCONN_NONE) {
1351         /* netconn is connecting, closing or in blocking write */
1352         msg->err = ERR_INPROGRESS;
1353       } else if (msg->conn->pcb.tcp != NULL) {
1354         msg->conn->state = NETCONN_WRITE;
1355         /* set all the variables used by do_writemore */
1356         LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL &&
1357           msg->conn->write_offset == 0);
1358         LWIP_ASSERT("msg->msg.w.len != 0", msg->msg.w.len != 0);
1359         msg->conn->current_msg = msg;
1360         msg->conn->write_offset = 0;
1361 #if LWIP_TCPIP_CORE_LOCKING
1362         msg->conn->flags &= ~NETCONN_FLAG_WRITE_DELAYED;
1363         if (do_writemore(msg->conn) != ERR_OK) {
1364           LWIP_ASSERT("state!", msg->conn->state == NETCONN_WRITE);
1365           UNLOCK_TCPIP_CORE();
1366           sys_arch_sem_wait(&msg->conn->op_completed, 0);
1367           LOCK_TCPIP_CORE();
1368           LWIP_ASSERT("state!", msg->conn->state == NETCONN_NONE);
1369         }
1370 #else /* LWIP_TCPIP_CORE_LOCKING */
1371         do_writemore(msg->conn);
1372 #endif /* LWIP_TCPIP_CORE_LOCKING */
1373         /* for both cases: if do_writemore was called, don't ACK the APIMSG
1374            since do_writemore ACKs it! */
1375         return;
1376       } else {
1377         msg->err = ERR_CONN;
1378       }
1379 #else /* LWIP_TCP */
1380       msg->err = ERR_VAL;
1381 #endif /* LWIP_TCP */
1382 #if (LWIP_UDP || LWIP_RAW)
1383     } else {
1384       msg->err = ERR_VAL;
1385 #endif /* (LWIP_UDP || LWIP_RAW) */
1386     }
1387   }
1388   TCPIP_APIMSG_ACK(msg);
1389 }
1390 
1391 /**
1392  * Return a connection's local or remote address
1393  * Called from netconn_getaddr
1394  *
1395  * @param msg the api_msg_msg pointing to the connection
1396  */
1397 void
1398 do_getaddr(struct api_msg_msg *msg)
1399 {
1400   if (msg->conn->pcb.ip != NULL) {
1401     *(msg->msg.ad.ipaddr) = (msg->msg.ad.local ? msg->conn->pcb.ip->local_ip :
1402                              msg->conn->pcb.ip->remote_ip);
1403 
1404     msg->err = ERR_OK;
1405     switch (NETCONNTYPE_GROUP(msg->conn->type)) {
1406 #if LWIP_RAW
1407     case NETCONN_RAW:
1408       if (msg->msg.ad.local) {
1409         *(msg->msg.ad.port) = msg->conn->pcb.raw->protocol;
1410       } else {
1411         /* return an error as connecting is only a helper for upper layers */
1412         msg->err = ERR_CONN;
1413       }
1414       break;
1415 #endif /* LWIP_RAW */
1416 #if LWIP_UDP
1417     case NETCONN_UDP:
1418       if (msg->msg.ad.local) {
1419         *(msg->msg.ad.port) = msg->conn->pcb.udp->local_port;
1420       } else {
1421         if ((msg->conn->pcb.udp->flags & UDP_FLAGS_CONNECTED) == 0) {
1422           msg->err = ERR_CONN;
1423         } else {
1424           *(msg->msg.ad.port) = msg->conn->pcb.udp->remote_port;
1425         }
1426       }
1427       break;
1428 #endif /* LWIP_UDP */
1429 #if LWIP_TCP
1430     case NETCONN_TCP:
1431       *(msg->msg.ad.port) = (msg->msg.ad.local?msg->conn->pcb.tcp->local_port:msg->conn->pcb.tcp->remote_port);
1432       break;
1433 #endif /* LWIP_TCP */
1434     default:
1435       LWIP_ASSERT("invalid netconn_type", 0);
1436       break;
1437     }
1438   } else {
1439     msg->err = ERR_CONN;
1440   }
1441   TCPIP_APIMSG_ACK(msg);
1442 }
1443 
1444 /**
1445  * Close a TCP pcb contained in a netconn
1446  * Called from netconn_close
1447  *
1448  * @param msg the api_msg_msg pointing to the connection
1449  */
1450 void
1451 do_close(struct api_msg_msg *msg)
1452 {
1453 #if LWIP_TCP
1454   /* @todo: abort running write/connect? */
1455   if ((msg->conn->state != NETCONN_NONE) && (msg->conn->state != NETCONN_LISTEN)) {
1456     /* this only happens for TCP netconns */
1457     LWIP_ASSERT("msg->conn->type == NETCONN_TCP", msg->conn->type == NETCONN_TCP);
1458     msg->err = ERR_INPROGRESS;
1459   } else if ((msg->conn->pcb.tcp != NULL) && (msg->conn->type == NETCONN_TCP)) {
1460     if ((msg->msg.sd.shut != NETCONN_SHUT_RDWR) && (msg->conn->state == NETCONN_LISTEN)) {
1461       /* LISTEN doesn't support half shutdown */
1462       msg->err = ERR_CONN;
1463     } else {
1464       if (msg->msg.sd.shut & NETCONN_SHUT_RD) {
1465         /* Drain and delete mboxes */
1466         netconn_drain(msg->conn);
1467       }
1468       LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL &&
1469         msg->conn->write_offset == 0);
1470       msg->conn->state = NETCONN_CLOSE;
1471       msg->conn->current_msg = msg;
1472       do_close_internal(msg->conn);
1473       /* for tcp netconns, do_close_internal ACKs the message */
1474       return;
1475     }
1476   } else
1477 #endif /* LWIP_TCP */
1478   {
1479     msg->err = ERR_VAL;
1480   }
1481   sys_sem_signal(&msg->conn->op_completed);
1482 }
1483 
1484 #if LWIP_IGMP
1485 /**
1486  * Join multicast groups for UDP netconns.
1487  * Called from netconn_join_leave_group
1488  *
1489  * @param msg the api_msg_msg pointing to the connection
1490  */
1491 void
1492 do_join_leave_group(struct api_msg_msg *msg)
1493 {
1494   if (ERR_IS_FATAL(msg->conn->last_err)) {
1495     msg->err = msg->conn->last_err;
1496   } else {
1497     if (msg->conn->pcb.tcp != NULL) {
1498       if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_UDP) {
1499 #if LWIP_UDP
1500         if (msg->msg.jl.join_or_leave == NETCONN_JOIN) {
1501           msg->err = igmp_joingroup(msg->msg.jl.netif_addr, msg->msg.jl.multiaddr);
1502         } else {
1503           msg->err = igmp_leavegroup(msg->msg.jl.netif_addr, msg->msg.jl.multiaddr);
1504         }
1505 #endif /* LWIP_UDP */
1506 #if (LWIP_TCP || LWIP_RAW)
1507       } else {
1508         msg->err = ERR_VAL;
1509 #endif /* (LWIP_TCP || LWIP_RAW) */
1510       }
1511     } else {
1512       msg->err = ERR_CONN;
1513     }
1514   }
1515   TCPIP_APIMSG_ACK(msg);
1516 }
1517 #endif /* LWIP_IGMP */
1518 
1519 #if LWIP_DNS
1520 /**
1521  * Callback function that is called when DNS name is resolved
1522  * (or on timeout). A waiting application thread is waked up by
1523  * signaling the semaphore.
1524  */
1525 static void
1526 do_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
1527 {
1528   struct dns_api_msg *msg = (struct dns_api_msg*)arg;
1529 
1530   LWIP_ASSERT("DNS response for wrong host name", strcmp(msg->name, name) == 0);
1531   LWIP_UNUSED_ARG(name);
1532 
1533   if (ipaddr == NULL) {
1534     /* timeout or memory error */
1535     *msg->err = ERR_VAL;
1536   } else {
1537     /* address was resolved */
1538     *msg->err = ERR_OK;
1539     *msg->addr = *ipaddr;
1540   }
1541   /* wake up the application task waiting in netconn_gethostbyname */
1542   sys_sem_signal(msg->sem);
1543 }
1544 
1545 /**
1546  * Execute a DNS query
1547  * Called from netconn_gethostbyname
1548  *
1549  * @param arg the dns_api_msg pointing to the query
1550  */
1551 void
1552 do_gethostbyname(void *arg)
1553 {
1554   struct dns_api_msg *msg = (struct dns_api_msg*)arg;
1555 
1556   *msg->err = dns_gethostbyname(msg->name, msg->addr, do_dns_found, msg);
1557   if (*msg->err != ERR_INPROGRESS) {
1558     /* on error or immediate success, wake up the application
1559      * task waiting in netconn_gethostbyname */
1560     sys_sem_signal(msg->sem);
1561   }
1562 }
1563 #endif /* LWIP_DNS */
1564 
1565 #endif /* LWIP_NETCONN */
1566