code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
#ifndef VJBSDHDR_H
#define VJBSDHDR_H
#include "lwip/tcp.h"
/*
* Structure of an internet header, naked of options.
*
* We declare ip_len and ip_off to be short, rather than u_short
* pragmatically since otherwise unsigned comparisons can result
* against negative integers quite easily, and fail in subtle ways.
*/
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct ip
{
#if defined(NO_CHAR_BITFIELDS)
u_char ip_hl_v; /* bug in GCC for mips means the bitfield stuff will sometimes break - so we use a char for both and get round it with macro's instead... */
#else
#if BYTE_ORDER == LITTLE_ENDIAN
unsigned ip_hl:4, /* header length */
ip_v :4; /* version */
#elif BYTE_ORDER == BIG_ENDIAN
unsigned ip_v :4, /* version */
ip_hl:4; /* header length */
#else
COMPLAIN - NO BYTE ORDER SELECTED!
#endif
#endif
u_char ip_tos; /* type of service */
u_short ip_len; /* total length */
u_short ip_id; /* identification */
u_short ip_off; /* fragment offset field */
#define IP_DF 0x4000 /* dont fragment flag */
#define IP_MF 0x2000 /* more fragments flag */
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
u_char ip_ttl; /* time to live */
u_char ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src,ip_dst; /* source and dest address */
};
PACK_STRUCT_END
typedef u32_t tcp_seq;
/*
* TCP header.
* Per RFC 793, September, 1981.
*/
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct tcphdr
{
u_short th_sport; /* source port */
u_short th_dport; /* destination port */
tcp_seq th_seq; /* sequence number */
tcp_seq th_ack; /* acknowledgement number */
#if defined(NO_CHAR_BITFIELDS)
u_char th_x2_off;
#else
#if BYTE_ORDER == LITTLE_ENDIAN
unsigned th_x2 :4, /* (unused) */
th_off:4; /* data offset */
#endif
#if BYTE_ORDER == BIG_ENDIAN
unsigned th_off:4, /* data offset */
th_x2 :4; /* (unused) */
#endif
#endif
u_char th_flags;
u_short th_win; /* window */
u_short th_sum; /* checksum */
u_short th_urp; /* urgent pointer */
};
PACK_STRUCT_END
#endif /* VJBSDHDR_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/vjbsdhdr.h | C | oos | 2,555 |
/*****************************************************************************
* ppp.c - Network Point to Point Protocol program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-11-05 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original.
*****************************************************************************/
/*
* ppp_defs.h - PPP definitions.
*
* if_pppvar.h - private structures and declarations for PPP.
*
* Copyright (c) 1994 The Australian National University.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, provided that the above copyright
* notice appears in all copies. This software is provided without any
* warranty, express or implied. The Australian National University
* makes no representations about the suitability of this software for
* any purpose.
*
* IN NO EVENT SHALL THE AUSTRALIAN NATIONAL UNIVERSITY BE LIABLE TO ANY
* PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
* THE AUSTRALIAN NATIONAL UNIVERSITY HAVE BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* THE AUSTRALIAN NATIONAL UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE AUSTRALIAN NATIONAL UNIVERSITY HAS NO
* OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
* OR MODIFICATIONS.
*/
/*
* if_ppp.h - Point-to-Point Protocol definitions.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "lwip/ip.h" /* for ip_input() */
#include "ppp.h"
#include "pppdebug.h"
#include "randm.h"
#include "fsm.h"
#if PAP_SUPPORT
#include "pap.h"
#endif /* PAP_SUPPORT */
#if CHAP_SUPPORT
#include "chap.h"
#endif /* CHAP_SUPPORT */
#include "ipcp.h"
#include "lcp.h"
#include "magic.h"
#include "auth.h"
#if VJ_SUPPORT
#include "vj.h"
#endif /* VJ_SUPPORT */
#if PPPOE_SUPPORT
#include "netif/ppp_oe.h"
#endif /* PPPOE_SUPPORT */
#include <string.h>
/*************************/
/*** LOCAL DEFINITIONS ***/
/*************************/
/*
* The basic PPP frame.
*/
#define PPP_ADDRESS(p) (((u_char *)(p))[0])
#define PPP_CONTROL(p) (((u_char *)(p))[1])
#define PPP_PROTOCOL(p) ((((u_char *)(p))[2] << 8) + ((u_char *)(p))[3])
/* PPP packet parser states. Current state indicates operation yet to be
* completed. */
typedef enum {
PDIDLE = 0, /* Idle state - waiting. */
PDSTART, /* Process start flag. */
PDADDRESS, /* Process address field. */
PDCONTROL, /* Process control field. */
PDPROTOCOL1, /* Process protocol field 1. */
PDPROTOCOL2, /* Process protocol field 2. */
PDDATA /* Process data byte. */
} PPPDevStates;
#define ESCAPE_P(accm, c) ((accm)[(c) >> 3] & pppACCMMask[c & 0x07])
/************************/
/*** LOCAL DATA TYPES ***/
/************************/
/*
* PPP interface control block.
*/
typedef struct PPPControl_s {
char openFlag; /* True when in use. */
#if PPPOE_SUPPORT
struct netif *ethif;
struct pppoe_softc *pppoe_sc;
#endif /* PPPOE_SUPPORT */
int if_up; /* True when the interface is up. */
int errCode; /* Code indicating why interface is down. */
#if PPPOS_SUPPORT
sio_fd_t fd; /* File device ID of port. */
int kill_link; /* Shut the link down. */
int sig_hup; /* Carrier lost. */
struct pbuf *inHead, *inTail; /* The input packet. */
PPPDevStates inState; /* The input process state. */
char inEscaped; /* Escape next character. */
u16_t inProtocol; /* The input protocol code. */
u16_t inFCS; /* Input Frame Check Sequence value. */
#endif /* PPPOS_SUPPORT */
int mtu; /* Peer's mru */
int pcomp; /* Does peer accept protocol compression? */
int accomp; /* Does peer accept addr/ctl compression? */
u_long lastXMit; /* Time of last transmission. */
ext_accm inACCM; /* Async-Ctl-Char-Map for input. */
ext_accm outACCM; /* Async-Ctl-Char-Map for output. */
#if PPPOS_SUPPORT && VJ_SUPPORT
int vjEnabled; /* Flag indicating VJ compression enabled. */
struct vjcompress vjComp; /* Van Jabobsen compression header. */
#endif /* PPPOS_SUPPORT && VJ_SUPPORT */
struct netif netif;
struct ppp_addrs addrs;
void (*linkStatusCB)(void *ctx, int errCode, void *arg);
void *linkStatusCtx;
} PPPControl;
/*
* Ioctl definitions.
*/
struct npioctl {
int protocol; /* PPP procotol, e.g. PPP_IP */
enum NPmode mode;
};
/***********************************/
/*** LOCAL FUNCTION DECLARATIONS ***/
/***********************************/
#if PPPOS_SUPPORT
static void pppMain(void *pd);
static void pppDrop(PPPControl *pc);
static void pppInProc(int pd, u_char *s, int l);
#endif /* PPPOS_SUPPORT */
/******************************/
/*** PUBLIC DATA STRUCTURES ***/
/******************************/
u_long subnetMask;
static PPPControl pppControl[NUM_PPP]; /* The PPP interface control blocks. */
/*
* PPP Data Link Layer "protocol" table.
* One entry per supported protocol.
* The last entry must be NULL.
*/
struct protent *ppp_protocols[] = {
&lcp_protent,
#if PAP_SUPPORT
&pap_protent,
#endif /* PAP_SUPPORT */
#if CHAP_SUPPORT
&chap_protent,
#endif /* CHAP_SUPPORT */
#if CBCP_SUPPORT
&cbcp_protent,
#endif /* CBCP_SUPPORT */
&ipcp_protent,
#if CCP_SUPPORT
&ccp_protent,
#endif /* CCP_SUPPORT */
NULL
};
/*
* Buffers for outgoing packets. This must be accessed only from the appropriate
* PPP task so that it doesn't need to be protected to avoid collisions.
*/
u_char *outpacket_buf[NUM_PPP];
/*****************************/
/*** LOCAL DATA STRUCTURES ***/
/*****************************/
#if PPPOS_SUPPORT
/*
* FCS lookup table as calculated by genfcstab.
*/
static const u_short fcstab[256] = {
0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
};
/* PPP's Asynchronous-Control-Character-Map. The mask array is used
* to select the specific bit for a character. */
static u_char pppACCMMask[] = {
0x01,
0x02,
0x04,
0x08,
0x10,
0x20,
0x40,
0x80
};
void
pppMainWakeup(int pd)
{
PPPDEBUG((LOG_DEBUG, "pppMainWakeup: unit %d\n", pd));
sio_read_abort(pppControl[pd].fd);
}
#endif /* PPPOS_SUPPORT */
void
pppLinkTerminated(int pd)
{
PPPControl *pc = &pppControl[pd];
PPPDEBUG((LOG_DEBUG, "pppLinkTerminated: unit %d\n", pd));
#if PPPOE_SUPPORT
if(pc->ethif) {
pppoe_disconnect(pc->pppoe_sc);
} else
#endif /* PPPOE_SUPPORT */
{
#if PPPOS_SUPPORT
pppMainWakeup(pd);
#endif /* PPPOS_SUPPORT */
}
}
void
pppLinkDown(int pd)
{
PPPControl *pc = &pppControl[pd];
PPPDEBUG((LOG_DEBUG, "pppLinkDown: unit %d\n", pd));
#if PPPOE_SUPPORT
if(pc->ethif) {
pppoe_disconnect(pc->pppoe_sc);
} else
#endif /* PPPOE_SUPPORT */
{
#if PPPOS_SUPPORT
pppMainWakeup(pd);
#endif /* PPPOS_SUPPORT */
}
}
/* these callbacks are necessary because lcp_* functions
must be called in the same context as pppInput(),
namely the tcpip_thread(), essentially because
they manipulate timeouts which are thread-private
*/
static void
pppStartCB(void *arg)
{
int pd = (int)arg;
PPPDEBUG((LOG_DEBUG, "pppStartCB: unit %d\n", pd));
lcp_lowerup(pd);
lcp_open(pd); /* Start protocol */
}
static void
pppStopCB(void *arg)
{
int pd = (int)arg;
PPPDEBUG((LOG_DEBUG, "pppStopCB: unit %d\n", pd));
lcp_close(pd, "User request");
}
static void
pppHupCB(void *arg)
{
int pd = (int)arg;
PPPDEBUG((LOG_DEBUG, "pppHupCB: unit %d\n", pd));
lcp_lowerdown(pd);
link_terminated(pd);
}
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
/* Initialize the PPP subsystem. */
struct ppp_settings ppp_settings;
err_t
pppInit(void)
{
struct protent *protp;
int i, j;
memset(&ppp_settings, 0, sizeof(ppp_settings));
ppp_settings.usepeerdns = 1;
pppSetAuth(PPPAUTHTYPE_NONE, NULL, NULL);
magicInit();
for (i = 0; i < NUM_PPP; i++) {
pppControl[i].openFlag = 0;
subnetMask = htonl(0xffffff00);
outpacket_buf[i] = (u_char *)mem_malloc(PPP_MRU+PPP_HDRLEN);
if(!outpacket_buf[i]) {
return ERR_MEM;
}
/*
* Initialize to the standard option set.
*/
for (j = 0; (protp = ppp_protocols[j]) != NULL; ++j) {
(*protp->init)(i);
}
}
#if LINK_STATS
/** @todo already done in stats_init (in fact, zeroed at boot). So, remove it? */
/* Clear the statistics. */
memset(&lwip_stats.link, 0, sizeof(lwip_stats.link));
#endif /* LINK_STATS */
#if PPPOE_SUPPORT
pppoe_init();
#endif /* PPPOE_SUPPORT */
return ERR_OK;
}
void
pppSetAuth(enum pppAuthType authType, const char *user, const char *passwd)
{
switch(authType) {
case PPPAUTHTYPE_NONE:
default:
#ifdef LWIP_PPP_STRICT_PAP_REJECT
ppp_settings.refuse_pap = 1;
#else /* LWIP_PPP_STRICT_PAP_REJECT */
/* some providers request pap and accept an empty login/pw */
ppp_settings.refuse_pap = 0;
#endif /* LWIP_PPP_STRICT_PAP_REJECT */
ppp_settings.refuse_chap = 1;
break;
case PPPAUTHTYPE_ANY:
/* Warning: Using PPPAUTHTYPE_ANY might have security consequences.
* RFC 1994 says:
*
* In practice, within or associated with each PPP server, there is a
* database which associates "user" names with authentication
* information ("secrets"). It is not anticipated that a particular
* named user would be authenticated by multiple methods. This would
* make the user vulnerable to attacks which negotiate the least secure
* method from among a set (such as PAP rather than CHAP). If the same
* secret was used, PAP would reveal the secret to be used later with
* CHAP.
*
* Instead, for each user name there should be an indication of exactly
* one method used to authenticate that user name. If a user needs to
* make use of different authentication methods under different
* circumstances, then distinct user names SHOULD be employed, each of
* which identifies exactly one authentication method.
*
*/
ppp_settings.refuse_pap = 0;
ppp_settings.refuse_chap = 0;
break;
case PPPAUTHTYPE_PAP:
ppp_settings.refuse_pap = 0;
ppp_settings.refuse_chap = 1;
break;
case PPPAUTHTYPE_CHAP:
ppp_settings.refuse_pap = 1;
ppp_settings.refuse_chap = 0;
break;
}
if(user) {
strncpy(ppp_settings.user, user, sizeof(ppp_settings.user)-1);
ppp_settings.user[sizeof(ppp_settings.user)-1] = '\0';
} else {
ppp_settings.user[0] = '\0';
}
if(passwd) {
strncpy(ppp_settings.passwd, passwd, sizeof(ppp_settings.passwd)-1);
ppp_settings.passwd[sizeof(ppp_settings.passwd)-1] = '\0';
} else {
ppp_settings.passwd[0] = '\0';
}
}
#if PPPOS_SUPPORT
/* Open a new PPP connection using the given I/O device.
* This initializes the PPP control block but does not
* attempt to negotiate the LCP session. If this port
* connects to a modem, the modem connection must be
* established before calling this.
* Return a new PPP connection descriptor on success or
* an error code (negative) on failure. */
int
pppOverSerialOpen(sio_fd_t fd, void (*linkStatusCB)(void *ctx, int errCode, void *arg), void *linkStatusCtx)
{
PPPControl *pc;
int pd;
/* Find a free PPP session descriptor. Critical region? */
for (pd = 0; pd < NUM_PPP && pppControl[pd].openFlag != 0; pd++);
if (pd >= NUM_PPP) {
pd = PPPERR_OPEN;
} else {
pppControl[pd].openFlag = !0;
}
/* Launch a deamon thread. */
if (pd >= 0) {
pppControl[pd].openFlag = 1;
lcp_init(pd);
pc = &pppControl[pd];
pc->fd = fd;
#if PPPOE_SUPPORT
pc->ethif= NULL;
#endif /* PPPOE_SUPPORT */
pc->kill_link = 0;
pc->sig_hup = 0;
pc->if_up = 0;
pc->errCode = 0;
pc->inState = PDIDLE;
pc->inHead = NULL;
pc->inTail = NULL;
pc->inEscaped = 0;
pc->lastXMit = 0;
#if VJ_SUPPORT
pc->vjEnabled = 0;
vj_compress_init(&pc->vjComp);
#endif /* VJ_SUPPORT */
/*
* Default the in and out accm so that escape and flag characters
* are always escaped.
*/
memset(pc->inACCM, 0, sizeof(ext_accm));
pc->inACCM[15] = 0x60;
memset(pc->outACCM, 0, sizeof(ext_accm));
pc->outACCM[15] = 0x60;
pc->linkStatusCB = linkStatusCB;
pc->linkStatusCtx = linkStatusCtx;
sys_thread_new(PPP_THREAD_NAME, pppMain, (void*)pd, PPP_THREAD_STACKSIZE, PPP_THREAD_PRIO);
if(!linkStatusCB) {
while(pd >= 0 && !pc->if_up) {
sys_msleep(500);
if (lcp_phase[pd] == PHASE_DEAD) {
pppClose(pd);
if (pc->errCode) {
pd = pc->errCode;
} else {
pd = PPPERR_CONNECT;
}
}
}
}
}
return pd;
}
#endif /* PPPOS_SUPPORT */
#if PPPOE_SUPPORT
static void pppOverEthernetLinkStatusCB(int pd, int up);
void
pppOverEthernetClose(int pd)
{
PPPControl* pc = &pppControl[pd];
/* *TJL* There's no lcp_deinit */
lcp_close(pd, NULL);
pppoe_destroy(&pc->netif);
}
int pppOverEthernetOpen(struct netif *ethif, const char *service_name, const char *concentrator_name, void (*linkStatusCB)(void *ctx, int errCode, void *arg), void *linkStatusCtx)
{
PPPControl *pc;
int pd;
LWIP_UNUSED_ARG(service_name);
LWIP_UNUSED_ARG(concentrator_name);
/* Find a free PPP session descriptor. Critical region? */
for (pd = 0; pd < NUM_PPP && pppControl[pd].openFlag != 0; pd++);
if (pd >= NUM_PPP) {
pd = PPPERR_OPEN;
} else {
pppControl[pd].openFlag = !0;
}
/* Launch a deamon thread. */
if (pd >= 0) {
pppControl[pd].openFlag = 1;
lcp_init(pd);
lcp_wantoptions[pd].mru = PPPOE_MAXMTU;
lcp_wantoptions[pd].neg_asyncmap = 0;
lcp_wantoptions[pd].neg_pcompression = 0;
lcp_wantoptions[pd].neg_accompression = 0;
lcp_allowoptions[pd].mru = PPPOE_MAXMTU;
lcp_allowoptions[pd].neg_asyncmap = 0;
lcp_allowoptions[pd].neg_pcompression = 0;
lcp_allowoptions[pd].neg_accompression = 0;
pc = &pppControl[pd];
pc->if_up = 0;
pc->errCode = 0;
pc->lastXMit = 0;
#if PPPOS_SUPPORT
pc->kill_link = 0;
pc->sig_hup = 0;
pc->inState = PDIDLE;
pc->inHead = NULL;
pc->inTail = NULL;
pc->inEscaped = 0;
#if VJ_SUPPORT
pc->vjEnabled = 0;
#endif /* VJ_SUPPORT */
#endif /* PPPOS_SUPPORT */
pc->ethif= ethif;
memset(pc->inACCM, 0, sizeof(ext_accm));
memset(pc->outACCM, 0, sizeof(ext_accm));
pc->linkStatusCB = linkStatusCB;
pc->linkStatusCtx = linkStatusCtx;
if(pppoe_create(ethif, pd, pppOverEthernetLinkStatusCB, &pc->pppoe_sc) != ERR_OK) {
pc->openFlag = 0;
return PPPERR_OPEN;
}
pppoe_connect(pc->pppoe_sc);
if(!linkStatusCB) {
while(pd >= 0 && !pc->if_up) {
sys_msleep(500);
if (lcp_phase[pd] == PHASE_DEAD) {
pppClose(pd);
if (pc->errCode) {
pd = pc->errCode;
} else {
pd = PPPERR_CONNECT;
}
}
}
}
}
return pd;
}
#endif /* PPPOE_SUPPORT */
/* Close a PPP connection and release the descriptor.
* Any outstanding packets in the queues are dropped.
* Return 0 on success, an error code on failure. */
int
pppClose(int pd)
{
PPPControl *pc = &pppControl[pd];
int st = 0;
/* Disconnect */
#if PPPOE_SUPPORT
if(pc->ethif) {
PPPDEBUG((LOG_DEBUG, "pppClose: unit %d kill_link -> pppStopCB\n", pd));
pc->errCode = PPPERR_USER;
/* This will leave us at PHASE_DEAD. */
tcpip_callback(pppStopCB, (void*)pd);
} else
#endif /* PPPOE_SUPPORT */
{
#if PPPOS_SUPPORT
pc->kill_link = !0;
pppMainWakeup(pd);
#endif /* PPPOS_SUPPORT */
}
if(!pc->linkStatusCB) {
while(st >= 0 && lcp_phase[pd] != PHASE_DEAD) {
sys_msleep(500);
break;
}
}
return st;
}
/* This function is called when carrier is lost on the PPP channel. */
void
pppSigHUP(int pd)
{
PPPControl *pc = &pppControl[pd];
#if PPPOE_SUPPORT
if(pc->ethif) {
PPPDEBUG((LOG_DEBUG, "pppSigHUP: unit %d sig_hup -> pppHupCB\n", pd));
tcpip_callback(pppHupCB, (void*)pd);
} else
#endif /* PPPOE_SUPPORT */
{
#if PPPOS_SUPPORT
pc->sig_hup = 1;
pppMainWakeup(pd);
#endif /* PPPOS_SUPPORT */
}
}
#if PPPOS_SUPPORT
static void
nPut(PPPControl *pc, struct pbuf *nb)
{
struct pbuf *b;
int c;
for(b = nb; b != NULL; b = b->next) {
if((c = sio_write(pc->fd, b->payload, b->len)) != b->len) {
PPPDEBUG((LOG_WARNING,
"PPP nPut: incomplete sio_write(%d,, %u) = %d\n", pc->fd, b->len, c));
LINK_STATS_INC(link.err);
pc->lastXMit = 0; /* prepend PPP_FLAG to next packet */
break;
}
}
pbuf_free(nb);
LINK_STATS_INC(link.xmit);
}
/*
* pppAppend - append given character to end of given pbuf. If outACCM
* is not NULL and the character needs to be escaped, do so.
* If pbuf is full, append another.
* Return the current pbuf.
*/
static struct pbuf *
pppAppend(u_char c, struct pbuf *nb, ext_accm *outACCM)
{
struct pbuf *tb = nb;
/* Make sure there is room for the character and an escape code.
* Sure we don't quite fill the buffer if the character doesn't
* get escaped but is one character worth complicating this? */
/* Note: We assume no packet header. */
if (nb && (PBUF_POOL_BUFSIZE - nb->len) < 2) {
tb = pbuf_alloc(PBUF_RAW, 0, PBUF_POOL);
if (tb) {
nb->next = tb;
} else {
LINK_STATS_INC(link.memerr);
}
nb = tb;
}
if (nb) {
if (outACCM && ESCAPE_P(*outACCM, c)) {
*((u_char*)nb->payload + nb->len++) = PPP_ESCAPE;
*((u_char*)nb->payload + nb->len++) = c ^ PPP_TRANS;
} else {
*((u_char*)nb->payload + nb->len++) = c;
}
}
return tb;
}
#endif /* PPPOS_SUPPORT */
#if PPPOE_SUPPORT
static err_t
pppifOutputOverEthernet(int pd, struct pbuf *p)
{
PPPControl *pc = &pppControl[pd];
struct pbuf *pb;
u_short protocol = PPP_IP;
int i=0;
pb = pbuf_alloc(PBUF_LINK, pppoe_hdrlen + sizeof(protocol), PBUF_RAM);
if(!pb) {
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.proterr);
return ERR_MEM;
}
pbuf_header(pb, -pppoe_hdrlen);
pc->lastXMit = sys_jiffies();
if (!pc->pcomp || protocol > 0xFF) {
*((u_char*)pb->payload + i++) = (protocol >> 8) & 0xFF;
}
*((u_char*)pb->payload + i) = protocol & 0xFF;
pbuf_chain(pb, p);
if(pppoe_xmit(pc->pppoe_sc, pb) != ERR_OK) {
LINK_STATS_INC(link.err);
return PPPERR_DEVICE;
}
LINK_STATS_INC(link.xmit);
return ERR_OK;
}
#endif /* PPPOE_SUPPORT */
/* Send a packet on the given connection. */
static err_t
pppifOutput(struct netif *netif, struct pbuf *pb, struct ip_addr *ipaddr)
{
int pd = (int)netif->state;
u_short protocol = PPP_IP;
PPPControl *pc = &pppControl[pd];
#if PPPOS_SUPPORT
u_int fcsOut = PPP_INITFCS;
struct pbuf *headMB = NULL, *tailMB = NULL, *p;
u_char c;
#endif /* PPPOS_SUPPORT */
LWIP_UNUSED_ARG(ipaddr);
/* Validate parameters. */
/* We let any protocol value go through - it can't hurt us
* and the peer will just drop it if it's not accepting it. */
if (pd < 0 || pd >= NUM_PPP || !pc->openFlag || !pb) {
PPPDEBUG((LOG_WARNING, "pppifOutput[%d]: bad parms prot=%d pb=%p\n",
pd, protocol, pb));
LINK_STATS_INC(link.opterr);
LINK_STATS_INC(link.drop);
return ERR_ARG;
}
/* Check that the link is up. */
if (lcp_phase[pd] == PHASE_DEAD) {
PPPDEBUG((LOG_ERR, "pppifOutput[%d]: link not up\n", pd));
LINK_STATS_INC(link.rterr);
LINK_STATS_INC(link.drop);
return ERR_RTE;
}
#if PPPOE_SUPPORT
if(pc->ethif) {
return pppifOutputOverEthernet(pd, pb);
}
#endif /* PPPOE_SUPPORT */
#if PPPOS_SUPPORT
/* Grab an output buffer. */
headMB = pbuf_alloc(PBUF_RAW, 0, PBUF_POOL);
if (headMB == NULL) {
PPPDEBUG((LOG_WARNING, "pppifOutput[%d]: first alloc fail\n", pd));
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
return ERR_MEM;
}
#if VJ_SUPPORT
/*
* Attempt Van Jacobson header compression if VJ is configured and
* this is an IP packet.
*/
if (protocol == PPP_IP && pc->vjEnabled) {
switch (vj_compress_tcp(&pc->vjComp, pb)) {
case TYPE_IP:
/* No change...
protocol = PPP_IP_PROTOCOL; */
break;
case TYPE_COMPRESSED_TCP:
protocol = PPP_VJC_COMP;
break;
case TYPE_UNCOMPRESSED_TCP:
protocol = PPP_VJC_UNCOMP;
break;
default:
PPPDEBUG((LOG_WARNING, "pppifOutput[%d]: bad IP packet\n", pd));
LINK_STATS_INC(link.proterr);
LINK_STATS_INC(link.drop);
pbuf_free(headMB);
return ERR_VAL;
}
}
#endif /* VJ_SUPPORT */
tailMB = headMB;
/* Build the PPP header. */
if ((sys_jiffies() - pc->lastXMit) >= PPP_MAXIDLEFLAG) {
tailMB = pppAppend(PPP_FLAG, tailMB, NULL);
}
pc->lastXMit = sys_jiffies();
if (!pc->accomp) {
fcsOut = PPP_FCS(fcsOut, PPP_ALLSTATIONS);
tailMB = pppAppend(PPP_ALLSTATIONS, tailMB, &pc->outACCM);
fcsOut = PPP_FCS(fcsOut, PPP_UI);
tailMB = pppAppend(PPP_UI, tailMB, &pc->outACCM);
}
if (!pc->pcomp || protocol > 0xFF) {
c = (protocol >> 8) & 0xFF;
fcsOut = PPP_FCS(fcsOut, c);
tailMB = pppAppend(c, tailMB, &pc->outACCM);
}
c = protocol & 0xFF;
fcsOut = PPP_FCS(fcsOut, c);
tailMB = pppAppend(c, tailMB, &pc->outACCM);
/* Load packet. */
for(p = pb; p; p = p->next) {
int n;
u_char *sPtr;
sPtr = (u_char*)p->payload;
n = p->len;
while (n-- > 0) {
c = *sPtr++;
/* Update FCS before checking for special characters. */
fcsOut = PPP_FCS(fcsOut, c);
/* Copy to output buffer escaping special characters. */
tailMB = pppAppend(c, tailMB, &pc->outACCM);
}
}
/* Add FCS and trailing flag. */
c = ~fcsOut & 0xFF;
tailMB = pppAppend(c, tailMB, &pc->outACCM);
c = (~fcsOut >> 8) & 0xFF;
tailMB = pppAppend(c, tailMB, &pc->outACCM);
tailMB = pppAppend(PPP_FLAG, tailMB, NULL);
/* If we failed to complete the packet, throw it away. */
if (!tailMB) {
PPPDEBUG((LOG_WARNING,
"pppifOutput[%d]: Alloc err - dropping proto=%d\n",
pd, protocol));
pbuf_free(headMB);
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
return ERR_MEM;
}
/* Send it. */
PPPDEBUG((LOG_INFO, "pppifOutput[%d]: proto=0x%04X\n", pd, protocol));
nPut(pc, headMB);
#endif /* PPPOS_SUPPORT */
return ERR_OK;
}
/* Get and set parameters for the given connection.
* Return 0 on success, an error code on failure. */
int
pppIOCtl(int pd, int cmd, void *arg)
{
PPPControl *pc = &pppControl[pd];
int st = 0;
if (pd < 0 || pd >= NUM_PPP) {
st = PPPERR_PARAM;
} else {
switch(cmd) {
case PPPCTLG_UPSTATUS: /* Get the PPP up status. */
if (arg) {
*(int *)arg = (int)(pc->if_up);
} else {
st = PPPERR_PARAM;
}
break;
case PPPCTLS_ERRCODE: /* Set the PPP error code. */
if (arg) {
pc->errCode = *(int *)arg;
} else {
st = PPPERR_PARAM;
}
break;
case PPPCTLG_ERRCODE: /* Get the PPP error code. */
if (arg) {
*(int *)arg = (int)(pc->errCode);
} else {
st = PPPERR_PARAM;
}
break;
#if PPPOS_SUPPORT
case PPPCTLG_FD:
if (arg) {
*(sio_fd_t *)arg = pc->fd;
} else {
st = PPPERR_PARAM;
}
break;
#endif /* PPPOS_SUPPORT */
default:
st = PPPERR_PARAM;
break;
}
}
return st;
}
/*
* Return the Maximum Transmission Unit for the given PPP connection.
*/
u_int
pppMTU(int pd)
{
PPPControl *pc = &pppControl[pd];
u_int st;
/* Validate parameters. */
if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) {
st = 0;
} else {
st = pc->mtu;
}
return st;
}
#if PPPOE_SUPPORT
int
pppWriteOverEthernet(int pd, const u_char *s, int n)
{
PPPControl *pc = &pppControl[pd];
struct pbuf *pb;
/* skip address & flags */
s += 2;
n -= 2;
pb = pbuf_alloc(PBUF_LINK, pppoe_hdrlen + n, PBUF_RAM);
if(!pb) {
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.proterr);
return PPPERR_ALLOC;
}
pbuf_header(pb, -pppoe_hdrlen);
pc->lastXMit = sys_jiffies();
SMEMCPY(pb->payload, s, n);
if(pppoe_xmit(pc->pppoe_sc, pb) != ERR_OK) {
LINK_STATS_INC(link.err);
return PPPERR_DEVICE;
}
LINK_STATS_INC(link.xmit);
return PPPERR_NONE;
}
#endif /* PPPOE_SUPPORT */
/*
* Write n characters to a ppp link.
* RETURN: >= 0 Number of characters written
* -1 Failed to write to device
*/
int
pppWrite(int pd, const u_char *s, int n)
{
PPPControl *pc = &pppControl[pd];
#if PPPOS_SUPPORT
u_char c;
u_int fcsOut;
struct pbuf *headMB, *tailMB;
#endif /* PPPOS_SUPPORT */
#if PPPOE_SUPPORT
if(pc->ethif) {
return pppWriteOverEthernet(pd, s, n);
}
#endif /* PPPOE_SUPPORT */
#if PPPOS_SUPPORT
headMB = pbuf_alloc(PBUF_RAW, 0, PBUF_POOL);
if (headMB == NULL) {
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.proterr);
return PPPERR_ALLOC;
}
tailMB = headMB;
/* If the link has been idle, we'll send a fresh flag character to
* flush any noise. */
if ((sys_jiffies() - pc->lastXMit) >= PPP_MAXIDLEFLAG) {
tailMB = pppAppend(PPP_FLAG, tailMB, NULL);
}
pc->lastXMit = sys_jiffies();
fcsOut = PPP_INITFCS;
/* Load output buffer. */
while (n-- > 0) {
c = *s++;
/* Update FCS before checking for special characters. */
fcsOut = PPP_FCS(fcsOut, c);
/* Copy to output buffer escaping special characters. */
tailMB = pppAppend(c, tailMB, &pc->outACCM);
}
/* Add FCS and trailing flag. */
c = ~fcsOut & 0xFF;
tailMB = pppAppend(c, tailMB, &pc->outACCM);
c = (~fcsOut >> 8) & 0xFF;
tailMB = pppAppend(c, tailMB, &pc->outACCM);
tailMB = pppAppend(PPP_FLAG, tailMB, NULL);
/* If we failed to complete the packet, throw it away.
* Otherwise send it. */
if (!tailMB) {
PPPDEBUG((LOG_WARNING,
"pppWrite[%d]: Alloc err - dropping pbuf len=%d\n", pd, headMB->len));
/*"pppWrite[%d]: Alloc err - dropping %d:%.*H", pd, headMB->len, LWIP_MIN(headMB->len * 2, 40), headMB->payload)); */
pbuf_free(headMB);
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.proterr);
return PPPERR_ALLOC;
}
PPPDEBUG((LOG_INFO, "pppWrite[%d]: len=%d\n", pd, headMB->len));
/* "pppWrite[%d]: %d:%.*H", pd, headMB->len, LWIP_MIN(headMB->len * 2, 40), headMB->payload)); */
nPut(pc, headMB);
#endif /* PPPOS_SUPPORT */
return PPPERR_NONE;
}
/*
* ppp_send_config - configure the transmit characteristics of
* the ppp interface.
*/
void
ppp_send_config( int unit, int mtu, u32_t asyncmap, int pcomp, int accomp)
{
PPPControl *pc = &pppControl[unit];
int i;
pc->mtu = mtu;
pc->pcomp = pcomp;
pc->accomp = accomp;
/* Load the ACCM bits for the 32 control codes. */
for (i = 0; i < 32/8; i++) {
pc->outACCM[i] = (u_char)((asyncmap >> (8 * i)) & 0xFF);
}
PPPDEBUG((LOG_INFO, "ppp_send_config[%d]: outACCM=%X %X %X %X\n",
unit,
pc->outACCM[0], pc->outACCM[1], pc->outACCM[2], pc->outACCM[3]));
}
/*
* ppp_set_xaccm - set the extended transmit ACCM for the interface.
*/
void
ppp_set_xaccm(int unit, ext_accm *accm)
{
SMEMCPY(pppControl[unit].outACCM, accm, sizeof(ext_accm));
PPPDEBUG((LOG_INFO, "ppp_set_xaccm[%d]: outACCM=%X %X %X %X\n",
unit,
pppControl[unit].outACCM[0],
pppControl[unit].outACCM[1],
pppControl[unit].outACCM[2],
pppControl[unit].outACCM[3]));
}
/*
* ppp_recv_config - configure the receive-side characteristics of
* the ppp interface.
*/
void
ppp_recv_config( int unit, int mru, u32_t asyncmap, int pcomp, int accomp)
{
PPPControl *pc = &pppControl[unit];
int i;
LWIP_UNUSED_ARG(accomp);
LWIP_UNUSED_ARG(pcomp);
LWIP_UNUSED_ARG(mru);
/* Load the ACCM bits for the 32 control codes. */
for (i = 0; i < 32 / 8; i++) {
pc->inACCM[i] = (u_char)(asyncmap >> (i * 8));
}
PPPDEBUG((LOG_INFO, "ppp_recv_config[%d]: inACCM=%X %X %X %X\n",
unit,
pc->inACCM[0], pc->inACCM[1], pc->inACCM[2], pc->inACCM[3]));
}
#if 0
/*
* ccp_test - ask kernel whether a given compression method
* is acceptable for use. Returns 1 if the method and parameters
* are OK, 0 if the method is known but the parameters are not OK
* (e.g. code size should be reduced), or -1 if the method is unknown.
*/
int
ccp_test( int unit, int opt_len, int for_transmit, u_char *opt_ptr)
{
return 0; /* XXX Currently no compression. */
}
/*
* ccp_flags_set - inform kernel about the current state of CCP.
*/
void
ccp_flags_set(int unit, int isopen, int isup)
{
/* XXX */
}
/*
* ccp_fatal_error - returns 1 if decompression was disabled as a
* result of an error detected after decompression of a packet,
* 0 otherwise. This is necessary because of patent nonsense.
*/
int
ccp_fatal_error(int unit)
{
/* XXX */
return 0;
}
#endif
/*
* get_idle_time - return how long the link has been idle.
*/
int
get_idle_time(int u, struct ppp_idle *ip)
{
/* XXX */
LWIP_UNUSED_ARG(u);
LWIP_UNUSED_ARG(ip);
return 0;
}
/*
* Return user specified netmask, modified by any mask we might determine
* for address `addr' (in network byte order).
* Here we scan through the system's list of interfaces, looking for
* any non-point-to-point interfaces which might appear to be on the same
* network as `addr'. If we find any, we OR in their netmask to the
* user-specified netmask.
*/
u32_t
GetMask(u32_t addr)
{
u32_t mask, nmask;
htonl(addr);
if (IN_CLASSA(addr)) { /* determine network mask for address class */
nmask = IN_CLASSA_NET;
} else if (IN_CLASSB(addr)) {
nmask = IN_CLASSB_NET;
} else {
nmask = IN_CLASSC_NET;
}
/* class D nets are disallowed by bad_ip_adrs */
mask = subnetMask | htonl(nmask);
/* XXX
* Scan through the system's network interfaces.
* Get each netmask and OR them into our mask.
*/
return mask;
}
/*
* sifvjcomp - config tcp header compression
*/
int
sifvjcomp( int pd, int vjcomp, int cidcomp, int maxcid)
{
#if PPPOS_SUPPORT && VJ_SUPPORT
PPPControl *pc = &pppControl[pd];
pc->vjEnabled = vjcomp;
pc->vjComp.compressSlot = cidcomp;
pc->vjComp.maxSlotIndex = maxcid;
PPPDEBUG((LOG_INFO, "sifvjcomp: VJ compress enable=%d slot=%d max slot=%d\n",
vjcomp, cidcomp, maxcid));
#endif /* PPPOS_SUPPORT && VJ_SUPPORT */
return 0;
}
/*
* pppifNetifInit - netif init callback
*/
static err_t
pppifNetifInit(struct netif *netif)
{
netif->name[0] = 'p';
netif->name[1] = 'p';
netif->output = pppifOutput;
netif->mtu = pppMTU((int)netif->state);
return ERR_OK;
}
/*
* sifup - Config the interface up and enable IP packets to pass.
*/
int
sifup(int pd)
{
PPPControl *pc = &pppControl[pd];
int st = 1;
if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) {
st = 0;
PPPDEBUG((LOG_WARNING, "sifup[%d]: bad parms\n", pd));
} else {
netif_remove(&pc->netif);
if (netif_add(&pc->netif, &pc->addrs.our_ipaddr, &pc->addrs.netmask, &pc->addrs.his_ipaddr, (void *)pd, pppifNetifInit, ip_input)) {
netif_set_up(&pc->netif);
#if LWIP_DHCP
/* ugly workaround for storing a reference to the ppp related info*/
pc->netif.dhcp = (struct dhcp *) &pc->addrs;
#endif /* LWIP_DHCP */
pc->if_up = 1;
pc->errCode = PPPERR_NONE;
PPPDEBUG((LOG_DEBUG, "sifup: unit %d: linkStatusCB=%lx errCode=%d\n", pd, pc->linkStatusCB, pc->errCode));
if(pc->linkStatusCB) {
pc->linkStatusCB(pc->linkStatusCtx, pc->errCode, &pc->addrs);
}
} else {
st = 0;
PPPDEBUG((LOG_ERR, "sifup[%d]: netif_add failed\n", pd));
}
}
return st;
}
/*
* sifnpmode - Set the mode for handling packets for a given NP.
*/
int
sifnpmode(int u, int proto, enum NPmode mode)
{
LWIP_UNUSED_ARG(u);
LWIP_UNUSED_ARG(proto);
LWIP_UNUSED_ARG(mode);
return 0;
}
/*
* sifdown - Config the interface down and disable IP.
*/
int
sifdown(int pd)
{
PPPControl *pc = &pppControl[pd];
int st = 1;
if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) {
st = 0;
PPPDEBUG((LOG_WARNING, "sifdown[%d]: bad parms\n", pd));
} else {
pc->if_up = 0;
netif_remove(&pc->netif);
PPPDEBUG((LOG_DEBUG, "sifdown: unit %d: linkStatusCB=%lx errCode=%d\n", pd, pc->linkStatusCB, pc->errCode));
if(pc->linkStatusCB) {
pc->linkStatusCB(pc->linkStatusCtx, PPPERR_CONNECT, NULL);
}
}
return st;
}
/**
* sifaddr - Config the interface IP addresses and netmask.
* @param pd Interface unit ???
* @param o Our IP address ???
* @param h His IP address ???
* @param m IP subnet mask ???
* @param ns1 Primary DNS
* @param ns2 Secondary DNS
*/
int
sifaddr( int pd, u32_t o, u32_t h, u32_t m, u32_t ns1, u32_t ns2)
{
PPPControl *pc = &pppControl[pd];
int st = 1;
if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) {
st = 0;
PPPDEBUG((LOG_WARNING, "sifup[%d]: bad parms\n", pd));
} else {
SMEMCPY(&pc->addrs.our_ipaddr, &o, sizeof(o));
SMEMCPY(&pc->addrs.his_ipaddr, &h, sizeof(h));
SMEMCPY(&pc->addrs.netmask, &m, sizeof(m));
SMEMCPY(&pc->addrs.dns1, &ns1, sizeof(ns1));
SMEMCPY(&pc->addrs.dns2, &ns2, sizeof(ns2));
}
return st;
}
/**
* cifaddr - Clear the interface IP addresses, and delete routes
* through the interface if possible.
* @param pd Interface unit ???
* @param o Our IP address ???
* @param h IP broadcast address ???
*/
int
cifaddr( int pd, u32_t o, u32_t h)
{
PPPControl *pc = &pppControl[pd];
int st = 1;
LWIP_UNUSED_ARG(o);
LWIP_UNUSED_ARG(h);
if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) {
st = 0;
PPPDEBUG((LOG_WARNING, "sifup[%d]: bad parms\n", pd));
} else {
IP4_ADDR(&pc->addrs.our_ipaddr, 0,0,0,0);
IP4_ADDR(&pc->addrs.his_ipaddr, 0,0,0,0);
IP4_ADDR(&pc->addrs.netmask, 255,255,255,0);
IP4_ADDR(&pc->addrs.dns1, 0,0,0,0);
IP4_ADDR(&pc->addrs.dns2, 0,0,0,0);
}
return st;
}
/*
* sifdefaultroute - assign a default route through the address given.
*/
int
sifdefaultroute(int pd, u32_t l, u32_t g)
{
PPPControl *pc = &pppControl[pd];
int st = 1;
LWIP_UNUSED_ARG(l);
LWIP_UNUSED_ARG(g);
if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) {
st = 0;
PPPDEBUG((LOG_WARNING, "sifup[%d]: bad parms\n", pd));
} else {
netif_set_default(&pc->netif);
}
/* TODO: check how PPP handled the netMask, previously not set by ipSetDefault */
return st;
}
/*
* cifdefaultroute - delete a default route through the address given.
*/
int
cifdefaultroute(int pd, u32_t l, u32_t g)
{
PPPControl *pc = &pppControl[pd];
int st = 1;
LWIP_UNUSED_ARG(l);
LWIP_UNUSED_ARG(g);
if (pd < 0 || pd >= NUM_PPP || !pc->openFlag) {
st = 0;
PPPDEBUG((LOG_WARNING, "sifup[%d]: bad parms\n", pd));
} else {
netif_set_default(NULL);
}
return st;
}
/**********************************/
/*** LOCAL FUNCTION DEFINITIONS ***/
/**********************************/
#if PPPOS_SUPPORT
/* The main PPP process function. This implements the state machine according
* to section 4 of RFC 1661: The Point-To-Point Protocol. */
static void
pppMain(void *arg)
{
int pd = (int)arg;
struct pbuf *p;
PPPControl* pc;
int c;
pc = &pppControl[pd];
p = pbuf_alloc(PBUF_RAW, PPP_MRU+PPP_HDRLEN, PBUF_RAM);
if (!p) {
LWIP_ASSERT("p != NULL", p);
pc->errCode = PPPERR_ALLOC;
goto out;
}
/*
* Start the connection and handle incoming events (packet or timeout).
*/
PPPDEBUG((LOG_INFO, "pppMain: unit %d: Connecting\n", pd));
tcpip_callback(pppStartCB, arg);
while (lcp_phase[pd] != PHASE_DEAD) {
if (pc->kill_link) {
PPPDEBUG((LOG_DEBUG, "pppMain: unit %d kill_link -> pppStopCB\n", pd));
pc->errCode = PPPERR_USER;
/* This will leave us at PHASE_DEAD. */
tcpip_callback(pppStopCB, arg);
pc->kill_link = 0;
} else if (pc->sig_hup) {
PPPDEBUG((LOG_DEBUG, "pppMain: unit %d sig_hup -> pppHupCB\n", pd));
pc->sig_hup = 0;
tcpip_callback(pppHupCB, arg);
} else {
c = sio_read(pc->fd, p->payload, p->len);
if(c > 0) {
pppInProc(pd, p->payload, c);
} else {
PPPDEBUG((LOG_DEBUG, "pppMain: unit %d sio_read len=%d returned %d\n", pd, p->len, c));
sys_msleep(1); /* give other tasks a chance to run */
}
}
}
PPPDEBUG((LOG_INFO, "pppMain: unit %d: PHASE_DEAD\n", pd));
pppDrop(pc); /* bug fix #17726 */
pbuf_free(p);
out:
PPPDEBUG((LOG_DEBUG, "pppMain: unit %d: linkStatusCB=%lx errCode=%d\n", pd, pc->linkStatusCB, pc->errCode));
if(pc->linkStatusCB) {
pc->linkStatusCB(pc->linkStatusCtx, pc->errCode ? pc->errCode : PPPERR_PROTOCOL, NULL);
}
pc->openFlag = 0;
}
#endif /* PPPOS_SUPPORT */
#if PPPOE_SUPPORT
void
pppOverEthernetInitFailed(void* arg)
{
PPPControl* pc;
int pd = (int)arg;
pppHupCB(arg);
pppStopCB(arg);
pc = &pppControl[pd];
pppoe_destroy(&pc->netif);
pc->openFlag = 0;
if(pc->linkStatusCB) {
pc->linkStatusCB(pc->linkStatusCtx, pc->errCode ? pc->errCode : PPPERR_PROTOCOL, NULL);
}
}
static void
pppOverEthernetLinkStatusCB(int pd, int up)
{
if(up) {
PPPDEBUG((LOG_INFO, "pppMain: unit %d: Connecting\n", pd));
tcpip_callback(pppStartCB, (void*)pd);
} else {
PPPControl* pc;
pc = &pppControl[pd];
tcpip_callback(pppOverEthernetInitFailed, (void*)pd);
}
}
#endif /* PPPOE_SUPPORT */
struct pbuf *
pppSingleBuf(struct pbuf *p)
{
struct pbuf *q, *b;
u_char *pl;
if(p->tot_len == p->len) {
return p;
}
q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
if(!q) {
PPPDEBUG((LOG_ERR,
"pppSingleBuf: unable to alloc new buf (%d)\n", p->tot_len));
return p; /* live dangerously */
}
for(b = p, pl = q->payload; b != NULL; b = b->next) {
MEMCPY(pl, b->payload, b->len);
pl += b->len;
}
pbuf_free(p);
return q;
}
struct pppInputHeader {
int unit;
u16_t proto;
};
/*
* Pass the processed input packet to the appropriate handler.
* This function and all handlers run in the context of the tcpip_thread
*/
static void
pppInput(void *arg)
{
struct pbuf *nb = (struct pbuf *)arg;
u16_t protocol;
int pd;
pd = ((struct pppInputHeader *)nb->payload)->unit;
protocol = ((struct pppInputHeader *)nb->payload)->proto;
if(pbuf_header(nb, -(int)sizeof(struct pppInputHeader))) {
LWIP_ASSERT("pbuf_header failed\n", 0);
goto drop;
}
LINK_STATS_INC(link.recv);
/*
* Toss all non-LCP packets unless LCP is OPEN.
* Until we get past the authentication phase, toss all packets
* except LCP, LQR and authentication packets.
*/
if((lcp_phase[pd] <= PHASE_AUTHENTICATE) && (protocol != PPP_LCP)) {
if(!((protocol == PPP_LQR) || (protocol == PPP_PAP) || (protocol == PPP_CHAP)) ||
(lcp_phase[pd] != PHASE_AUTHENTICATE)) {
PPPDEBUG((LOG_INFO, "pppInput: discarding proto 0x%04X in phase %d\n", protocol, lcp_phase[pd]));
goto drop;
}
}
switch(protocol) {
case PPP_VJC_COMP: /* VJ compressed TCP */
#if VJ_SUPPORT
PPPDEBUG((LOG_INFO, "pppInput[%d]: vj_comp in pbuf len=%d\n", pd, nb->len));
/*
* Clip off the VJ header and prepend the rebuilt TCP/IP header and
* pass the result to IP.
*/
if ((vj_uncompress_tcp(&nb, &pppControl[pd].vjComp) >= 0) && (pppControl[pd].netif.input)) {
pppControl[pd].netif.input(nb, &pppControl[pd].netif);
return;
}
/* Something's wrong so drop it. */
PPPDEBUG((LOG_WARNING, "pppInput[%d]: Dropping VJ compressed\n", pd));
#else /* VJ_SUPPORT */
/* No handler for this protocol so drop the packet. */
PPPDEBUG((LOG_INFO, "pppInput[%d]: drop VJ Comp in %d:%s\n", pd, nb->len, nb->payload));
#endif /* VJ_SUPPORT */
break;
case PPP_VJC_UNCOMP: /* VJ uncompressed TCP */
#if VJ_SUPPORT
PPPDEBUG((LOG_INFO, "pppInput[%d]: vj_un in pbuf len=%d\n", pd, nb->len));
/*
* Process the TCP/IP header for VJ header compression and then pass
* the packet to IP.
*/
if ((vj_uncompress_uncomp(nb, &pppControl[pd].vjComp) >= 0) && pppControl[pd].netif.input) {
pppControl[pd].netif.input(nb, &pppControl[pd].netif);
return;
}
/* Something's wrong so drop it. */
PPPDEBUG((LOG_WARNING, "pppInput[%d]: Dropping VJ uncompressed\n", pd));
#else /* VJ_SUPPORT */
/* No handler for this protocol so drop the packet. */
PPPDEBUG((LOG_INFO,
"pppInput[%d]: drop VJ UnComp in %d:.*H\n",
pd, nb->len, LWIP_MIN(nb->len * 2, 40), nb->payload));
#endif /* VJ_SUPPORT */
break;
case PPP_IP: /* Internet Protocol */
PPPDEBUG((LOG_INFO, "pppInput[%d]: ip in pbuf len=%d\n", pd, nb->len));
if (pppControl[pd].netif.input) {
pppControl[pd].netif.input(nb, &pppControl[pd].netif);
return;
}
break;
default: {
struct protent *protp;
int i;
/*
* Upcall the proper protocol input routine.
*/
for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) {
if (protp->protocol == protocol && protp->enabled_flag) {
PPPDEBUG((LOG_INFO, "pppInput[%d]: %s len=%d\n", pd, protp->name, nb->len));
nb = pppSingleBuf(nb);
(*protp->input)(pd, nb->payload, nb->len);
goto out;
}
}
/* No handler for this protocol so reject the packet. */
PPPDEBUG((LOG_INFO, "pppInput[%d]: rejecting unsupported proto 0x%04X len=%d\n", pd, protocol, nb->len));
if (pbuf_header(nb, sizeof(protocol))) {
LWIP_ASSERT("pbuf_header failed\n", 0);
goto drop;
}
#if BYTE_ORDER == LITTLE_ENDIAN
protocol = htons(protocol);
SMEMCPY(nb->payload, &protocol, sizeof(protocol));
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
lcp_sprotrej(pd, nb->payload, nb->len);
}
break;
}
drop:
LINK_STATS_INC(link.drop);
out:
pbuf_free(nb);
return;
}
#if PPPOS_SUPPORT
/*
* Drop the input packet.
*/
static void
pppDrop(PPPControl *pc)
{
if (pc->inHead != NULL) {
#if 0
PPPDEBUG((LOG_INFO, "pppDrop: %d:%.*H\n", pc->inHead->len, min(60, pc->inHead->len * 2), pc->inHead->payload));
#endif
PPPDEBUG((LOG_INFO, "pppDrop: pbuf len=%d\n", pc->inHead->len));
if (pc->inTail && (pc->inTail != pc->inHead)) {
pbuf_free(pc->inTail);
}
pbuf_free(pc->inHead);
pc->inHead = NULL;
pc->inTail = NULL;
}
#if VJ_SUPPORT
vj_uncompress_err(&pc->vjComp);
#endif /* VJ_SUPPORT */
LINK_STATS_INC(link.drop);
}
/**
* Process a received octet string.
*/
static void
pppInProc(int pd, u_char *s, int l)
{
PPPControl *pc = &pppControl[pd];
struct pbuf *nextNBuf;
u_char curChar;
PPPDEBUG((LOG_DEBUG, "pppInProc[%d]: got %d bytes\n", pd, l));
while (l-- > 0) {
curChar = *s++;
/* Handle special characters. */
if (ESCAPE_P(pc->inACCM, curChar)) {
/* Check for escape sequences. */
/* XXX Note that this does not handle an escaped 0x5d character which
* would appear as an escape character. Since this is an ASCII ']'
* and there is no reason that I know of to escape it, I won't complicate
* the code to handle this case. GLL */
if (curChar == PPP_ESCAPE) {
pc->inEscaped = 1;
/* Check for the flag character. */
} else if (curChar == PPP_FLAG) {
/* If this is just an extra flag character, ignore it. */
if (pc->inState <= PDADDRESS) {
/* ignore it */;
/* If we haven't received the packet header, drop what has come in. */
} else if (pc->inState < PDDATA) {
PPPDEBUG((LOG_WARNING,
"pppInProc[%d]: Dropping incomplete packet %d\n",
pd, pc->inState));
LINK_STATS_INC(link.lenerr);
pppDrop(pc);
/* If the fcs is invalid, drop the packet. */
} else if (pc->inFCS != PPP_GOODFCS) {
PPPDEBUG((LOG_INFO,
"pppInProc[%d]: Dropping bad fcs 0x%04X proto=0x%04X\n",
pd, pc->inFCS, pc->inProtocol));
LINK_STATS_INC(link.chkerr);
pppDrop(pc);
/* Otherwise it's a good packet so pass it on. */
} else {
/* Trim off the checksum. */
if(pc->inTail->len >= 2) {
pc->inTail->len -= 2;
pc->inTail->tot_len = pc->inTail->len;
if (pc->inTail != pc->inHead) {
pbuf_cat(pc->inHead, pc->inTail);
}
} else {
pc->inTail->tot_len = pc->inTail->len;
if (pc->inTail != pc->inHead) {
pbuf_cat(pc->inHead, pc->inTail);
}
pbuf_realloc(pc->inHead, pc->inHead->tot_len - 2);
}
/* Dispatch the packet thereby consuming it. */
if(tcpip_callback(pppInput, pc->inHead) != ERR_OK) {
PPPDEBUG((LOG_ERR, "pppInProc[%d]: tcpip_callback() failed, dropping packet\n", pd));
pbuf_free(pc->inHead);
LINK_STATS_INC(link.drop);
}
pc->inHead = NULL;
pc->inTail = NULL;
}
/* Prepare for a new packet. */
pc->inFCS = PPP_INITFCS;
pc->inState = PDADDRESS;
pc->inEscaped = 0;
/* Other characters are usually control characters that may have
* been inserted by the physical layer so here we just drop them. */
} else {
PPPDEBUG((LOG_WARNING,
"pppInProc[%d]: Dropping ACCM char <%d>\n", pd, curChar));
}
/* Process other characters. */
} else {
/* Unencode escaped characters. */
if (pc->inEscaped) {
pc->inEscaped = 0;
curChar ^= PPP_TRANS;
}
/* Process character relative to current state. */
switch(pc->inState) {
case PDIDLE: /* Idle state - waiting. */
/* Drop the character if it's not 0xff
* we would have processed a flag character above. */
if (curChar != PPP_ALLSTATIONS) {
break;
}
/* Fall through */
case PDSTART: /* Process start flag. */
/* Prepare for a new packet. */
pc->inFCS = PPP_INITFCS;
/* Fall through */
case PDADDRESS: /* Process address field. */
if (curChar == PPP_ALLSTATIONS) {
pc->inState = PDCONTROL;
break;
}
/* Else assume compressed address and control fields so
* fall through to get the protocol... */
case PDCONTROL: /* Process control field. */
/* If we don't get a valid control code, restart. */
if (curChar == PPP_UI) {
pc->inState = PDPROTOCOL1;
break;
}
#if 0
else {
PPPDEBUG((LOG_WARNING,
"pppInProc[%d]: Invalid control <%d>\n", pd, curChar));
pc->inState = PDSTART;
}
#endif
case PDPROTOCOL1: /* Process protocol field 1. */
/* If the lower bit is set, this is the end of the protocol
* field. */
if (curChar & 1) {
pc->inProtocol = curChar;
pc->inState = PDDATA;
} else {
pc->inProtocol = (u_int)curChar << 8;
pc->inState = PDPROTOCOL2;
}
break;
case PDPROTOCOL2: /* Process protocol field 2. */
pc->inProtocol |= curChar;
pc->inState = PDDATA;
break;
case PDDATA: /* Process data byte. */
/* Make space to receive processed data. */
if (pc->inTail == NULL || pc->inTail->len == PBUF_POOL_BUFSIZE) {
if(pc->inTail) {
pc->inTail->tot_len = pc->inTail->len;
if (pc->inTail != pc->inHead) {
pbuf_cat(pc->inHead, pc->inTail);
}
}
/* If we haven't started a packet, we need a packet header. */
nextNBuf = pbuf_alloc(PBUF_RAW, 0, PBUF_POOL);
if (nextNBuf == NULL) {
/* No free buffers. Drop the input packet and let the
* higher layers deal with it. Continue processing
* the received pbuf chain in case a new packet starts. */
PPPDEBUG((LOG_ERR, "pppInProc[%d]: NO FREE MBUFS!\n", pd));
LINK_STATS_INC(link.memerr);
pppDrop(pc);
pc->inState = PDSTART; /* Wait for flag sequence. */
break;
}
if (pc->inHead == NULL) {
struct pppInputHeader *pih = nextNBuf->payload;
pih->unit = pd;
pih->proto = pc->inProtocol;
nextNBuf->len += sizeof(*pih);
pc->inHead = nextNBuf;
}
pc->inTail = nextNBuf;
}
/* Load character into buffer. */
((u_char*)pc->inTail->payload)[pc->inTail->len++] = curChar;
break;
}
/* update the frame check sequence number. */
pc->inFCS = PPP_FCS(pc->inFCS, curChar);
}
}
avRandomize();
}
#endif /* PPPOS_SUPPORT */
#if PPPOE_SUPPORT
void
pppInProcOverEthernet(int pd, struct pbuf *pb)
{
struct pppInputHeader *pih;
u16_t inProtocol;
if(pb->len < sizeof(inProtocol)) {
PPPDEBUG((LOG_ERR, "pppInProcOverEthernet: too small for protocol field\n"));
goto drop;
}
inProtocol = (((u8_t *)pb->payload)[0] << 8) | ((u8_t*)pb->payload)[1];
/* make room for pppInputHeader - should not fail */
if (pbuf_header(pb, sizeof(*pih) - sizeof(inProtocol)) != 0) {
PPPDEBUG((LOG_ERR, "pppInProcOverEthernet: could not allocate room for header\n"));
goto drop;
}
pih = pb->payload;
pih->unit = pd;
pih->proto = inProtocol;
/* Dispatch the packet thereby consuming it. */
if(tcpip_callback(pppInput, pb) != ERR_OK) {
PPPDEBUG((LOG_ERR, "pppInProcOverEthernet[%d]: tcpip_callback() failed, dropping packet\n", pd));
goto drop;
}
return;
drop:
LINK_STATS_INC(link.drop);
pbuf_free(pb);
return;
}
#endif /* PPPOE_SUPPORT */
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/ppp.c | C | oos | 57,136 |
/*****************************************************************************
* fsm.c - Network Control Protocol Finite State Machine program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-01 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original based on BSD fsm.c.
*****************************************************************************/
/*
* fsm.c - {Link, IP} Control Protocol Finite State Machine.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/*
* TODO:
* Randomize fsm id on link/init.
* Deal with variable outgoing MTU.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "pppdebug.h"
#include "fsm.h"
/*************************/
/*** LOCAL DEFINITIONS ***/
/*************************/
#if PPP_DEBUG
static const char *ppperr_strerr[] = {
"LS_INITIAL", /* LS_INITIAL 0 */
"LS_STARTING", /* LS_STARTING 1 */
"LS_CLOSED", /* LS_CLOSED 2 */
"LS_STOPPED", /* LS_STOPPED 3 */
"LS_CLOSING", /* LS_CLOSING 4 */
"LS_STOPPING", /* LS_STOPPING 5 */
"LS_REQSENT", /* LS_REQSENT 6 */
"LS_ACKRCVD", /* LS_ACKRCVD 7 */
"LS_ACKSENT", /* LS_ACKSENT 8 */
"LS_OPENED" /* LS_OPENED 9 */
};
#endif /* PPP_DEBUG */
/************************/
/*** LOCAL DATA TYPES ***/
/************************/
/***********************************/
/*** LOCAL FUNCTION DECLARATIONS ***/
/***********************************/
static void fsm_timeout (void *);
static void fsm_rconfreq (fsm *, u_char, u_char *, int);
static void fsm_rconfack (fsm *, int, u_char *, int);
static void fsm_rconfnakrej (fsm *, int, int, u_char *, int);
static void fsm_rtermreq (fsm *, int, u_char *, int);
static void fsm_rtermack (fsm *);
static void fsm_rcoderej (fsm *, u_char *, int);
static void fsm_sconfreq (fsm *, int);
#define PROTO_NAME(f) ((f)->callbacks->proto_name)
/******************************/
/*** PUBLIC DATA STRUCTURES ***/
/******************************/
/*****************************/
/*** LOCAL DATA STRUCTURES ***/
/*****************************/
int peer_mru[NUM_PPP];
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
/*
* fsm_init - Initialize fsm.
*
* Initialize fsm state.
*/
void
fsm_init(fsm *f)
{
f->state = LS_INITIAL;
f->flags = 0;
f->id = 0; /* XXX Start with random id? */
f->timeouttime = FSM_DEFTIMEOUT;
f->maxconfreqtransmits = FSM_DEFMAXCONFREQS;
f->maxtermtransmits = FSM_DEFMAXTERMREQS;
f->maxnakloops = FSM_DEFMAXNAKLOOPS;
f->term_reason_len = 0;
}
/*
* fsm_lowerup - The lower layer is up.
*/
void
fsm_lowerup(fsm *f)
{
int oldState = f->state;
LWIP_UNUSED_ARG(oldState);
switch( f->state ) {
case LS_INITIAL:
f->state = LS_CLOSED;
break;
case LS_STARTING:
if( f->flags & OPT_SILENT ) {
f->state = LS_STOPPED;
} else {
/* Send an initial configure-request */
fsm_sconfreq(f, 0);
f->state = LS_REQSENT;
}
break;
default:
FSMDEBUG((LOG_INFO, "%s: Up event in state %d (%s)!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
FSMDEBUG((LOG_INFO, "%s: lowerup state %d (%s) -> %d (%s)\n",
PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state]));
}
/*
* fsm_lowerdown - The lower layer is down.
*
* Cancel all timeouts and inform upper layers.
*/
void
fsm_lowerdown(fsm *f)
{
int oldState = f->state;
LWIP_UNUSED_ARG(oldState);
switch( f->state ) {
case LS_CLOSED:
f->state = LS_INITIAL;
break;
case LS_STOPPED:
f->state = LS_STARTING;
if( f->callbacks->starting ) {
(*f->callbacks->starting)(f);
}
break;
case LS_CLOSING:
f->state = LS_INITIAL;
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
break;
case LS_STOPPING:
case LS_REQSENT:
case LS_ACKRCVD:
case LS_ACKSENT:
f->state = LS_STARTING;
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
break;
case LS_OPENED:
if( f->callbacks->down ) {
(*f->callbacks->down)(f);
}
f->state = LS_STARTING;
break;
default:
FSMDEBUG((LOG_INFO, "%s: Down event in state %d (%s)!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
FSMDEBUG((LOG_INFO, "%s: lowerdown state %d (%s) -> %d (%s)\n",
PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state]));
}
/*
* fsm_open - Link is allowed to come up.
*/
void
fsm_open(fsm *f)
{
int oldState = f->state;
LWIP_UNUSED_ARG(oldState);
switch( f->state ) {
case LS_INITIAL:
f->state = LS_STARTING;
if( f->callbacks->starting ) {
(*f->callbacks->starting)(f);
}
break;
case LS_CLOSED:
if( f->flags & OPT_SILENT ) {
f->state = LS_STOPPED;
} else {
/* Send an initial configure-request */
fsm_sconfreq(f, 0);
f->state = LS_REQSENT;
}
break;
case LS_CLOSING:
f->state = LS_STOPPING;
/* fall through */
case LS_STOPPED:
case LS_OPENED:
if( f->flags & OPT_RESTART ) {
fsm_lowerdown(f);
fsm_lowerup(f);
}
break;
}
FSMDEBUG((LOG_INFO, "%s: open state %d (%s) -> %d (%s)\n",
PROTO_NAME(f), oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state]));
}
/*
* fsm_close - Start closing connection.
*
* Cancel timeouts and either initiate close or possibly go directly to
* the LS_CLOSED state.
*/
void
fsm_close(fsm *f, char *reason)
{
int oldState = f->state;
LWIP_UNUSED_ARG(oldState);
f->term_reason = reason;
f->term_reason_len = (reason == NULL? 0: strlen(reason));
switch( f->state ) {
case LS_STARTING:
f->state = LS_INITIAL;
break;
case LS_STOPPED:
f->state = LS_CLOSED;
break;
case LS_STOPPING:
f->state = LS_CLOSING;
break;
case LS_REQSENT:
case LS_ACKRCVD:
case LS_ACKSENT:
case LS_OPENED:
if( f->state != LS_OPENED ) {
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
} else if( f->callbacks->down ) {
(*f->callbacks->down)(f); /* Inform upper layers we're down */
}
/* Init restart counter, send Terminate-Request */
f->retransmits = f->maxtermtransmits;
fsm_sdata(f, TERMREQ, f->reqid = ++f->id,
(u_char *) f->term_reason, f->term_reason_len);
TIMEOUT(fsm_timeout, f, f->timeouttime);
--f->retransmits;
f->state = LS_CLOSING;
break;
}
FSMDEBUG((LOG_INFO, "%s: close reason=%s state %d (%s) -> %d (%s)\n",
PROTO_NAME(f), reason, oldState, ppperr_strerr[oldState], f->state, ppperr_strerr[f->state]));
}
/*
* fsm_sdata - Send some data.
*
* Used for all packets sent to our peer by this module.
*/
void
fsm_sdata( fsm *f, u_char code, u_char id, u_char *data, int datalen)
{
u_char *outp;
int outlen;
/* Adjust length to be smaller than MTU */
outp = outpacket_buf[f->unit];
if (datalen > peer_mru[f->unit] - (int)HEADERLEN) {
datalen = peer_mru[f->unit] - HEADERLEN;
}
if (datalen && data != outp + PPP_HDRLEN + HEADERLEN) {
BCOPY(data, outp + PPP_HDRLEN + HEADERLEN, datalen);
}
outlen = datalen + HEADERLEN;
MAKEHEADER(outp, f->protocol);
PUTCHAR(code, outp);
PUTCHAR(id, outp);
PUTSHORT(outlen, outp);
pppWrite(f->unit, outpacket_buf[f->unit], outlen + PPP_HDRLEN);
FSMDEBUG((LOG_INFO, "fsm_sdata(%s): Sent code %d,%d,%d.\n",
PROTO_NAME(f), code, id, outlen));
}
/*
* fsm_input - Input packet.
*/
void
fsm_input(fsm *f, u_char *inpacket, int l)
{
u_char *inp = inpacket;
u_char code, id;
int len;
/*
* Parse header (code, id and length).
* If packet too short, drop it.
*/
if (l < HEADERLEN) {
FSMDEBUG((LOG_WARNING, "fsm_input(%x): Rcvd short header.\n",
f->protocol));
return;
}
GETCHAR(code, inp);
GETCHAR(id, inp);
GETSHORT(len, inp);
if (len < HEADERLEN) {
FSMDEBUG((LOG_INFO, "fsm_input(%x): Rcvd illegal length.\n",
f->protocol));
return;
}
if (len > l) {
FSMDEBUG((LOG_INFO, "fsm_input(%x): Rcvd short packet.\n",
f->protocol));
return;
}
len -= HEADERLEN; /* subtract header length */
if( f->state == LS_INITIAL || f->state == LS_STARTING ) {
FSMDEBUG((LOG_INFO, "fsm_input(%x): Rcvd packet in state %d (%s).\n",
f->protocol, f->state, ppperr_strerr[f->state]));
return;
}
FSMDEBUG((LOG_INFO, "fsm_input(%s):%d,%d,%d\n", PROTO_NAME(f), code, id, l));
/*
* Action depends on code.
*/
switch (code) {
case CONFREQ:
fsm_rconfreq(f, id, inp, len);
break;
case CONFACK:
fsm_rconfack(f, id, inp, len);
break;
case CONFNAK:
case CONFREJ:
fsm_rconfnakrej(f, code, id, inp, len);
break;
case TERMREQ:
fsm_rtermreq(f, id, inp, len);
break;
case TERMACK:
fsm_rtermack(f);
break;
case CODEREJ:
fsm_rcoderej(f, inp, len);
break;
default:
if( !f->callbacks->extcode ||
!(*f->callbacks->extcode)(f, code, id, inp, len) ) {
fsm_sdata(f, CODEREJ, ++f->id, inpacket, len + HEADERLEN);
}
break;
}
}
/*
* fsm_protreject - Peer doesn't speak this protocol.
*
* Treat this as a catastrophic error (RXJ-).
*/
void
fsm_protreject(fsm *f)
{
switch( f->state ) {
case LS_CLOSING:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
/* fall through */
case LS_CLOSED:
f->state = LS_CLOSED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
break;
case LS_STOPPING:
case LS_REQSENT:
case LS_ACKRCVD:
case LS_ACKSENT:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
/* fall through */
case LS_STOPPED:
f->state = LS_STOPPED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
break;
case LS_OPENED:
if( f->callbacks->down ) {
(*f->callbacks->down)(f);
}
/* Init restart counter, send Terminate-Request */
f->retransmits = f->maxtermtransmits;
fsm_sdata(f, TERMREQ, f->reqid = ++f->id,
(u_char *) f->term_reason, f->term_reason_len);
TIMEOUT(fsm_timeout, f, f->timeouttime);
--f->retransmits;
f->state = LS_STOPPING;
break;
default:
FSMDEBUG((LOG_INFO, "%s: Protocol-reject event in state %d (%s)!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
}
/**********************************/
/*** LOCAL FUNCTION DEFINITIONS ***/
/**********************************/
/*
* fsm_timeout - Timeout expired.
*/
static void
fsm_timeout(void *arg)
{
fsm *f = (fsm *) arg;
switch (f->state) {
case LS_CLOSING:
case LS_STOPPING:
if( f->retransmits <= 0 ) {
FSMDEBUG((LOG_WARNING, "%s: timeout sending Terminate-Request state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
/*
* We've waited for an ack long enough. Peer probably heard us.
*/
f->state = (f->state == LS_CLOSING)? LS_CLOSED: LS_STOPPED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
} else {
FSMDEBUG((LOG_WARNING, "%s: timeout resending Terminate-Requests state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
/* Send Terminate-Request */
fsm_sdata(f, TERMREQ, f->reqid = ++f->id,
(u_char *) f->term_reason, f->term_reason_len);
TIMEOUT(fsm_timeout, f, f->timeouttime);
--f->retransmits;
}
break;
case LS_REQSENT:
case LS_ACKRCVD:
case LS_ACKSENT:
if (f->retransmits <= 0) {
FSMDEBUG((LOG_WARNING, "%s: timeout sending Config-Requests state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
f->state = LS_STOPPED;
if( (f->flags & OPT_PASSIVE) == 0 && f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
} else {
FSMDEBUG((LOG_WARNING, "%s: timeout resending Config-Request state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
/* Retransmit the configure-request */
if (f->callbacks->retransmit) {
(*f->callbacks->retransmit)(f);
}
fsm_sconfreq(f, 1); /* Re-send Configure-Request */
if( f->state == LS_ACKRCVD ) {
f->state = LS_REQSENT;
}
}
break;
default:
FSMDEBUG((LOG_INFO, "%s: Timeout event in state %d (%s)!\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
}
}
/*
* fsm_rconfreq - Receive Configure-Request.
*/
static void
fsm_rconfreq(fsm *f, u_char id, u_char *inp, int len)
{
int code, reject_if_disagree;
FSMDEBUG((LOG_INFO, "fsm_rconfreq(%s): Rcvd id %d state=%d (%s)\n",
PROTO_NAME(f), id, f->state, ppperr_strerr[f->state]));
switch( f->state ) {
case LS_CLOSED:
/* Go away, we're closed */
fsm_sdata(f, TERMACK, id, NULL, 0);
return;
case LS_CLOSING:
case LS_STOPPING:
return;
case LS_OPENED:
/* Go down and restart negotiation */
if( f->callbacks->down ) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
break;
case LS_STOPPED:
/* Negotiation started by our peer */
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = LS_REQSENT;
break;
}
/*
* Pass the requested configuration options
* to protocol-specific code for checking.
*/
if (f->callbacks->reqci) { /* Check CI */
reject_if_disagree = (f->nakloops >= f->maxnakloops);
code = (*f->callbacks->reqci)(f, inp, &len, reject_if_disagree);
} else if (len) {
code = CONFREJ; /* Reject all CI */
} else {
code = CONFACK;
}
/* send the Ack, Nak or Rej to the peer */
fsm_sdata(f, (u_char)code, id, inp, len);
if (code == CONFACK) {
if (f->state == LS_ACKRCVD) {
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
f->state = LS_OPENED;
if (f->callbacks->up) {
(*f->callbacks->up)(f); /* Inform upper layers */
}
} else {
f->state = LS_ACKSENT;
}
f->nakloops = 0;
} else {
/* we sent CONFACK or CONFREJ */
if (f->state != LS_ACKRCVD) {
f->state = LS_REQSENT;
}
if( code == CONFNAK ) {
++f->nakloops;
}
}
}
/*
* fsm_rconfack - Receive Configure-Ack.
*/
static void
fsm_rconfack(fsm *f, int id, u_char *inp, int len)
{
FSMDEBUG((LOG_INFO, "fsm_rconfack(%s): Rcvd id %d state=%d (%s)\n",
PROTO_NAME(f), id, f->state, ppperr_strerr[f->state]));
if (id != f->reqid || f->seen_ack) { /* Expected id? */
return; /* Nope, toss... */
}
if( !(f->callbacks->ackci? (*f->callbacks->ackci)(f, inp, len): (len == 0)) ) {
/* Ack is bad - ignore it */
FSMDEBUG((LOG_INFO, "%s: received bad Ack (length %d)\n",
PROTO_NAME(f), len));
return;
}
f->seen_ack = 1;
switch (f->state) {
case LS_CLOSED:
case LS_STOPPED:
fsm_sdata(f, TERMACK, (u_char)id, NULL, 0);
break;
case LS_REQSENT:
f->state = LS_ACKRCVD;
f->retransmits = f->maxconfreqtransmits;
break;
case LS_ACKRCVD:
/* Huh? an extra valid Ack? oh well... */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
fsm_sconfreq(f, 0);
f->state = LS_REQSENT;
break;
case LS_ACKSENT:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
f->state = LS_OPENED;
f->retransmits = f->maxconfreqtransmits;
if (f->callbacks->up) {
(*f->callbacks->up)(f); /* Inform upper layers */
}
break;
case LS_OPENED:
/* Go down and restart negotiation */
if (f->callbacks->down) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = LS_REQSENT;
break;
}
}
/*
* fsm_rconfnakrej - Receive Configure-Nak or Configure-Reject.
*/
static void
fsm_rconfnakrej(fsm *f, int code, int id, u_char *inp, int len)
{
int (*proc) (fsm *, u_char *, int);
int ret;
FSMDEBUG((LOG_INFO, "fsm_rconfnakrej(%s): Rcvd id %d state=%d (%s)\n",
PROTO_NAME(f), id, f->state, ppperr_strerr[f->state]));
if (id != f->reqid || f->seen_ack) { /* Expected id? */
return; /* Nope, toss... */
}
proc = (code == CONFNAK)? f->callbacks->nakci: f->callbacks->rejci;
if (!proc || !((ret = proc(f, inp, len)))) {
/* Nak/reject is bad - ignore it */
FSMDEBUG((LOG_INFO, "%s: received bad %s (length %d)\n",
PROTO_NAME(f), (code==CONFNAK? "Nak": "reject"), len));
return;
}
f->seen_ack = 1;
switch (f->state) {
case LS_CLOSED:
case LS_STOPPED:
fsm_sdata(f, TERMACK, (u_char)id, NULL, 0);
break;
case LS_REQSENT:
case LS_ACKSENT:
/* They didn't agree to what we wanted - try another request */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
if (ret < 0) {
f->state = LS_STOPPED; /* kludge for stopping CCP */
} else {
fsm_sconfreq(f, 0); /* Send Configure-Request */
}
break;
case LS_ACKRCVD:
/* Got a Nak/reject when we had already had an Ack?? oh well... */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
fsm_sconfreq(f, 0);
f->state = LS_REQSENT;
break;
case LS_OPENED:
/* Go down and restart negotiation */
if (f->callbacks->down) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = LS_REQSENT;
break;
}
}
/*
* fsm_rtermreq - Receive Terminate-Req.
*/
static void
fsm_rtermreq(fsm *f, int id, u_char *p, int len)
{
LWIP_UNUSED_ARG(p);
FSMDEBUG((LOG_INFO, "fsm_rtermreq(%s): Rcvd id %d state=%d (%s)\n",
PROTO_NAME(f), id, f->state, ppperr_strerr[f->state]));
switch (f->state) {
case LS_ACKRCVD:
case LS_ACKSENT:
f->state = LS_REQSENT; /* Start over but keep trying */
break;
case LS_OPENED:
if (len > 0) {
FSMDEBUG((LOG_INFO, "%s terminated by peer (%x)\n", PROTO_NAME(f), p));
} else {
FSMDEBUG((LOG_INFO, "%s terminated by peer\n", PROTO_NAME(f)));
}
if (f->callbacks->down) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
f->retransmits = 0;
f->state = LS_STOPPING;
TIMEOUT(fsm_timeout, f, f->timeouttime);
break;
}
fsm_sdata(f, TERMACK, (u_char)id, NULL, 0);
}
/*
* fsm_rtermack - Receive Terminate-Ack.
*/
static void
fsm_rtermack(fsm *f)
{
FSMDEBUG((LOG_INFO, "fsm_rtermack(%s): state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
switch (f->state) {
case LS_CLOSING:
UNTIMEOUT(fsm_timeout, f);
f->state = LS_CLOSED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
break;
case LS_STOPPING:
UNTIMEOUT(fsm_timeout, f);
f->state = LS_STOPPED;
if( f->callbacks->finished ) {
(*f->callbacks->finished)(f);
}
break;
case LS_ACKRCVD:
f->state = LS_REQSENT;
break;
case LS_OPENED:
if (f->callbacks->down) {
(*f->callbacks->down)(f); /* Inform upper layers */
}
fsm_sconfreq(f, 0);
break;
}
}
/*
* fsm_rcoderej - Receive an Code-Reject.
*/
static void
fsm_rcoderej(fsm *f, u_char *inp, int len)
{
u_char code, id;
FSMDEBUG((LOG_INFO, "fsm_rcoderej(%s): state=%d (%s)\n",
PROTO_NAME(f), f->state, ppperr_strerr[f->state]));
if (len < HEADERLEN) {
FSMDEBUG((LOG_INFO, "fsm_rcoderej: Rcvd short Code-Reject packet!\n"));
return;
}
GETCHAR(code, inp);
GETCHAR(id, inp);
FSMDEBUG((LOG_WARNING, "%s: Rcvd Code-Reject for code %d, id %d\n",
PROTO_NAME(f), code, id));
if( f->state == LS_ACKRCVD ) {
f->state = LS_REQSENT;
}
}
/*
* fsm_sconfreq - Send a Configure-Request.
*/
static void
fsm_sconfreq(fsm *f, int retransmit)
{
u_char *outp;
int cilen;
if( f->state != LS_REQSENT && f->state != LS_ACKRCVD && f->state != LS_ACKSENT ) {
/* Not currently negotiating - reset options */
if( f->callbacks->resetci ) {
(*f->callbacks->resetci)(f);
}
f->nakloops = 0;
}
if( !retransmit ) {
/* New request - reset retransmission counter, use new ID */
f->retransmits = f->maxconfreqtransmits;
f->reqid = ++f->id;
}
f->seen_ack = 0;
/*
* Make up the request packet
*/
outp = outpacket_buf[f->unit] + PPP_HDRLEN + HEADERLEN;
if( f->callbacks->cilen && f->callbacks->addci ) {
cilen = (*f->callbacks->cilen)(f);
if( cilen > peer_mru[f->unit] - (int)HEADERLEN ) {
cilen = peer_mru[f->unit] - HEADERLEN;
}
if (f->callbacks->addci) {
(*f->callbacks->addci)(f, outp, &cilen);
}
} else {
cilen = 0;
}
/* send the request to our peer */
fsm_sdata(f, CONFREQ, f->reqid, outp, cilen);
/* start the retransmit timer */
--f->retransmits;
TIMEOUT(fsm_timeout, f, f->timeouttime);
FSMDEBUG((LOG_INFO, "%s: sending Configure-Request, id %d\n",
PROTO_NAME(f), f->reqid));
}
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/fsm.c | C | oos | 24,756 |
/*****************************************************************************
* lcp.h - Network Link Control Protocol header file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-11-05 Guy Lancaster <glanca@gesn.com>, Global Election Systems Inc.
* Original derived from BSD codes.
*****************************************************************************/
/*
* lcp.h - Link Control Protocol definitions.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* $Id: lcp.h,v 1.3 2007/12/19 20:47:23 fbernon Exp $
*/
#ifndef LCP_H
#define LCP_H
/*************************
*** PUBLIC DEFINITIONS ***
*************************/
/*
* Options.
*/
#define CI_MRU 1 /* Maximum Receive Unit */
#define CI_ASYNCMAP 2 /* Async Control Character Map */
#define CI_AUTHTYPE 3 /* Authentication Type */
#define CI_QUALITY 4 /* Quality Protocol */
#define CI_MAGICNUMBER 5 /* Magic Number */
#define CI_PCOMPRESSION 7 /* Protocol Field Compression */
#define CI_ACCOMPRESSION 8 /* Address/Control Field Compression */
#define CI_CALLBACK 13 /* callback */
#define CI_MRRU 17 /* max reconstructed receive unit; multilink */
#define CI_SSNHF 18 /* short sequence numbers for multilink */
#define CI_EPDISC 19 /* endpoint discriminator */
/*
* LCP-specific packet types.
*/
#define PROTREJ 8 /* Protocol Reject */
#define ECHOREQ 9 /* Echo Request */
#define ECHOREP 10 /* Echo Reply */
#define DISCREQ 11 /* Discard Request */
#define CBCP_OPT 6 /* Use callback control protocol */
/************************
*** PUBLIC DATA TYPES ***
************************/
/*
* The state of options is described by an lcp_options structure.
*/
typedef struct lcp_options {
u_int passive : 1; /* Don't die if we don't get a response */
u_int silent : 1; /* Wait for the other end to start first */
u_int restart : 1; /* Restart vs. exit after close */
u_int neg_mru : 1; /* Negotiate the MRU? */
u_int neg_asyncmap : 1; /* Negotiate the async map? */
u_int neg_upap : 1; /* Ask for UPAP authentication? */
u_int neg_chap : 1; /* Ask for CHAP authentication? */
u_int neg_magicnumber : 1; /* Ask for magic number? */
u_int neg_pcompression : 1; /* HDLC Protocol Field Compression? */
u_int neg_accompression : 1; /* HDLC Address/Control Field Compression? */
u_int neg_lqr : 1; /* Negotiate use of Link Quality Reports */
u_int neg_cbcp : 1; /* Negotiate use of CBCP */
#ifdef PPP_MULTILINK
u_int neg_mrru : 1; /* Negotiate multilink MRRU */
u_int neg_ssnhf : 1; /* Negotiate short sequence numbers */
u_int neg_endpoint : 1; /* Negotiate endpoint discriminator */
#endif
u_short mru; /* Value of MRU */
#ifdef PPP_MULTILINK
u_short mrru; /* Value of MRRU, and multilink enable */
#endif
u_char chap_mdtype; /* which MD type (hashing algorithm) */
u32_t asyncmap; /* Value of async map */
u32_t magicnumber;
int numloops; /* Number of loops during magic number neg. */
u32_t lqr_period; /* Reporting period for LQR 1/100ths second */
#ifdef PPP_MULTILINK
struct epdisc endpoint; /* endpoint discriminator */
#endif
} lcp_options;
/*
* Values for phase from BSD pppd.h based on RFC 1661.
*/
typedef enum {
PHASE_DEAD = 0,
PHASE_INITIALIZE,
PHASE_ESTABLISH,
PHASE_AUTHENTICATE,
PHASE_CALLBACK,
PHASE_NETWORK,
PHASE_TERMINATE
} LinkPhase;
/*****************************
*** PUBLIC DATA STRUCTURES ***
*****************************/
extern LinkPhase lcp_phase[NUM_PPP]; /* Phase of link session (RFC 1661) */
extern lcp_options lcp_wantoptions[];
extern lcp_options lcp_gotoptions[];
extern lcp_options lcp_allowoptions[];
extern lcp_options lcp_hisoptions[];
extern ext_accm xmit_accm[];
/***********************
*** PUBLIC FUNCTIONS ***
***********************/
void lcp_init (int);
void lcp_open (int);
void lcp_close (int, char *);
void lcp_lowerup (int);
void lcp_lowerdown(int);
void lcp_sprotrej (int, u_char *, int); /* send protocol reject */
extern struct protent lcp_protent;
/* Default number of times we receive our magic number from the peer
before deciding the link is looped-back. */
#define DEFLOOPBACKFAIL 10
#endif /* LCP_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/lcp.h | C | oos | 6,768 |
/*****************************************************************************
* auth.c - Network Authentication and Phase Control program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* Copyright (c) 1997 by Global Election Systems Inc. All rights reserved.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-08 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Ported from public pppd code.
*****************************************************************************/
/*
* auth.c - PPP authentication and phase control.
*
* Copyright (c) 1993 The Australian National University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the Australian National University. The name of the University
* may not be used to endorse or promote products derived from this
* software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "pppdebug.h"
#include "fsm.h"
#include "lcp.h"
#include "pap.h"
#include "chap.h"
#include "auth.h"
#include "ipcp.h"
#if CBCP_SUPPORT
#include "cbcp.h"
#endif /* CBCP_SUPPORT */
/*************************/
/*** LOCAL DEFINITIONS ***/
/*************************/
/* Bits in auth_pending[] */
#define PAP_WITHPEER 1
#define PAP_PEER 2
#define CHAP_WITHPEER 4
#define CHAP_PEER 8
/************************/
/*** LOCAL DATA TYPES ***/
/************************/
/* Used for storing a sequence of words. Usually malloced. */
struct wordlist {
struct wordlist *next;
char word[1];
};
/***********************************/
/*** LOCAL FUNCTION DECLARATIONS ***/
/***********************************/
extern char *crypt (const char *, const char *);
/* Prototypes for procedures local to this file. */
static void network_phase (int);
static void check_idle (void *);
static void connect_time_expired (void *);
#if 0
static int login (char *, char *, char **, int *);
#endif
static void logout (void);
static int null_login (int);
static int get_pap_passwd (int, char *, char *);
static int have_pap_secret (void);
static int have_chap_secret (char *, char *, u32_t);
static int ip_addr_check (u32_t, struct wordlist *);
#if 0 /* PAP_SUPPORT || CHAP_SUPPORT */
static void set_allowed_addrs(int unit, struct wordlist *addrs);
static void free_wordlist (struct wordlist *);
#endif /* 0 */ /* PAP_SUPPORT || CHAP_SUPPORT */
#if CBCP_SUPPORT
static void callback_phase (int);
#endif /* CBCP_SUPPORT */
/******************************/
/*** PUBLIC DATA STRUCTURES ***/
/******************************/
/*****************************/
/*** LOCAL DATA STRUCTURES ***/
/*****************************/
#if PAP_SUPPORT || CHAP_SUPPORT
/* The name by which the peer authenticated itself to us. */
static char peer_authname[MAXNAMELEN];
#endif /* PAP_SUPPORT || CHAP_SUPPORT */
/* Records which authentication operations haven't completed yet. */
static int auth_pending[NUM_PPP];
/* Set if we have successfully called login() */
static int logged_in;
/* Set if we have run the /etc/ppp/auth-up script. */
static int did_authup;
/* List of addresses which the peer may use. */
static struct wordlist *addresses[NUM_PPP];
/* Number of network protocols which we have opened. */
static int num_np_open;
/* Number of network protocols which have come up. */
static int num_np_up;
#if PAP_SUPPORT || CHAP_SUPPORT
/* Set if we got the contents of passwd[] from the pap-secrets file. */
static int passwd_from_file;
#endif /* PAP_SUPPORT || CHAP_SUPPORT */
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
/*
* An Open on LCP has requested a change from Dead to Establish phase.
* Do what's necessary to bring the physical layer up.
*/
void
link_required(int unit)
{
LWIP_UNUSED_ARG(unit);
AUTHDEBUG((LOG_INFO, "link_required: %d\n", unit));
}
/*
* LCP has terminated the link; go to the Dead phase and take the
* physical layer down.
*/
void
link_terminated(int unit)
{
AUTHDEBUG((LOG_INFO, "link_terminated: %d\n", unit));
if (lcp_phase[unit] == PHASE_DEAD) {
return;
}
if (logged_in) {
logout();
}
lcp_phase[unit] = PHASE_DEAD;
AUTHDEBUG((LOG_NOTICE, "Connection terminated.\n"));
pppLinkTerminated(unit);
}
/*
* LCP has gone down; it will either die or try to re-establish.
*/
void
link_down(int unit)
{
int i;
struct protent *protp;
AUTHDEBUG((LOG_INFO, "link_down: %d\n", unit));
if (did_authup) {
/* XXX Do link down processing. */
did_authup = 0;
}
for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) {
if (!protp->enabled_flag) {
continue;
}
if (protp->protocol != PPP_LCP && protp->lowerdown != NULL) {
(*protp->lowerdown)(unit);
}
if (protp->protocol < 0xC000 && protp->close != NULL) {
(*protp->close)(unit, "LCP down");
}
}
num_np_open = 0;
num_np_up = 0;
if (lcp_phase[unit] != PHASE_DEAD) {
lcp_phase[unit] = PHASE_TERMINATE;
}
pppLinkDown(unit);
}
/*
* The link is established.
* Proceed to the Dead, Authenticate or Network phase as appropriate.
*/
void
link_established(int unit)
{
int auth;
int i;
struct protent *protp;
lcp_options *wo = &lcp_wantoptions[unit];
lcp_options *go = &lcp_gotoptions[unit];
#if PAP_SUPPORT || CHAP_SUPPORT
lcp_options *ho = &lcp_hisoptions[unit];
#endif /* PAP_SUPPORT || CHAP_SUPPORT */
AUTHDEBUG((LOG_INFO, "link_established: %d\n", unit));
/*
* Tell higher-level protocols that LCP is up.
*/
for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) {
if (protp->protocol != PPP_LCP && protp->enabled_flag && protp->lowerup != NULL) {
(*protp->lowerup)(unit);
}
}
if (ppp_settings.auth_required && !(go->neg_chap || go->neg_upap)) {
/*
* We wanted the peer to authenticate itself, and it refused:
* treat it as though it authenticated with PAP using a username
* of "" and a password of "". If that's not OK, boot it out.
*/
if (!wo->neg_upap || !null_login(unit)) {
AUTHDEBUG((LOG_WARNING, "peer refused to authenticate\n"));
lcp_close(unit, "peer refused to authenticate");
return;
}
}
lcp_phase[unit] = PHASE_AUTHENTICATE;
auth = 0;
#if CHAP_SUPPORT
if (go->neg_chap) {
ChapAuthPeer(unit, ppp_settings.our_name, go->chap_mdtype);
auth |= CHAP_PEER;
}
#endif /* CHAP_SUPPORT */
#if PAP_SUPPORT && CHAP_SUPPORT
else
#endif /* PAP_SUPPORT && CHAP_SUPPORT */
#if PAP_SUPPORT
if (go->neg_upap) {
upap_authpeer(unit);
auth |= PAP_PEER;
}
#endif /* PAP_SUPPORT */
#if CHAP_SUPPORT
if (ho->neg_chap) {
ChapAuthWithPeer(unit, ppp_settings.user, ho->chap_mdtype);
auth |= CHAP_WITHPEER;
}
#endif /* CHAP_SUPPORT */
#if PAP_SUPPORT && CHAP_SUPPORT
else
#endif /* PAP_SUPPORT && CHAP_SUPPORT */
#if PAP_SUPPORT
if (ho->neg_upap) {
if (ppp_settings.passwd[0] == 0) {
passwd_from_file = 1;
if (!get_pap_passwd(unit, ppp_settings.user, ppp_settings.passwd)) {
AUTHDEBUG((LOG_ERR, "No secret found for PAP login\n"));
}
}
upap_authwithpeer(unit, ppp_settings.user, ppp_settings.passwd);
auth |= PAP_WITHPEER;
}
#endif /* PAP_SUPPORT */
auth_pending[unit] = auth;
if (!auth) {
network_phase(unit);
}
}
/*
* The peer has failed to authenticate himself using `protocol'.
*/
void
auth_peer_fail(int unit, u16_t protocol)
{
LWIP_UNUSED_ARG(protocol);
AUTHDEBUG((LOG_INFO, "auth_peer_fail: %d proto=%X\n", unit, protocol));
/*
* Authentication failure: take the link down
*/
lcp_close(unit, "Authentication failed");
}
#if PAP_SUPPORT || CHAP_SUPPORT
/*
* The peer has been successfully authenticated using `protocol'.
*/
void
auth_peer_success(int unit, u16_t protocol, char *name, int namelen)
{
int pbit;
AUTHDEBUG((LOG_INFO, "auth_peer_success: %d proto=%X\n", unit, protocol));
switch (protocol) {
case PPP_CHAP:
pbit = CHAP_PEER;
break;
case PPP_PAP:
pbit = PAP_PEER;
break;
default:
AUTHDEBUG((LOG_WARNING, "auth_peer_success: unknown protocol %x\n", protocol));
return;
}
/*
* Save the authenticated name of the peer for later.
*/
if (namelen > sizeof(peer_authname) - 1) {
namelen = sizeof(peer_authname) - 1;
}
BCOPY(name, peer_authname, namelen);
peer_authname[namelen] = 0;
/*
* If there is no more authentication still to be done,
* proceed to the network (or callback) phase.
*/
if ((auth_pending[unit] &= ~pbit) == 0) {
network_phase(unit);
}
}
/*
* We have failed to authenticate ourselves to the peer using `protocol'.
*/
void
auth_withpeer_fail(int unit, u16_t protocol)
{
int errCode = PPPERR_AUTHFAIL;
LWIP_UNUSED_ARG(protocol);
AUTHDEBUG((LOG_INFO, "auth_withpeer_fail: %d proto=%X\n", unit, protocol));
if (passwd_from_file) {
BZERO(ppp_settings.passwd, MAXSECRETLEN);
}
/*
* XXX Warning: the unit number indicates the interface which is
* not necessarily the PPP connection. It works here as long
* as we are only supporting PPP interfaces.
*/
pppIOCtl(unit, PPPCTLS_ERRCODE, &errCode);
/*
* We've failed to authenticate ourselves to our peer.
* He'll probably take the link down, and there's not much
* we can do except wait for that.
*/
}
/*
* We have successfully authenticated ourselves with the peer using `protocol'.
*/
void
auth_withpeer_success(int unit, u16_t protocol)
{
int pbit;
AUTHDEBUG((LOG_INFO, "auth_withpeer_success: %d proto=%X\n", unit, protocol));
switch (protocol) {
case PPP_CHAP:
pbit = CHAP_WITHPEER;
break;
case PPP_PAP:
if (passwd_from_file) {
BZERO(ppp_settings.passwd, MAXSECRETLEN);
}
pbit = PAP_WITHPEER;
break;
default:
AUTHDEBUG((LOG_WARNING, "auth_peer_success: unknown protocol %x\n", protocol));
pbit = 0;
}
/*
* If there is no more authentication still being done,
* proceed to the network (or callback) phase.
*/
if ((auth_pending[unit] &= ~pbit) == 0) {
network_phase(unit);
}
}
#endif /* PAP_SUPPORT || CHAP_SUPPORT */
/*
* np_up - a network protocol has come up.
*/
void
np_up(int unit, u16_t proto)
{
LWIP_UNUSED_ARG(unit);
LWIP_UNUSED_ARG(proto);
AUTHDEBUG((LOG_INFO, "np_up: %d proto=%X\n", unit, proto));
if (num_np_up == 0) {
AUTHDEBUG((LOG_INFO, "np_up: maxconnect=%d idle_time_limit=%d\n",ppp_settings.maxconnect,ppp_settings.idle_time_limit));
/*
* At this point we consider that the link has come up successfully.
*/
if (ppp_settings.idle_time_limit > 0) {
TIMEOUT(check_idle, NULL, ppp_settings.idle_time_limit);
}
/*
* Set a timeout to close the connection once the maximum
* connect time has expired.
*/
if (ppp_settings.maxconnect > 0) {
TIMEOUT(connect_time_expired, 0, ppp_settings.maxconnect);
}
}
++num_np_up;
}
/*
* np_down - a network protocol has gone down.
*/
void
np_down(int unit, u16_t proto)
{
LWIP_UNUSED_ARG(unit);
LWIP_UNUSED_ARG(proto);
AUTHDEBUG((LOG_INFO, "np_down: %d proto=%X\n", unit, proto));
if (--num_np_up == 0 && ppp_settings.idle_time_limit > 0) {
UNTIMEOUT(check_idle, NULL);
}
}
/*
* np_finished - a network protocol has finished using the link.
*/
void
np_finished(int unit, u16_t proto)
{
LWIP_UNUSED_ARG(unit);
LWIP_UNUSED_ARG(proto);
AUTHDEBUG((LOG_INFO, "np_finished: %d proto=%X\n", unit, proto));
if (--num_np_open <= 0) {
/* no further use for the link: shut up shop. */
lcp_close(0, "No network protocols running");
}
}
/*
* auth_reset - called when LCP is starting negotiations to recheck
* authentication options, i.e. whether we have appropriate secrets
* to use for authenticating ourselves and/or the peer.
*/
void
auth_reset(int unit)
{
lcp_options *go = &lcp_gotoptions[unit];
lcp_options *ao = &lcp_allowoptions[0];
ipcp_options *ipwo = &ipcp_wantoptions[0];
u32_t remote;
AUTHDEBUG((LOG_INFO, "auth_reset: %d\n", unit));
ao->neg_upap = !ppp_settings.refuse_pap && (ppp_settings.passwd[0] != 0 || get_pap_passwd(unit, NULL, NULL));
ao->neg_chap = !ppp_settings.refuse_chap && ppp_settings.passwd[0] != 0 /*have_chap_secret(ppp_settings.user, ppp_settings.remote_name, (u32_t)0)*/;
if (go->neg_upap && !have_pap_secret()) {
go->neg_upap = 0;
}
if (go->neg_chap) {
remote = ipwo->accept_remote? 0: ipwo->hisaddr;
if (!have_chap_secret(ppp_settings.remote_name, ppp_settings.our_name, remote)) {
go->neg_chap = 0;
}
}
}
#if PAP_SUPPORT
/*
* check_passwd - Check the user name and passwd against the PAP secrets
* file. If requested, also check against the system password database,
* and login the user if OK.
*
* returns:
* UPAP_AUTHNAK: Authentication failed.
* UPAP_AUTHACK: Authentication succeeded.
* In either case, msg points to an appropriate message.
*/
int
check_passwd( int unit, char *auser, int userlen, char *apasswd, int passwdlen, char **msg, int *msglen)
{
#if 1
LWIP_UNUSED_ARG(unit);
LWIP_UNUSED_ARG(auser);
LWIP_UNUSED_ARG(userlen);
LWIP_UNUSED_ARG(apasswd);
LWIP_UNUSED_ARG(passwdlen);
LWIP_UNUSED_ARG(msglen);
*msg = (char *) 0;
return UPAP_AUTHACK; /* XXX Assume all entries OK. */
#else
int ret = 0;
struct wordlist *addrs = NULL;
char passwd[256], user[256];
char secret[MAXWORDLEN];
static u_short attempts = 0;
/*
* Make copies of apasswd and auser, then null-terminate them.
*/
BCOPY(apasswd, passwd, passwdlen);
passwd[passwdlen] = '\0';
BCOPY(auser, user, userlen);
user[userlen] = '\0';
*msg = (char *) 0;
/* XXX Validate user name and password. */
ret = UPAP_AUTHACK; /* XXX Assume all entries OK. */
if (ret == UPAP_AUTHNAK) {
if (*msg == (char *) 0) {
*msg = "Login incorrect";
}
*msglen = strlen(*msg);
/*
* Frustrate passwd stealer programs.
* Allow 10 tries, but start backing off after 3 (stolen from login).
* On 10'th, drop the connection.
*/
if (attempts++ >= 10) {
AUTHDEBUG((LOG_WARNING, "%d LOGIN FAILURES BY %s\n", attempts, user));
/*ppp_panic("Excess Bad Logins");*/
}
if (attempts > 3) {
sys_msleep((attempts - 3) * 5);
}
if (addrs != NULL) {
free_wordlist(addrs);
}
} else {
attempts = 0; /* Reset count */
if (*msg == (char *) 0) {
*msg = "Login ok";
}
*msglen = strlen(*msg);
set_allowed_addrs(unit, addrs);
}
BZERO(passwd, sizeof(passwd));
BZERO(secret, sizeof(secret));
return ret;
#endif
}
#endif /* PAP_SUPPORT */
/*
* auth_ip_addr - check whether the peer is authorized to use
* a given IP address. Returns 1 if authorized, 0 otherwise.
*/
int
auth_ip_addr(int unit, u32_t addr)
{
return ip_addr_check(addr, addresses[unit]);
}
/*
* bad_ip_adrs - return 1 if the IP address is one we don't want
* to use, such as an address in the loopback net or a multicast address.
* addr is in network byte order.
*/
int
bad_ip_adrs(u32_t addr)
{
addr = ntohl(addr);
return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
|| IN_MULTICAST(addr) || IN_BADCLASS(addr);
}
#if CHAP_SUPPORT
/*
* get_secret - open the CHAP secret file and return the secret
* for authenticating the given client on the given server.
* (We could be either client or server).
*/
int get_secret( int unit, char *client, char *server, char *secret, int *secret_len, int save_addrs)
{
#if 1
int len;
struct wordlist *addrs;
LWIP_UNUSED_ARG(unit);
LWIP_UNUSED_ARG(server);
LWIP_UNUSED_ARG(save_addrs);
addrs = NULL;
if(!client || !client[0] || strcmp(client, ppp_settings.user)) {
return 0;
}
len = strlen(ppp_settings.passwd);
if (len > MAXSECRETLEN) {
AUTHDEBUG((LOG_ERR, "Secret for %s on %s is too long\n", client, server));
len = MAXSECRETLEN;
}
BCOPY(ppp_settings.passwd, secret, len);
*secret_len = len;
return 1;
#else
int ret = 0, len;
struct wordlist *addrs;
char secbuf[MAXWORDLEN];
addrs = NULL;
secbuf[0] = 0;
/* XXX Find secret. */
if (ret < 0) {
return 0;
}
if (save_addrs) {
set_allowed_addrs(unit, addrs);
}
len = strlen(secbuf);
if (len > MAXSECRETLEN) {
AUTHDEBUG((LOG_ERR, "Secret for %s on %s is too long\n", client, server));
len = MAXSECRETLEN;
}
BCOPY(secbuf, secret, len);
BZERO(secbuf, sizeof(secbuf));
*secret_len = len;
return 1;
#endif
}
#endif /* CHAP_SUPPORT */
#if 0 /* UNUSED */
/*
* auth_check_options - called to check authentication options.
*/
void
auth_check_options(void)
{
lcp_options *wo = &lcp_wantoptions[0];
int can_auth;
ipcp_options *ipwo = &ipcp_wantoptions[0];
u32_t remote;
/* Default our_name to hostname, and user to our_name */
if (ppp_settings.our_name[0] == 0 || ppp_settings.usehostname) {
strcpy(ppp_settings.our_name, ppp_settings.hostname);
}
if (ppp_settings.user[0] == 0) {
strcpy(ppp_settings.user, ppp_settings.our_name);
}
/* If authentication is required, ask peer for CHAP or PAP. */
if (ppp_settings.auth_required && !wo->neg_chap && !wo->neg_upap) {
wo->neg_chap = 1;
wo->neg_upap = 1;
}
/*
* Check whether we have appropriate secrets to use
* to authenticate the peer.
*/
can_auth = wo->neg_upap && have_pap_secret();
if (!can_auth && wo->neg_chap) {
remote = ipwo->accept_remote? 0: ipwo->hisaddr;
can_auth = have_chap_secret(ppp_settings.remote_name, ppp_settings.our_name, remote);
}
if (ppp_settings.auth_required && !can_auth) {
ppp_panic("No auth secret");
}
}
#endif
/**********************************/
/*** LOCAL FUNCTION DEFINITIONS ***/
/**********************************/
/*
* Proceed to the network phase.
*/
static void
network_phase(int unit)
{
int i;
struct protent *protp;
lcp_options *go = &lcp_gotoptions[unit];
/*
* If the peer had to authenticate, run the auth-up script now.
*/
if ((go->neg_chap || go->neg_upap) && !did_authup) {
/* XXX Do setup for peer authentication. */
did_authup = 1;
}
#if CBCP_SUPPORT
/*
* If we negotiated callback, do it now.
*/
if (go->neg_cbcp) {
lcp_phase[unit] = PHASE_CALLBACK;
(*cbcp_protent.open)(unit);
return;
}
#endif /* CBCP_SUPPORT */
lcp_phase[unit] = PHASE_NETWORK;
for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) {
if (protp->protocol < 0xC000 && protp->enabled_flag && protp->open != NULL) {
(*protp->open)(unit);
if (protp->protocol != PPP_CCP) {
++num_np_open;
}
}
}
if (num_np_open == 0) {
/* nothing to do */
lcp_close(0, "No network protocols running");
}
}
/*
* check_idle - check whether the link has been idle for long
* enough that we can shut it down.
*/
static void
check_idle(void *arg)
{
struct ppp_idle idle;
u_short itime;
LWIP_UNUSED_ARG(arg);
if (!get_idle_time(0, &idle)) {
return;
}
itime = LWIP_MIN(idle.xmit_idle, idle.recv_idle);
if (itime >= ppp_settings.idle_time_limit) {
/* link is idle: shut it down. */
AUTHDEBUG((LOG_INFO, "Terminating connection due to lack of activity.\n"));
lcp_close(0, "Link inactive");
} else {
TIMEOUT(check_idle, NULL, ppp_settings.idle_time_limit - itime);
}
}
/*
* connect_time_expired - log a message and close the connection.
*/
static void
connect_time_expired(void *arg)
{
LWIP_UNUSED_ARG(arg);
AUTHDEBUG((LOG_INFO, "Connect time expired\n"));
lcp_close(0, "Connect time expired"); /* Close connection */
}
#if 0
/*
* login - Check the user name and password against the system
* password database, and login the user if OK.
*
* returns:
* UPAP_AUTHNAK: Login failed.
* UPAP_AUTHACK: Login succeeded.
* In either case, msg points to an appropriate message.
*/
static int
login(char *user, char *passwd, char **msg, int *msglen)
{
/* XXX Fail until we decide that we want to support logins. */
return (UPAP_AUTHNAK);
}
#endif
/*
* logout - Logout the user.
*/
static void
logout(void)
{
logged_in = 0;
}
/*
* null_login - Check if a username of "" and a password of "" are
* acceptable, and iff so, set the list of acceptable IP addresses
* and return 1.
*/
static int
null_login(int unit)
{
LWIP_UNUSED_ARG(unit);
/* XXX Fail until we decide that we want to support logins. */
return 0;
}
/*
* get_pap_passwd - get a password for authenticating ourselves with
* our peer using PAP. Returns 1 on success, 0 if no suitable password
* could be found.
*/
static int
get_pap_passwd(int unit, char *user, char *passwd)
{
LWIP_UNUSED_ARG(unit);
/* normally we would reject PAP if no password is provided,
but this causes problems with some providers (like CHT in Taiwan)
who incorrectly request PAP and expect a bogus/empty password, so
always provide a default user/passwd of "none"/"none"
*/
if(user) {
strcpy(user, "none");
}
if(passwd) {
strcpy(passwd, "none");
}
return 1;
}
/*
* have_pap_secret - check whether we have a PAP file with any
* secrets that we could possibly use for authenticating the peer.
*/
static int
have_pap_secret(void)
{
/* XXX Fail until we set up our passwords. */
return 0;
}
/*
* have_chap_secret - check whether we have a CHAP file with a
* secret that we could possibly use for authenticating `client'
* on `server'. Either can be the null string, meaning we don't
* know the identity yet.
*/
static int
have_chap_secret(char *client, char *server, u32_t remote)
{
LWIP_UNUSED_ARG(client);
LWIP_UNUSED_ARG(server);
LWIP_UNUSED_ARG(remote);
/* XXX Fail until we set up our passwords. */
return 0;
}
#if 0 /* PAP_SUPPORT || CHAP_SUPPORT */
/*
* set_allowed_addrs() - set the list of allowed addresses.
*/
static void
set_allowed_addrs(int unit, struct wordlist *addrs)
{
if (addresses[unit] != NULL) {
free_wordlist(addresses[unit]);
}
addresses[unit] = addrs;
#if 0
/*
* If there's only one authorized address we might as well
* ask our peer for that one right away
*/
if (addrs != NULL && addrs->next == NULL) {
char *p = addrs->word;
struct ipcp_options *wo = &ipcp_wantoptions[unit];
u32_t a;
struct hostent *hp;
if (wo->hisaddr == 0 && *p != '!' && *p != '-' && strchr(p, '/') == NULL) {
hp = gethostbyname(p);
if (hp != NULL && hp->h_addrtype == AF_INET) {
a = *(u32_t *)hp->h_addr;
} else {
a = inet_addr(p);
}
if (a != (u32_t) -1) {
wo->hisaddr = a;
}
}
}
#endif
}
#endif /* 0 */ /* PAP_SUPPORT || CHAP_SUPPORT */
static int
ip_addr_check(u32_t addr, struct wordlist *addrs)
{
/* don't allow loopback or multicast address */
if (bad_ip_adrs(addr)) {
return 0;
}
if (addrs == NULL) {
return !ppp_settings.auth_required; /* no addresses authorized */
}
/* XXX All other addresses allowed. */
return 1;
}
#if 0 /* PAP_SUPPORT || CHAP_SUPPORT */
/*
* free_wordlist - release memory allocated for a wordlist.
*/
static void
free_wordlist(struct wordlist *wp)
{
struct wordlist *next;
while (wp != NULL) {
next = wp->next;
free(wp);
wp = next;
}
}
#endif /* 0 */ /* PAP_SUPPORT || CHAP_SUPPORT */
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/auth.c | C | oos | 26,909 |
/*** WARNING - THIS HAS NEVER BEEN FINISHED ***/
/*****************************************************************************
* chap.c - Network Challenge Handshake Authentication Protocol program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-04 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original based on BSD chap.c.
*****************************************************************************/
/*
* chap.c - Challenge Handshake Authentication Protocol.
*
* Copyright (c) 1993 The Australian National University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the Australian National University. The name of the University
* may not be used to endorse or promote products derived from this
* software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Copyright (c) 1991 Gregory M. Christy.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Gregory M. Christy. The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#if CHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "pppdebug.h"
#include "magic.h"
#include "randm.h"
#include "auth.h"
#include "md5.h"
#include "chap.h"
#include "chpms.h"
/*************************/
/*** LOCAL DEFINITIONS ***/
/*************************/
/************************/
/*** LOCAL DATA TYPES ***/
/************************/
/***********************************/
/*** LOCAL FUNCTION DECLARATIONS ***/
/***********************************/
/*
* Protocol entry points.
*/
static void ChapInit (int);
static void ChapLowerUp (int);
static void ChapLowerDown (int);
static void ChapInput (int, u_char *, int);
static void ChapProtocolReject (int);
#if 0
static int ChapPrintPkt (u_char *, int, void (*) (void *, char *, ...), void *);
#endif
static void ChapChallengeTimeout (void *);
static void ChapResponseTimeout (void *);
static void ChapReceiveChallenge (chap_state *, u_char *, int, int);
static void ChapRechallenge (void *);
static void ChapReceiveResponse (chap_state *, u_char *, int, int);
static void ChapReceiveSuccess(chap_state *cstate, u_char *inp, u_char id, int len);
static void ChapReceiveFailure(chap_state *cstate, u_char *inp, u_char id, int len);
static void ChapSendStatus (chap_state *, int);
static void ChapSendChallenge (chap_state *);
static void ChapSendResponse (chap_state *);
static void ChapGenChallenge (chap_state *);
/******************************/
/*** PUBLIC DATA STRUCTURES ***/
/******************************/
chap_state chap[NUM_PPP]; /* CHAP state; one for each unit */
struct protent chap_protent = {
PPP_CHAP,
ChapInit,
ChapInput,
ChapProtocolReject,
ChapLowerUp,
ChapLowerDown,
NULL,
NULL,
#if 0
ChapPrintPkt,
NULL,
#endif
1,
"CHAP",
#if 0
NULL,
NULL,
NULL
#endif
};
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
/*
* ChapAuthWithPeer - Authenticate us with our peer (start client).
*
*/
void
ChapAuthWithPeer(int unit, char *our_name, int digest)
{
chap_state *cstate = &chap[unit];
cstate->resp_name = our_name;
cstate->resp_type = digest;
if (cstate->clientstate == CHAPCS_INITIAL ||
cstate->clientstate == CHAPCS_PENDING) {
/* lower layer isn't up - wait until later */
cstate->clientstate = CHAPCS_PENDING;
return;
}
/*
* We get here as a result of LCP coming up.
* So even if CHAP was open before, we will
* have to re-authenticate ourselves.
*/
cstate->clientstate = CHAPCS_LISTEN;
}
/*
* ChapAuthPeer - Authenticate our peer (start server).
*/
void
ChapAuthPeer(int unit, char *our_name, int digest)
{
chap_state *cstate = &chap[unit];
cstate->chal_name = our_name;
cstate->chal_type = digest;
if (cstate->serverstate == CHAPSS_INITIAL ||
cstate->serverstate == CHAPSS_PENDING) {
/* lower layer isn't up - wait until later */
cstate->serverstate = CHAPSS_PENDING;
return;
}
ChapGenChallenge(cstate);
ChapSendChallenge(cstate); /* crank it up dude! */
cstate->serverstate = CHAPSS_INITIAL_CHAL;
}
/**********************************/
/*** LOCAL FUNCTION DEFINITIONS ***/
/**********************************/
/*
* ChapInit - Initialize a CHAP unit.
*/
static void
ChapInit(int unit)
{
chap_state *cstate = &chap[unit];
BZERO(cstate, sizeof(*cstate));
cstate->unit = unit;
cstate->clientstate = CHAPCS_INITIAL;
cstate->serverstate = CHAPSS_INITIAL;
cstate->timeouttime = CHAP_DEFTIMEOUT;
cstate->max_transmits = CHAP_DEFTRANSMITS;
/* random number generator is initialized in magic_init */
}
/*
* ChapChallengeTimeout - Timeout expired on sending challenge.
*/
static void
ChapChallengeTimeout(void *arg)
{
chap_state *cstate = (chap_state *) arg;
/* if we aren't sending challenges, don't worry. then again we */
/* probably shouldn't be here either */
if (cstate->serverstate != CHAPSS_INITIAL_CHAL &&
cstate->serverstate != CHAPSS_RECHALLENGE) {
return;
}
if (cstate->chal_transmits >= cstate->max_transmits) {
/* give up on peer */
CHAPDEBUG((LOG_ERR, "Peer failed to respond to CHAP challenge\n"));
cstate->serverstate = CHAPSS_BADAUTH;
auth_peer_fail(cstate->unit, PPP_CHAP);
return;
}
ChapSendChallenge(cstate); /* Re-send challenge */
}
/*
* ChapResponseTimeout - Timeout expired on sending response.
*/
static void
ChapResponseTimeout(void *arg)
{
chap_state *cstate = (chap_state *) arg;
/* if we aren't sending a response, don't worry. */
if (cstate->clientstate != CHAPCS_RESPONSE) {
return;
}
ChapSendResponse(cstate); /* re-send response */
}
/*
* ChapRechallenge - Time to challenge the peer again.
*/
static void
ChapRechallenge(void *arg)
{
chap_state *cstate = (chap_state *) arg;
/* if we aren't sending a response, don't worry. */
if (cstate->serverstate != CHAPSS_OPEN) {
return;
}
ChapGenChallenge(cstate);
ChapSendChallenge(cstate);
cstate->serverstate = CHAPSS_RECHALLENGE;
}
/*
* ChapLowerUp - The lower layer is up.
*
* Start up if we have pending requests.
*/
static void
ChapLowerUp(int unit)
{
chap_state *cstate = &chap[unit];
if (cstate->clientstate == CHAPCS_INITIAL) {
cstate->clientstate = CHAPCS_CLOSED;
} else if (cstate->clientstate == CHAPCS_PENDING) {
cstate->clientstate = CHAPCS_LISTEN;
}
if (cstate->serverstate == CHAPSS_INITIAL) {
cstate->serverstate = CHAPSS_CLOSED;
} else if (cstate->serverstate == CHAPSS_PENDING) {
ChapGenChallenge(cstate);
ChapSendChallenge(cstate);
cstate->serverstate = CHAPSS_INITIAL_CHAL;
}
}
/*
* ChapLowerDown - The lower layer is down.
*
* Cancel all timeouts.
*/
static void
ChapLowerDown(int unit)
{
chap_state *cstate = &chap[unit];
/* Timeout(s) pending? Cancel if so. */
if (cstate->serverstate == CHAPSS_INITIAL_CHAL ||
cstate->serverstate == CHAPSS_RECHALLENGE) {
UNTIMEOUT(ChapChallengeTimeout, cstate);
} else if (cstate->serverstate == CHAPSS_OPEN
&& cstate->chal_interval != 0) {
UNTIMEOUT(ChapRechallenge, cstate);
}
if (cstate->clientstate == CHAPCS_RESPONSE) {
UNTIMEOUT(ChapResponseTimeout, cstate);
}
cstate->clientstate = CHAPCS_INITIAL;
cstate->serverstate = CHAPSS_INITIAL;
}
/*
* ChapProtocolReject - Peer doesn't grok CHAP.
*/
static void
ChapProtocolReject(int unit)
{
chap_state *cstate = &chap[unit];
if (cstate->serverstate != CHAPSS_INITIAL &&
cstate->serverstate != CHAPSS_CLOSED) {
auth_peer_fail(unit, PPP_CHAP);
}
if (cstate->clientstate != CHAPCS_INITIAL &&
cstate->clientstate != CHAPCS_CLOSED) {
auth_withpeer_fail(unit, PPP_CHAP);
}
ChapLowerDown(unit); /* shutdown chap */
}
/*
* ChapInput - Input CHAP packet.
*/
static void
ChapInput(int unit, u_char *inpacket, int packet_len)
{
chap_state *cstate = &chap[unit];
u_char *inp;
u_char code, id;
int len;
/*
* Parse header (code, id and length).
* If packet too short, drop it.
*/
inp = inpacket;
if (packet_len < CHAP_HEADERLEN) {
CHAPDEBUG((LOG_INFO, "ChapInput: rcvd short header.\n"));
return;
}
GETCHAR(code, inp);
GETCHAR(id, inp);
GETSHORT(len, inp);
if (len < CHAP_HEADERLEN) {
CHAPDEBUG((LOG_INFO, "ChapInput: rcvd illegal length.\n"));
return;
}
if (len > packet_len) {
CHAPDEBUG((LOG_INFO, "ChapInput: rcvd short packet.\n"));
return;
}
len -= CHAP_HEADERLEN;
/*
* Action depends on code (as in fact it usually does :-).
*/
switch (code) {
case CHAP_CHALLENGE:
ChapReceiveChallenge(cstate, inp, id, len);
break;
case CHAP_RESPONSE:
ChapReceiveResponse(cstate, inp, id, len);
break;
case CHAP_FAILURE:
ChapReceiveFailure(cstate, inp, id, len);
break;
case CHAP_SUCCESS:
ChapReceiveSuccess(cstate, inp, id, len);
break;
default: /* Need code reject? */
CHAPDEBUG((LOG_WARNING, "Unknown CHAP code (%d) received.\n", code));
break;
}
}
/*
* ChapReceiveChallenge - Receive Challenge and send Response.
*/
static void
ChapReceiveChallenge(chap_state *cstate, u_char *inp, int id, int len)
{
int rchallenge_len;
u_char *rchallenge;
int secret_len;
char secret[MAXSECRETLEN];
char rhostname[256];
MD5_CTX mdContext;
u_char hash[MD5_SIGNATURE_SIZE];
CHAPDEBUG((LOG_INFO, "ChapReceiveChallenge: Rcvd id %d.\n", id));
if (cstate->clientstate == CHAPCS_CLOSED ||
cstate->clientstate == CHAPCS_PENDING) {
CHAPDEBUG((LOG_INFO, "ChapReceiveChallenge: in state %d\n",
cstate->clientstate));
return;
}
if (len < 2) {
CHAPDEBUG((LOG_INFO, "ChapReceiveChallenge: rcvd short packet.\n"));
return;
}
GETCHAR(rchallenge_len, inp);
len -= sizeof (u_char) + rchallenge_len; /* now name field length */
if (len < 0) {
CHAPDEBUG((LOG_INFO, "ChapReceiveChallenge: rcvd short packet.\n"));
return;
}
rchallenge = inp;
INCPTR(rchallenge_len, inp);
if (len >= sizeof(rhostname)) {
len = sizeof(rhostname) - 1;
}
BCOPY(inp, rhostname, len);
rhostname[len] = '\000';
CHAPDEBUG((LOG_INFO, "ChapReceiveChallenge: received name field '%s'\n", rhostname));
/* Microsoft doesn't send their name back in the PPP packet */
if (ppp_settings.remote_name[0] != 0 && (ppp_settings.explicit_remote || rhostname[0] == 0)) {
strncpy(rhostname, ppp_settings.remote_name, sizeof(rhostname));
rhostname[sizeof(rhostname) - 1] = 0;
CHAPDEBUG((LOG_INFO, "ChapReceiveChallenge: using '%s' as remote name\n", rhostname));
}
/* get secret for authenticating ourselves with the specified host */
if (!get_secret(cstate->unit, cstate->resp_name, rhostname, secret, &secret_len, 0)) {
secret_len = 0; /* assume null secret if can't find one */
CHAPDEBUG((LOG_WARNING, "No CHAP secret found for authenticating us to %s\n", rhostname));
}
/* cancel response send timeout if necessary */
if (cstate->clientstate == CHAPCS_RESPONSE) {
UNTIMEOUT(ChapResponseTimeout, cstate);
}
cstate->resp_id = id;
cstate->resp_transmits = 0;
/* generate MD based on negotiated type */
switch (cstate->resp_type) {
case CHAP_DIGEST_MD5:
MD5Init(&mdContext);
MD5Update(&mdContext, &cstate->resp_id, 1);
MD5Update(&mdContext, (u_char*)secret, secret_len);
MD5Update(&mdContext, rchallenge, rchallenge_len);
MD5Final(hash, &mdContext);
BCOPY(hash, cstate->response, MD5_SIGNATURE_SIZE);
cstate->resp_length = MD5_SIGNATURE_SIZE;
break;
#ifdef CHAPMS
case CHAP_MICROSOFT:
ChapMS(cstate, rchallenge, rchallenge_len, secret, secret_len);
break;
#endif
default:
CHAPDEBUG((LOG_INFO, "unknown digest type %d\n", cstate->resp_type));
return;
}
BZERO(secret, sizeof(secret));
ChapSendResponse(cstate);
}
/*
* ChapReceiveResponse - Receive and process response.
*/
static void
ChapReceiveResponse(chap_state *cstate, u_char *inp, int id, int len)
{
u_char *remmd, remmd_len;
int secret_len, old_state;
int code;
char rhostname[256];
MD5_CTX mdContext;
char secret[MAXSECRETLEN];
u_char hash[MD5_SIGNATURE_SIZE];
CHAPDEBUG((LOG_INFO, "ChapReceiveResponse: Rcvd id %d.\n", id));
if (cstate->serverstate == CHAPSS_CLOSED ||
cstate->serverstate == CHAPSS_PENDING) {
CHAPDEBUG((LOG_INFO, "ChapReceiveResponse: in state %d\n",
cstate->serverstate));
return;
}
if (id != cstate->chal_id) {
return; /* doesn't match ID of last challenge */
}
/*
* If we have received a duplicate or bogus Response,
* we have to send the same answer (Success/Failure)
* as we did for the first Response we saw.
*/
if (cstate->serverstate == CHAPSS_OPEN) {
ChapSendStatus(cstate, CHAP_SUCCESS);
return;
}
if (cstate->serverstate == CHAPSS_BADAUTH) {
ChapSendStatus(cstate, CHAP_FAILURE);
return;
}
if (len < 2) {
CHAPDEBUG((LOG_INFO, "ChapReceiveResponse: rcvd short packet.\n"));
return;
}
GETCHAR(remmd_len, inp); /* get length of MD */
remmd = inp; /* get pointer to MD */
INCPTR(remmd_len, inp);
len -= sizeof (u_char) + remmd_len;
if (len < 0) {
CHAPDEBUG((LOG_INFO, "ChapReceiveResponse: rcvd short packet.\n"));
return;
}
UNTIMEOUT(ChapChallengeTimeout, cstate);
if (len >= sizeof(rhostname)) {
len = sizeof(rhostname) - 1;
}
BCOPY(inp, rhostname, len);
rhostname[len] = '\000';
CHAPDEBUG((LOG_INFO, "ChapReceiveResponse: received name field: %s\n", rhostname));
/*
* Get secret for authenticating them with us,
* do the hash ourselves, and compare the result.
*/
code = CHAP_FAILURE;
if (!get_secret(cstate->unit, rhostname, cstate->chal_name, secret, &secret_len, 1)) {
/* CHAPDEBUG((LOG_WARNING, TL_CHAP, "No CHAP secret found for authenticating %s\n", rhostname)); */
CHAPDEBUG((LOG_WARNING, "No CHAP secret found for authenticating %s\n",
rhostname));
} else {
/* generate MD based on negotiated type */
switch (cstate->chal_type) {
case CHAP_DIGEST_MD5: /* only MD5 is defined for now */
if (remmd_len != MD5_SIGNATURE_SIZE) {
break; /* it's not even the right length */
}
MD5Init(&mdContext);
MD5Update(&mdContext, &cstate->chal_id, 1);
MD5Update(&mdContext, (u_char*)secret, secret_len);
MD5Update(&mdContext, cstate->challenge, cstate->chal_len);
MD5Final(hash, &mdContext);
/* compare local and remote MDs and send the appropriate status */
if (memcmp (hash, remmd, MD5_SIGNATURE_SIZE) == 0) {
code = CHAP_SUCCESS; /* they are the same! */
}
break;
default:
CHAPDEBUG((LOG_INFO, "unknown digest type %d\n", cstate->chal_type));
}
}
BZERO(secret, sizeof(secret));
ChapSendStatus(cstate, code);
if (code == CHAP_SUCCESS) {
old_state = cstate->serverstate;
cstate->serverstate = CHAPSS_OPEN;
if (old_state == CHAPSS_INITIAL_CHAL) {
auth_peer_success(cstate->unit, PPP_CHAP, rhostname, len);
}
if (cstate->chal_interval != 0) {
TIMEOUT(ChapRechallenge, cstate, cstate->chal_interval);
}
} else {
CHAPDEBUG((LOG_ERR, "CHAP peer authentication failed\n"));
cstate->serverstate = CHAPSS_BADAUTH;
auth_peer_fail(cstate->unit, PPP_CHAP);
}
}
/*
* ChapReceiveSuccess - Receive Success
*/
static void
ChapReceiveSuccess(chap_state *cstate, u_char *inp, u_char id, int len)
{
LWIP_UNUSED_ARG(id);
LWIP_UNUSED_ARG(inp);
CHAPDEBUG((LOG_INFO, "ChapReceiveSuccess: Rcvd id %d.\n", id));
if (cstate->clientstate == CHAPCS_OPEN) {
/* presumably an answer to a duplicate response */
return;
}
if (cstate->clientstate != CHAPCS_RESPONSE) {
/* don't know what this is */
CHAPDEBUG((LOG_INFO, "ChapReceiveSuccess: in state %d\n", cstate->clientstate));
return;
}
UNTIMEOUT(ChapResponseTimeout, cstate);
/*
* Print message.
*/
if (len > 0) {
PRINTMSG(inp, len);
}
cstate->clientstate = CHAPCS_OPEN;
auth_withpeer_success(cstate->unit, PPP_CHAP);
}
/*
* ChapReceiveFailure - Receive failure.
*/
static void
ChapReceiveFailure(chap_state *cstate, u_char *inp, u_char id, int len)
{
LWIP_UNUSED_ARG(id);
LWIP_UNUSED_ARG(inp);
CHAPDEBUG((LOG_INFO, "ChapReceiveFailure: Rcvd id %d.\n", id));
if (cstate->clientstate != CHAPCS_RESPONSE) {
/* don't know what this is */
CHAPDEBUG((LOG_INFO, "ChapReceiveFailure: in state %d\n", cstate->clientstate));
return;
}
UNTIMEOUT(ChapResponseTimeout, cstate);
/*
* Print message.
*/
if (len > 0) {
PRINTMSG(inp, len);
}
CHAPDEBUG((LOG_ERR, "CHAP authentication failed\n"));
auth_withpeer_fail(cstate->unit, PPP_CHAP);
}
/*
* ChapSendChallenge - Send an Authenticate challenge.
*/
static void
ChapSendChallenge(chap_state *cstate)
{
u_char *outp;
int chal_len, name_len;
int outlen;
chal_len = cstate->chal_len;
name_len = strlen(cstate->chal_name);
outlen = CHAP_HEADERLEN + sizeof (u_char) + chal_len + name_len;
outp = outpacket_buf[cstate->unit];
MAKEHEADER(outp, PPP_CHAP); /* paste in a CHAP header */
PUTCHAR(CHAP_CHALLENGE, outp);
PUTCHAR(cstate->chal_id, outp);
PUTSHORT(outlen, outp);
PUTCHAR(chal_len, outp); /* put length of challenge */
BCOPY(cstate->challenge, outp, chal_len);
INCPTR(chal_len, outp);
BCOPY(cstate->chal_name, outp, name_len); /* append hostname */
pppWrite(cstate->unit, outpacket_buf[cstate->unit], outlen + PPP_HDRLEN);
CHAPDEBUG((LOG_INFO, "ChapSendChallenge: Sent id %d.\n", cstate->chal_id));
TIMEOUT(ChapChallengeTimeout, cstate, cstate->timeouttime);
++cstate->chal_transmits;
}
/*
* ChapSendStatus - Send a status response (ack or nak).
*/
static void
ChapSendStatus(chap_state *cstate, int code)
{
u_char *outp;
int outlen, msglen;
char msg[256];
if (code == CHAP_SUCCESS) {
strcpy(msg, "Welcome!");
} else {
strcpy(msg, "I don't like you. Go 'way.");
}
msglen = strlen(msg);
outlen = CHAP_HEADERLEN + msglen;
outp = outpacket_buf[cstate->unit];
MAKEHEADER(outp, PPP_CHAP); /* paste in a header */
PUTCHAR(code, outp);
PUTCHAR(cstate->chal_id, outp);
PUTSHORT(outlen, outp);
BCOPY(msg, outp, msglen);
pppWrite(cstate->unit, outpacket_buf[cstate->unit], outlen + PPP_HDRLEN);
CHAPDEBUG((LOG_INFO, "ChapSendStatus: Sent code %d, id %d.\n", code, cstate->chal_id));
}
/*
* ChapGenChallenge is used to generate a pseudo-random challenge string of
* a pseudo-random length between min_len and max_len. The challenge
* string and its length are stored in *cstate, and various other fields of
* *cstate are initialized.
*/
static void
ChapGenChallenge(chap_state *cstate)
{
int chal_len;
u_char *ptr = cstate->challenge;
int i;
/* pick a random challenge length between MIN_CHALLENGE_LENGTH and
MAX_CHALLENGE_LENGTH */
chal_len = (unsigned)
((((magic() >> 16) *
(MAX_CHALLENGE_LENGTH - MIN_CHALLENGE_LENGTH)) >> 16)
+ MIN_CHALLENGE_LENGTH);
cstate->chal_len = chal_len;
cstate->chal_id = ++cstate->id;
cstate->chal_transmits = 0;
/* generate a random string */
for (i = 0; i < chal_len; i++ ) {
*ptr++ = (char) (magic() & 0xff);
}
}
/*
* ChapSendResponse - send a response packet with values as specified
* in *cstate.
*/
/* ARGSUSED */
static void
ChapSendResponse(chap_state *cstate)
{
u_char *outp;
int outlen, md_len, name_len;
md_len = cstate->resp_length;
name_len = strlen(cstate->resp_name);
outlen = CHAP_HEADERLEN + sizeof (u_char) + md_len + name_len;
outp = outpacket_buf[cstate->unit];
MAKEHEADER(outp, PPP_CHAP);
PUTCHAR(CHAP_RESPONSE, outp); /* we are a response */
PUTCHAR(cstate->resp_id, outp); /* copy id from challenge packet */
PUTSHORT(outlen, outp); /* packet length */
PUTCHAR(md_len, outp); /* length of MD */
BCOPY(cstate->response, outp, md_len); /* copy MD to buffer */
INCPTR(md_len, outp);
BCOPY(cstate->resp_name, outp, name_len); /* append our name */
/* send the packet */
pppWrite(cstate->unit, outpacket_buf[cstate->unit], outlen + PPP_HDRLEN);
cstate->clientstate = CHAPCS_RESPONSE;
TIMEOUT(ChapResponseTimeout, cstate, cstate->timeouttime);
++cstate->resp_transmits;
}
#if 0
static char *ChapCodenames[] = {
"Challenge", "Response", "Success", "Failure"
};
/*
* ChapPrintPkt - print the contents of a CHAP packet.
*/
static int
ChapPrintPkt( u_char *p, int plen, void (*printer) (void *, char *, ...), void *arg)
{
int code, id, len;
int clen, nlen;
u_char x;
if (plen < CHAP_HEADERLEN) {
return 0;
}
GETCHAR(code, p);
GETCHAR(id, p);
GETSHORT(len, p);
if (len < CHAP_HEADERLEN || len > plen) {
return 0;
}
if (code >= 1 && code <= sizeof(ChapCodenames) / sizeof(char *)) {
printer(arg, " %s", ChapCodenames[code-1]);
} else {
printer(arg, " code=0x%x", code);
}
printer(arg, " id=0x%x", id);
len -= CHAP_HEADERLEN;
switch (code) {
case CHAP_CHALLENGE:
case CHAP_RESPONSE:
if (len < 1) {
break;
}
clen = p[0];
if (len < clen + 1) {
break;
}
++p;
nlen = len - clen - 1;
printer(arg, " <");
for (; clen > 0; --clen) {
GETCHAR(x, p);
printer(arg, "%.2x", x);
}
printer(arg, ">, name = %.*Z", nlen, p);
break;
case CHAP_FAILURE:
case CHAP_SUCCESS:
printer(arg, " %.*Z", len, p);
break;
default:
for (clen = len; clen > 0; --clen) {
GETCHAR(x, p);
printer(arg, " %.2x", x);
}
}
return len + CHAP_HEADERLEN;
}
#endif
#endif /* CHAP_SUPPORT */
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/chap.c | C | oos | 25,373 |
/*** WARNING - THIS CODE HAS NOT BEEN FINISHED! ***/
/*****************************************************************************
* chpms.c - Network MicroSoft Challenge Handshake Authentication Protocol program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* Copyright (c) 1997 by Global Election Systems Inc. All rights reserved.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-08 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original based on BSD chap_ms.c.
*****************************************************************************/
/*
* chap_ms.c - Microsoft MS-CHAP compatible implementation.
*
* Copyright (c) 1995 Eric Rosenquist, Strata Software Limited.
* http://www.strataware.com/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Eric Rosenquist. The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/*
* Modifications by Lauri Pesonen / lpesonen@clinet.fi, april 1997
*
* Implemented LANManager type password response to MS-CHAP challenges.
* Now pppd provides both NT style and LANMan style blocks, and the
* prefered is set by option "ms-lanman". Default is to use NT.
* The hash text (StdText) was taken from Win95 RASAPI32.DLL.
*
* You should also use DOMAIN\\USERNAME as described in README.MSCHAP80
*/
#define USE_CRYPT
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#if MSCHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "pppdebug.h"
#include "md4.h"
#ifndef USE_CRYPT
#include "des.h"
#endif
#include "chap.h"
#include "chpms.h"
/*************************/
/*** LOCAL DEFINITIONS ***/
/*************************/
/************************/
/*** LOCAL DATA TYPES ***/
/************************/
typedef struct {
u_char LANManResp[24];
u_char NTResp[24];
u_char UseNT; /* If 1, ignore the LANMan response field */
} MS_ChapResponse;
/* We use MS_CHAP_RESPONSE_LEN, rather than sizeof(MS_ChapResponse),
in case this struct gets padded. */
/***********************************/
/*** LOCAL FUNCTION DECLARATIONS ***/
/***********************************/
/* XXX Don't know what to do with these. */
extern void setkey(const char *);
extern void encrypt(char *, int);
static void DesEncrypt (u_char *, u_char *, u_char *);
static void MakeKey (u_char *, u_char *);
#ifdef USE_CRYPT
static void Expand (u_char *, u_char *);
static void Collapse (u_char *, u_char *);
#endif
static void ChallengeResponse(
u_char *challenge, /* IN 8 octets */
u_char *pwHash, /* IN 16 octets */
u_char *response /* OUT 24 octets */
);
static void ChapMS_NT(
char *rchallenge,
int rchallenge_len,
char *secret,
int secret_len,
MS_ChapResponse *response
);
static u_char Get7Bits(
u_char *input,
int startBit
);
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
void
ChapMS( chap_state *cstate, char *rchallenge, int rchallenge_len, char *secret, int secret_len)
{
MS_ChapResponse response;
#ifdef MSLANMAN
extern int ms_lanman;
#endif
#if 0
CHAPDEBUG((LOG_INFO, "ChapMS: secret is '%.*s'\n", secret_len, secret));
#endif
BZERO(&response, sizeof(response));
/* Calculate both always */
ChapMS_NT(rchallenge, rchallenge_len, secret, secret_len, &response);
#ifdef MSLANMAN
ChapMS_LANMan(rchallenge, rchallenge_len, secret, secret_len, &response);
/* prefered method is set by option */
response.UseNT = !ms_lanman;
#else
response.UseNT = 1;
#endif
BCOPY(&response, cstate->response, MS_CHAP_RESPONSE_LEN);
cstate->resp_length = MS_CHAP_RESPONSE_LEN;
}
/**********************************/
/*** LOCAL FUNCTION DEFINITIONS ***/
/**********************************/
static void
ChallengeResponse( u_char *challenge, /* IN 8 octets */
u_char *pwHash, /* IN 16 octets */
u_char *response /* OUT 24 octets */)
{
char ZPasswordHash[21];
BZERO(ZPasswordHash, sizeof(ZPasswordHash));
BCOPY(pwHash, ZPasswordHash, 16);
#if 0
log_packet(ZPasswordHash, sizeof(ZPasswordHash), "ChallengeResponse - ZPasswordHash", LOG_DEBUG);
#endif
DesEncrypt(challenge, ZPasswordHash + 0, response + 0);
DesEncrypt(challenge, ZPasswordHash + 7, response + 8);
DesEncrypt(challenge, ZPasswordHash + 14, response + 16);
#if 0
log_packet(response, 24, "ChallengeResponse - response", LOG_DEBUG);
#endif
}
#ifdef USE_CRYPT
static void
DesEncrypt( u_char *clear, /* IN 8 octets */
u_char *key, /* IN 7 octets */
u_char *cipher /* OUT 8 octets */)
{
u_char des_key[8];
u_char crypt_key[66];
u_char des_input[66];
MakeKey(key, des_key);
Expand(des_key, crypt_key);
setkey(crypt_key);
#if 0
CHAPDEBUG((LOG_INFO, "DesEncrypt: 8 octet input : %02X%02X%02X%02X%02X%02X%02X%02X\n",
clear[0], clear[1], clear[2], clear[3], clear[4], clear[5], clear[6], clear[7]));
#endif
Expand(clear, des_input);
encrypt(des_input, 0);
Collapse(des_input, cipher);
#if 0
CHAPDEBUG((LOG_INFO, "DesEncrypt: 8 octet output: %02X%02X%02X%02X%02X%02X%02X%02X\n",
cipher[0], cipher[1], cipher[2], cipher[3], cipher[4], cipher[5], cipher[6], cipher[7]));
#endif
}
#else /* USE_CRYPT */
static void
DesEncrypt( u_char *clear, /* IN 8 octets */
u_char *key, /* IN 7 octets */
u_char *cipher /* OUT 8 octets */)
{
des_cblock des_key;
des_key_schedule key_schedule;
MakeKey(key, des_key);
des_set_key(&des_key, key_schedule);
#if 0
CHAPDEBUG((LOG_INFO, "DesEncrypt: 8 octet input : %02X%02X%02X%02X%02X%02X%02X%02X\n",
clear[0], clear[1], clear[2], clear[3], clear[4], clear[5], clear[6], clear[7]));
#endif
des_ecb_encrypt((des_cblock *)clear, (des_cblock *)cipher, key_schedule, 1);
#if 0
CHAPDEBUG((LOG_INFO, "DesEncrypt: 8 octet output: %02X%02X%02X%02X%02X%02X%02X%02X\n",
cipher[0], cipher[1], cipher[2], cipher[3], cipher[4], cipher[5], cipher[6], cipher[7]));
#endif
}
#endif /* USE_CRYPT */
static u_char
Get7Bits( u_char *input, int startBit)
{
register unsigned int word;
word = (unsigned)input[startBit / 8] << 8;
word |= (unsigned)input[startBit / 8 + 1];
word >>= 15 - (startBit % 8 + 7);
return word & 0xFE;
}
#ifdef USE_CRYPT
/* in == 8-byte string (expanded version of the 56-bit key)
* out == 64-byte string where each byte is either 1 or 0
* Note that the low-order "bit" is always ignored by by setkey()
*/
static void
Expand(u_char *in, u_char *out)
{
int j, c;
int i;
for(i = 0; i < 64; in++){
c = *in;
for(j = 7; j >= 0; j--) {
*out++ = (c >> j) & 01;
}
i += 8;
}
}
/* The inverse of Expand
*/
static void
Collapse(u_char *in, u_char *out)
{
int j;
int i;
unsigned int c;
for (i = 0; i < 64; i += 8, out++) {
c = 0;
for (j = 7; j >= 0; j--, in++) {
c |= *in << j;
}
*out = c & 0xff;
}
}
#endif
static void
MakeKey( u_char *key, /* IN 56 bit DES key missing parity bits */
u_char *des_key /* OUT 64 bit DES key with parity bits added */)
{
des_key[0] = Get7Bits(key, 0);
des_key[1] = Get7Bits(key, 7);
des_key[2] = Get7Bits(key, 14);
des_key[3] = Get7Bits(key, 21);
des_key[4] = Get7Bits(key, 28);
des_key[5] = Get7Bits(key, 35);
des_key[6] = Get7Bits(key, 42);
des_key[7] = Get7Bits(key, 49);
#ifndef USE_CRYPT
des_set_odd_parity((des_cblock *)des_key);
#endif
#if 0
CHAPDEBUG((LOG_INFO, "MakeKey: 56-bit input : %02X%02X%02X%02X%02X%02X%02X\n",
key[0], key[1], key[2], key[3], key[4], key[5], key[6]));
CHAPDEBUG((LOG_INFO, "MakeKey: 64-bit output: %02X%02X%02X%02X%02X%02X%02X%02X\n",
des_key[0], des_key[1], des_key[2], des_key[3], des_key[4], des_key[5], des_key[6], des_key[7]));
#endif
}
static void
ChapMS_NT( char *rchallenge,
int rchallenge_len,
char *secret,
int secret_len,
MS_ChapResponse *response)
{
int i;
MDstruct md4Context;
u_char unicodePassword[MAX_NT_PASSWORD * 2];
static int low_byte_first = -1;
/* Initialize the Unicode version of the secret (== password). */
/* This implicitly supports 8-bit ISO8859/1 characters. */
BZERO(unicodePassword, sizeof(unicodePassword));
for (i = 0; i < secret_len; i++) {
unicodePassword[i * 2] = (u_char)secret[i];
}
MDbegin(&md4Context);
MDupdate(&md4Context, unicodePassword, secret_len * 2 * 8); /* Unicode is 2 bytes/char, *8 for bit count */
if (low_byte_first == -1) {
low_byte_first = (htons((unsigned short int)1) != 1);
}
if (low_byte_first == 0) {
MDreverse((u_long *)&md4Context); /* sfb 961105 */
}
MDupdate(&md4Context, NULL, 0); /* Tell MD4 we're done */
ChallengeResponse(rchallenge, (char *)md4Context.buffer, response->NTResp);
}
#ifdef MSLANMAN
static u_char *StdText = (u_char *)"KGS!@#$%"; /* key from rasapi32.dll */
static void
ChapMS_LANMan( char *rchallenge,
int rchallenge_len,
char *secret,
int secret_len,
MS_ChapResponse *response)
{
int i;
u_char UcasePassword[MAX_NT_PASSWORD]; /* max is actually 14 */
u_char PasswordHash[16];
/* LANMan password is case insensitive */
BZERO(UcasePassword, sizeof(UcasePassword));
for (i = 0; i < secret_len; i++) {
UcasePassword[i] = (u_char)toupper(secret[i]);
}
DesEncrypt( StdText, UcasePassword + 0, PasswordHash + 0 );
DesEncrypt( StdText, UcasePassword + 7, PasswordHash + 8 );
ChallengeResponse(rchallenge, PasswordHash, response->LANManResp);
}
#endif
#endif /* MSCHAP_SUPPORT */
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/chpms.c | C | oos | 12,003 |
/*
***********************************************************************
** md5.h -- header file for implementation of MD5 **
** RSA Data Security, Inc. MD5 Message-Digest Algorithm **
** Created: 2/17/90 RLR **
** Revised: 12/27/90 SRD,AJ,BSK,JT Reference C version **
** Revised (for MD5): RLR 4/27/91 **
** -- G modified to have y&~z instead of y&z **
** -- FF, GG, HH modified to add in last register done **
** -- Access pattern: round 2 works mod 5, round 3 works mod 3 **
** -- distinct additive constant for each step **
** -- round 4 added, working mod 7 **
***********************************************************************
*/
/*
***********************************************************************
** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. **
** **
** License to copy and use this software is granted provided that **
** it is identified as the "RSA Data Security, Inc. MD5 Message- **
** Digest Algorithm" in all material mentioning or referencing this **
** software or this function. **
** **
** License is also granted to make and use derivative works **
** provided that such works are identified as "derived from the RSA **
** Data Security, Inc. MD5 Message-Digest Algorithm" in all **
** material mentioning or referencing the derived work. **
** **
** RSA Data Security, Inc. makes no representations concerning **
** either the merchantability of this software or the suitability **
** of this software for any particular purpose. It is provided "as **
** is" without express or implied warranty of any kind. **
** **
** These notices must be retained in any copies of any part of this **
** documentation and/or software. **
***********************************************************************
*/
#ifndef MD5_H
#define MD5_H
/* Data structure for MD5 (Message-Digest) computation */
typedef struct {
u32_t i[2]; /* number of _bits_ handled mod 2^64 */
u32_t buf[4]; /* scratch buffer */
unsigned char in[64]; /* input buffer */
unsigned char digest[16]; /* actual digest after MD5Final call */
} MD5_CTX;
void MD5Init ( MD5_CTX *mdContext);
void MD5Update( MD5_CTX *mdContext, unsigned char *inBuf, unsigned int inLen);
void MD5Final ( unsigned char hash[], MD5_CTX *mdContext);
#endif /* MD5_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/md5.h | C | oos | 3,023 |
/*****************************************************************************
* magic.c - Network Random Number Generator program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-04 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original based on BSD magic.c.
*****************************************************************************/
/*
* magic.c - PPP Magic Number routines.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT
#include "ppp.h"
#include "randm.h"
#include "magic.h"
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
/*
* magicInit - Initialize the magic number generator.
*
* Since we use another random number generator that has its own
* initialization, we do nothing here.
*/
void magicInit()
{
return;
}
/*
* magic - Returns the next magic number.
*/
u32_t magic()
{
return avRandom();
}
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/magic.c | C | oos | 3,210 |
/*****************************************************************************
* ipcp.h - PPP IP NCP: Internet Protocol Network Control Protocol header file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-04 Guy Lancaster <glanca@gesn.com>, Global Election Systems Inc.
* Original derived from BSD codes.
*****************************************************************************/
/*
* ipcp.h - IP Control Protocol definitions.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* $Id: ipcp.h,v 1.3 2007/12/19 20:47:23 fbernon Exp $
*/
#ifndef IPCP_H
#define IPCP_H
/*************************
*** PUBLIC DEFINITIONS ***
*************************/
/*
* Options.
*/
#define CI_ADDRS 1 /* IP Addresses */
#define CI_COMPRESSTYPE 2 /* Compression Type */
#define CI_ADDR 3
#define CI_MS_WINS1 128 /* Primary WINS value */
#define CI_MS_DNS1 129 /* Primary DNS value */
#define CI_MS_WINS2 130 /* Secondary WINS value */
#define CI_MS_DNS2 131 /* Secondary DNS value */
#define IPCP_VJMODE_OLD 1 /* "old" mode (option # = 0x0037) */
#define IPCP_VJMODE_RFC1172 2 /* "old-rfc"mode (option # = 0x002d) */
#define IPCP_VJMODE_RFC1332 3 /* "new-rfc"mode (option # = 0x002d, */
/* maxslot and slot number compression) */
#define IPCP_VJ_COMP 0x002d /* current value for VJ compression option */
#define IPCP_VJ_COMP_OLD 0x0037 /* "old" (i.e, broken) value for VJ */
/* compression option */
/************************
*** PUBLIC DATA TYPES ***
************************/
typedef struct ipcp_options {
u_int neg_addr : 1; /* Negotiate IP Address? */
u_int old_addrs : 1; /* Use old (IP-Addresses) option? */
u_int req_addr : 1; /* Ask peer to send IP address? */
u_int default_route : 1; /* Assign default route through interface? */
u_int proxy_arp : 1; /* Make proxy ARP entry for peer? */
u_int neg_vj : 1; /* Van Jacobson Compression? */
u_int old_vj : 1; /* use old (short) form of VJ option? */
u_int accept_local : 1; /* accept peer's value for ouraddr */
u_int accept_remote : 1; /* accept peer's value for hisaddr */
u_int req_dns1 : 1; /* Ask peer to send primary DNS address? */
u_int req_dns2 : 1; /* Ask peer to send secondary DNS address? */
u_short vj_protocol; /* protocol value to use in VJ option */
u_char maxslotindex; /* VJ slots - 1. */
u_char cflag; /* VJ slot compression flag. */
u32_t ouraddr, hisaddr; /* Addresses in NETWORK BYTE ORDER */
u32_t dnsaddr[2]; /* Primary and secondary MS DNS entries */
u32_t winsaddr[2]; /* Primary and secondary MS WINS entries */
} ipcp_options;
/*****************************
*** PUBLIC DATA STRUCTURES ***
*****************************/
extern fsm ipcp_fsm[];
extern ipcp_options ipcp_wantoptions[];
extern ipcp_options ipcp_gotoptions[];
extern ipcp_options ipcp_allowoptions[];
extern ipcp_options ipcp_hisoptions[];
extern struct protent ipcp_protent;
/***********************
*** PUBLIC FUNCTIONS ***
***********************/
#endif /* IPCP_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/ipcp.h | C | oos | 5,517 |
/*****************************************************************************
* ipcp.c - Network PPP IP Control Protocol program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-08 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original.
*****************************************************************************/
/*
* ipcp.c - PPP IP Control Protocol.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "pppdebug.h"
#include "auth.h"
#include "fsm.h"
#include "vj.h"
#include "ipcp.h"
#include <string.h>
/*************************/
/*** LOCAL DEFINITIONS ***/
/*************************/
/* #define OLD_CI_ADDRS 1 */ /* Support deprecated address negotiation. */
/*
* Lengths of configuration options.
*/
#define CILEN_VOID 2
#define CILEN_COMPRESS 4 /* min length for compression protocol opt. */
#define CILEN_VJ 6 /* length for RFC1332 Van-Jacobson opt. */
#define CILEN_ADDR 6 /* new-style single address option */
#define CILEN_ADDRS 10 /* old-style dual address option */
/***********************************/
/*** LOCAL FUNCTION DECLARATIONS ***/
/***********************************/
/*
* Callbacks for fsm code. (CI = Configuration Information)
*/
static void ipcp_resetci (fsm *); /* Reset our CI */
static int ipcp_cilen (fsm *); /* Return length of our CI */
static void ipcp_addci (fsm *, u_char *, int *); /* Add our CI */
static int ipcp_ackci (fsm *, u_char *, int); /* Peer ack'd our CI */
static int ipcp_nakci (fsm *, u_char *, int); /* Peer nak'd our CI */
static int ipcp_rejci (fsm *, u_char *, int); /* Peer rej'd our CI */
static int ipcp_reqci (fsm *, u_char *, int *, int); /* Rcv CI */
static void ipcp_up (fsm *); /* We're UP */
static void ipcp_down (fsm *); /* We're DOWN */
#if 0
static void ipcp_script (fsm *, char *); /* Run an up/down script */
#endif
static void ipcp_finished (fsm *); /* Don't need lower layer */
/*
* Protocol entry points from main code.
*/
static void ipcp_init (int);
static void ipcp_open (int);
static void ipcp_close (int, char *);
static void ipcp_lowerup (int);
static void ipcp_lowerdown (int);
static void ipcp_input (int, u_char *, int);
static void ipcp_protrej (int);
static void ipcp_clear_addrs (int);
#define CODENAME(x) ((x) == CONFACK ? "ACK" : \
(x) == CONFNAK ? "NAK" : "REJ")
/******************************/
/*** PUBLIC DATA STRUCTURES ***/
/******************************/
/* global vars */
ipcp_options ipcp_wantoptions[NUM_PPP]; /* Options that we want to request */
ipcp_options ipcp_gotoptions[NUM_PPP]; /* Options that peer ack'd */
ipcp_options ipcp_allowoptions[NUM_PPP]; /* Options we allow peer to request */
ipcp_options ipcp_hisoptions[NUM_PPP]; /* Options that we ack'd */
fsm ipcp_fsm[NUM_PPP]; /* IPCP fsm structure */
struct protent ipcp_protent = {
PPP_IPCP,
ipcp_init,
ipcp_input,
ipcp_protrej,
ipcp_lowerup,
ipcp_lowerdown,
ipcp_open,
ipcp_close,
#if 0
ipcp_printpkt,
NULL,
#endif
1,
"IPCP",
#if 0
ip_check_options,
NULL,
ip_active_pkt
#endif
};
/*****************************/
/*** LOCAL DATA STRUCTURES ***/
/*****************************/
/* local vars */
static int cis_received[NUM_PPP]; /* # Conf-Reqs received */
static int default_route_set[NUM_PPP]; /* Have set up a default route */
static fsm_callbacks ipcp_callbacks = { /* IPCP callback routines */
ipcp_resetci, /* Reset our Configuration Information */
ipcp_cilen, /* Length of our Configuration Information */
ipcp_addci, /* Add our Configuration Information */
ipcp_ackci, /* ACK our Configuration Information */
ipcp_nakci, /* NAK our Configuration Information */
ipcp_rejci, /* Reject our Configuration Information */
ipcp_reqci, /* Request peer's Configuration Information */
ipcp_up, /* Called when fsm reaches LS_OPENED state */
ipcp_down, /* Called when fsm leaves LS_OPENED state */
NULL, /* Called when we want the lower layer up */
ipcp_finished, /* Called when we want the lower layer down */
NULL, /* Called when Protocol-Reject received */
NULL, /* Retransmission is necessary */
NULL, /* Called to handle protocol-specific codes */
"IPCP" /* String name of protocol */
};
/**********************************/
/*** LOCAL FUNCTION DEFINITIONS ***/
/**********************************/
/*
* Non-standard inet_ntoa left here for compat with original ppp
* sources. Assumes u32_t instead of struct in_addr.
*/
char *
_inet_ntoa(u32_t n)
{
struct in_addr ia;
ia.s_addr = n;
return inet_ntoa(ia);
}
#define inet_ntoa _inet_ntoa
/*
* ipcp_init - Initialize IPCP.
*/
static void
ipcp_init(int unit)
{
fsm *f = &ipcp_fsm[unit];
ipcp_options *wo = &ipcp_wantoptions[unit];
ipcp_options *ao = &ipcp_allowoptions[unit];
f->unit = unit;
f->protocol = PPP_IPCP;
f->callbacks = &ipcp_callbacks;
fsm_init(&ipcp_fsm[unit]);
memset(wo, 0, sizeof(*wo));
memset(ao, 0, sizeof(*ao));
wo->neg_addr = 1;
wo->ouraddr = 0;
#if VJ_SUPPORT
wo->neg_vj = 1;
#else /* VJ_SUPPORT */
wo->neg_vj = 0;
#endif /* VJ_SUPPORT */
wo->vj_protocol = IPCP_VJ_COMP;
wo->maxslotindex = MAX_SLOTS - 1;
wo->cflag = 0;
wo->default_route = 1;
ao->neg_addr = 1;
#if VJ_SUPPORT
ao->neg_vj = 1;
#else /* VJ_SUPPORT */
ao->neg_vj = 0;
#endif /* VJ_SUPPORT */
ao->maxslotindex = MAX_SLOTS - 1;
ao->cflag = 1;
ao->default_route = 1;
}
/*
* ipcp_open - IPCP is allowed to come up.
*/
static void
ipcp_open(int unit)
{
fsm_open(&ipcp_fsm[unit]);
}
/*
* ipcp_close - Take IPCP down.
*/
static void
ipcp_close(int unit, char *reason)
{
fsm_close(&ipcp_fsm[unit], reason);
}
/*
* ipcp_lowerup - The lower layer is up.
*/
static void
ipcp_lowerup(int unit)
{
fsm_lowerup(&ipcp_fsm[unit]);
}
/*
* ipcp_lowerdown - The lower layer is down.
*/
static void
ipcp_lowerdown(int unit)
{
fsm_lowerdown(&ipcp_fsm[unit]);
}
/*
* ipcp_input - Input IPCP packet.
*/
static void
ipcp_input(int unit, u_char *p, int len)
{
fsm_input(&ipcp_fsm[unit], p, len);
}
/*
* ipcp_protrej - A Protocol-Reject was received for IPCP.
*
* Pretend the lower layer went down, so we shut up.
*/
static void
ipcp_protrej(int unit)
{
fsm_lowerdown(&ipcp_fsm[unit]);
}
/*
* ipcp_resetci - Reset our CI.
*/
static void
ipcp_resetci(fsm *f)
{
ipcp_options *wo = &ipcp_wantoptions[f->unit];
wo->req_addr = wo->neg_addr && ipcp_allowoptions[f->unit].neg_addr;
if (wo->ouraddr == 0) {
wo->accept_local = 1;
}
if (wo->hisaddr == 0) {
wo->accept_remote = 1;
}
/* Request DNS addresses from the peer */
wo->req_dns1 = ppp_settings.usepeerdns;
wo->req_dns2 = ppp_settings.usepeerdns;
ipcp_gotoptions[f->unit] = *wo;
cis_received[f->unit] = 0;
}
/*
* ipcp_cilen - Return length of our CI.
*/
static int
ipcp_cilen(fsm *f)
{
ipcp_options *go = &ipcp_gotoptions[f->unit];
ipcp_options *wo = &ipcp_wantoptions[f->unit];
ipcp_options *ho = &ipcp_hisoptions[f->unit];
#define LENCIVJ(neg, old) (neg ? (old? CILEN_COMPRESS : CILEN_VJ) : 0)
#define LENCIADDR(neg, old) (neg ? (old? CILEN_ADDRS : CILEN_ADDR) : 0)
#define LENCIDNS(neg) (neg ? (CILEN_ADDR) : 0)
/*
* First see if we want to change our options to the old
* forms because we have received old forms from the peer.
*/
if (wo->neg_addr && !go->neg_addr && !go->old_addrs) {
/* use the old style of address negotiation */
go->neg_addr = 1;
go->old_addrs = 1;
}
if (wo->neg_vj && !go->neg_vj && !go->old_vj) {
/* try an older style of VJ negotiation */
if (cis_received[f->unit] == 0) {
/* keep trying the new style until we see some CI from the peer */
go->neg_vj = 1;
} else {
/* use the old style only if the peer did */
if (ho->neg_vj && ho->old_vj) {
go->neg_vj = 1;
go->old_vj = 1;
go->vj_protocol = ho->vj_protocol;
}
}
}
return (LENCIADDR(go->neg_addr, go->old_addrs) +
LENCIVJ(go->neg_vj, go->old_vj) +
LENCIDNS(go->req_dns1) +
LENCIDNS(go->req_dns2));
}
/*
* ipcp_addci - Add our desired CIs to a packet.
*/
static void
ipcp_addci(fsm *f, u_char *ucp, int *lenp)
{
ipcp_options *go = &ipcp_gotoptions[f->unit];
int len = *lenp;
#define ADDCIVJ(opt, neg, val, old, maxslotindex, cflag) \
if (neg) { \
int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \
if (len >= vjlen) { \
PUTCHAR(opt, ucp); \
PUTCHAR(vjlen, ucp); \
PUTSHORT(val, ucp); \
if (!old) { \
PUTCHAR(maxslotindex, ucp); \
PUTCHAR(cflag, ucp); \
} \
len -= vjlen; \
} else { \
neg = 0; \
} \
}
#define ADDCIADDR(opt, neg, old, val1, val2) \
if (neg) { \
int addrlen = (old? CILEN_ADDRS: CILEN_ADDR); \
if (len >= addrlen) { \
u32_t l; \
PUTCHAR(opt, ucp); \
PUTCHAR(addrlen, ucp); \
l = ntohl(val1); \
PUTLONG(l, ucp); \
if (old) { \
l = ntohl(val2); \
PUTLONG(l, ucp); \
} \
len -= addrlen; \
} else { \
neg = 0; \
} \
}
#define ADDCIDNS(opt, neg, addr) \
if (neg) { \
if (len >= CILEN_ADDR) { \
u32_t l; \
PUTCHAR(opt, ucp); \
PUTCHAR(CILEN_ADDR, ucp); \
l = ntohl(addr); \
PUTLONG(l, ucp); \
len -= CILEN_ADDR; \
} else { \
neg = 0; \
} \
}
ADDCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), go->neg_addr,
go->old_addrs, go->ouraddr, go->hisaddr);
ADDCIVJ(CI_COMPRESSTYPE, go->neg_vj, go->vj_protocol, go->old_vj,
go->maxslotindex, go->cflag);
ADDCIDNS(CI_MS_DNS1, go->req_dns1, go->dnsaddr[0]);
ADDCIDNS(CI_MS_DNS2, go->req_dns2, go->dnsaddr[1]);
*lenp -= len;
}
/*
* ipcp_ackci - Ack our CIs.
*
* Returns:
* 0 - Ack was bad.
* 1 - Ack was good.
*/
static int
ipcp_ackci(fsm *f, u_char *p, int len)
{
ipcp_options *go = &ipcp_gotoptions[f->unit];
u_short cilen, citype, cishort;
u32_t cilong;
u_char cimaxslotindex, cicflag;
/*
* CIs must be in exactly the same order that we sent...
* Check packet length and CI length at each step.
* If we find any deviations, then this packet is bad.
*/
#define ACKCIVJ(opt, neg, val, old, maxslotindex, cflag) \
if (neg) { \
int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \
if ((len -= vjlen) < 0) { \
goto bad; \
} \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != vjlen || \
citype != opt) { \
goto bad; \
} \
GETSHORT(cishort, p); \
if (cishort != val) { \
goto bad; \
} \
if (!old) { \
GETCHAR(cimaxslotindex, p); \
if (cimaxslotindex != maxslotindex) { \
goto bad; \
} \
GETCHAR(cicflag, p); \
if (cicflag != cflag) { \
goto bad; \
} \
} \
}
#define ACKCIADDR(opt, neg, old, val1, val2) \
if (neg) { \
int addrlen = (old? CILEN_ADDRS: CILEN_ADDR); \
u32_t l; \
if ((len -= addrlen) < 0) { \
goto bad; \
} \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != addrlen || \
citype != opt) { \
goto bad; \
} \
GETLONG(l, p); \
cilong = htonl(l); \
if (val1 != cilong) { \
goto bad; \
} \
if (old) { \
GETLONG(l, p); \
cilong = htonl(l); \
if (val2 != cilong) { \
goto bad; \
} \
} \
}
#define ACKCIDNS(opt, neg, addr) \
if (neg) { \
u32_t l; \
if ((len -= CILEN_ADDR) < 0) { \
goto bad; \
} \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_ADDR || \
citype != opt) { \
goto bad; \
} \
GETLONG(l, p); \
cilong = htonl(l); \
if (addr != cilong) { \
goto bad; \
} \
}
ACKCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), go->neg_addr,
go->old_addrs, go->ouraddr, go->hisaddr);
ACKCIVJ(CI_COMPRESSTYPE, go->neg_vj, go->vj_protocol, go->old_vj,
go->maxslotindex, go->cflag);
ACKCIDNS(CI_MS_DNS1, go->req_dns1, go->dnsaddr[0]);
ACKCIDNS(CI_MS_DNS2, go->req_dns2, go->dnsaddr[1]);
/*
* If there are any remaining CIs, then this packet is bad.
*/
if (len != 0) {
goto bad;
}
return (1);
bad:
IPCPDEBUG((LOG_INFO, "ipcp_ackci: received bad Ack!\n"));
return (0);
}
/*
* ipcp_nakci - Peer has sent a NAK for some of our CIs.
* This should not modify any state if the Nak is bad
* or if IPCP is in the LS_OPENED state.
*
* Returns:
* 0 - Nak was bad.
* 1 - Nak was good.
*/
static int
ipcp_nakci(fsm *f, u_char *p, int len)
{
ipcp_options *go = &ipcp_gotoptions[f->unit];
u_char cimaxslotindex, cicflag;
u_char citype, cilen, *next;
u_short cishort;
u32_t ciaddr1, ciaddr2, l, cidnsaddr;
ipcp_options no; /* options we've seen Naks for */
ipcp_options try; /* options to request next time */
BZERO(&no, sizeof(no));
try = *go;
/*
* Any Nak'd CIs must be in exactly the same order that we sent.
* Check packet length and CI length at each step.
* If we find any deviations, then this packet is bad.
*/
#define NAKCIADDR(opt, neg, old, code) \
if (go->neg && \
len >= (cilen = (old? CILEN_ADDRS: CILEN_ADDR)) && \
p[1] == cilen && \
p[0] == opt) { \
len -= cilen; \
INCPTR(2, p); \
GETLONG(l, p); \
ciaddr1 = htonl(l); \
if (old) { \
GETLONG(l, p); \
ciaddr2 = htonl(l); \
no.old_addrs = 1; \
} else { \
ciaddr2 = 0; \
} \
no.neg = 1; \
code \
}
#define NAKCIVJ(opt, neg, code) \
if (go->neg && \
((cilen = p[1]) == CILEN_COMPRESS || cilen == CILEN_VJ) && \
len >= cilen && \
p[0] == opt) { \
len -= cilen; \
INCPTR(2, p); \
GETSHORT(cishort, p); \
no.neg = 1; \
code \
}
#define NAKCIDNS(opt, neg, code) \
if (go->neg && \
((cilen = p[1]) == CILEN_ADDR) && \
len >= cilen && \
p[0] == opt) { \
len -= cilen; \
INCPTR(2, p); \
GETLONG(l, p); \
cidnsaddr = htonl(l); \
no.neg = 1; \
code \
}
/*
* Accept the peer's idea of {our,his} address, if different
* from our idea, only if the accept_{local,remote} flag is set.
*/
NAKCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), neg_addr, go->old_addrs,
if (go->accept_local && ciaddr1) { /* Do we know our address? */
try.ouraddr = ciaddr1;
IPCPDEBUG((LOG_INFO, "local IP address %s\n",
inet_ntoa(ciaddr1)));
}
if (go->accept_remote && ciaddr2) { /* Does he know his? */
try.hisaddr = ciaddr2;
IPCPDEBUG((LOG_INFO, "remote IP address %s\n",
inet_ntoa(ciaddr2)));
}
);
/*
* Accept the peer's value of maxslotindex provided that it
* is less than what we asked for. Turn off slot-ID compression
* if the peer wants. Send old-style compress-type option if
* the peer wants.
*/
NAKCIVJ(CI_COMPRESSTYPE, neg_vj,
if (cilen == CILEN_VJ) {
GETCHAR(cimaxslotindex, p);
GETCHAR(cicflag, p);
if (cishort == IPCP_VJ_COMP) {
try.old_vj = 0;
if (cimaxslotindex < go->maxslotindex) {
try.maxslotindex = cimaxslotindex;
}
if (!cicflag) {
try.cflag = 0;
}
} else {
try.neg_vj = 0;
}
} else {
if (cishort == IPCP_VJ_COMP || cishort == IPCP_VJ_COMP_OLD) {
try.old_vj = 1;
try.vj_protocol = cishort;
} else {
try.neg_vj = 0;
}
}
);
NAKCIDNS(CI_MS_DNS1, req_dns1,
try.dnsaddr[0] = cidnsaddr;
IPCPDEBUG((LOG_INFO, "primary DNS address %s\n", inet_ntoa(cidnsaddr)));
);
NAKCIDNS(CI_MS_DNS2, req_dns2,
try.dnsaddr[1] = cidnsaddr;
IPCPDEBUG((LOG_INFO, "secondary DNS address %s\n", inet_ntoa(cidnsaddr)));
);
/*
* There may be remaining CIs, if the peer is requesting negotiation
* on an option that we didn't include in our request packet.
* If they want to negotiate about IP addresses, we comply.
* If they want us to ask for compression, we refuse.
*/
while (len > CILEN_VOID) {
GETCHAR(citype, p);
GETCHAR(cilen, p);
if( (len -= cilen) < 0 ) {
goto bad;
}
next = p + cilen - 2;
switch (citype) {
case CI_COMPRESSTYPE:
if (go->neg_vj || no.neg_vj ||
(cilen != CILEN_VJ && cilen != CILEN_COMPRESS)) {
goto bad;
}
no.neg_vj = 1;
break;
case CI_ADDRS:
if ((go->neg_addr && go->old_addrs) || no.old_addrs
|| cilen != CILEN_ADDRS) {
goto bad;
}
try.neg_addr = 1;
try.old_addrs = 1;
GETLONG(l, p);
ciaddr1 = htonl(l);
if (ciaddr1 && go->accept_local) {
try.ouraddr = ciaddr1;
}
GETLONG(l, p);
ciaddr2 = htonl(l);
if (ciaddr2 && go->accept_remote) {
try.hisaddr = ciaddr2;
}
no.old_addrs = 1;
break;
case CI_ADDR:
if (go->neg_addr || no.neg_addr || cilen != CILEN_ADDR) {
goto bad;
}
try.old_addrs = 0;
GETLONG(l, p);
ciaddr1 = htonl(l);
if (ciaddr1 && go->accept_local) {
try.ouraddr = ciaddr1;
}
if (try.ouraddr != 0) {
try.neg_addr = 1;
}
no.neg_addr = 1;
break;
}
p = next;
}
/* If there is still anything left, this packet is bad. */
if (len != 0) {
goto bad;
}
/*
* OK, the Nak is good. Now we can update state.
*/
if (f->state != LS_OPENED) {
*go = try;
}
return 1;
bad:
IPCPDEBUG((LOG_INFO, "ipcp_nakci: received bad Nak!\n"));
return 0;
}
/*
* ipcp_rejci - Reject some of our CIs.
*/
static int
ipcp_rejci(fsm *f, u_char *p, int len)
{
ipcp_options *go = &ipcp_gotoptions[f->unit];
u_char cimaxslotindex, ciflag, cilen;
u_short cishort;
u32_t cilong;
ipcp_options try; /* options to request next time */
try = *go;
/*
* Any Rejected CIs must be in exactly the same order that we sent.
* Check packet length and CI length at each step.
* If we find any deviations, then this packet is bad.
*/
#define REJCIADDR(opt, neg, old, val1, val2) \
if (go->neg && \
len >= (cilen = old? CILEN_ADDRS: CILEN_ADDR) && \
p[1] == cilen && \
p[0] == opt) { \
u32_t l; \
len -= cilen; \
INCPTR(2, p); \
GETLONG(l, p); \
cilong = htonl(l); \
/* Check rejected value. */ \
if (cilong != val1) { \
goto bad; \
} \
if (old) { \
GETLONG(l, p); \
cilong = htonl(l); \
/* Check rejected value. */ \
if (cilong != val2) { \
goto bad; \
} \
} \
try.neg = 0; \
}
#define REJCIVJ(opt, neg, val, old, maxslot, cflag) \
if (go->neg && \
p[1] == (old? CILEN_COMPRESS : CILEN_VJ) && \
len >= p[1] && \
p[0] == opt) { \
len -= p[1]; \
INCPTR(2, p); \
GETSHORT(cishort, p); \
/* Check rejected value. */ \
if (cishort != val) { \
goto bad; \
} \
if (!old) { \
GETCHAR(cimaxslotindex, p); \
if (cimaxslotindex != maxslot) { \
goto bad; \
} \
GETCHAR(ciflag, p); \
if (ciflag != cflag) { \
goto bad; \
} \
} \
try.neg = 0; \
}
#define REJCIDNS(opt, neg, dnsaddr) \
if (go->neg && \
((cilen = p[1]) == CILEN_ADDR) && \
len >= cilen && \
p[0] == opt) { \
u32_t l; \
len -= cilen; \
INCPTR(2, p); \
GETLONG(l, p); \
cilong = htonl(l); \
/* Check rejected value. */ \
if (cilong != dnsaddr) { \
goto bad; \
} \
try.neg = 0; \
}
REJCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), neg_addr,
go->old_addrs, go->ouraddr, go->hisaddr);
REJCIVJ(CI_COMPRESSTYPE, neg_vj, go->vj_protocol, go->old_vj,
go->maxslotindex, go->cflag);
REJCIDNS(CI_MS_DNS1, req_dns1, go->dnsaddr[0]);
REJCIDNS(CI_MS_DNS2, req_dns2, go->dnsaddr[1]);
/*
* If there are any remaining CIs, then this packet is bad.
*/
if (len != 0) {
goto bad;
}
/*
* Now we can update state.
*/
if (f->state != LS_OPENED) {
*go = try;
}
return 1;
bad:
IPCPDEBUG((LOG_INFO, "ipcp_rejci: received bad Reject!\n"));
return 0;
}
/*
* ipcp_reqci - Check the peer's requested CIs and send appropriate response.
*
* Returns: CONFACK, CONFNAK or CONFREJ and input packet modified
* appropriately. If reject_if_disagree is non-zero, doesn't return
* CONFNAK; returns CONFREJ if it can't return CONFACK.
*/
static int
ipcp_reqci(fsm *f, u_char *inp/* Requested CIs */,int *len/* Length of requested CIs */,int reject_if_disagree)
{
ipcp_options *wo = &ipcp_wantoptions[f->unit];
ipcp_options *ho = &ipcp_hisoptions[f->unit];
ipcp_options *ao = &ipcp_allowoptions[f->unit];
#ifdef OLD_CI_ADDRS
ipcp_options *go = &ipcp_gotoptions[f->unit];
#endif
u_char *cip, *next; /* Pointer to current and next CIs */
u_short cilen, citype; /* Parsed len, type */
u_short cishort; /* Parsed short value */
u32_t tl, ciaddr1; /* Parsed address values */
#ifdef OLD_CI_ADDRS
u32_t ciaddr2; /* Parsed address values */
#endif
int rc = CONFACK; /* Final packet return code */
int orc; /* Individual option return code */
u_char *p; /* Pointer to next char to parse */
u_char *ucp = inp; /* Pointer to current output char */
int l = *len; /* Length left */
u_char maxslotindex, cflag;
int d;
cis_received[f->unit] = 1;
/*
* Reset all his options.
*/
BZERO(ho, sizeof(*ho));
/*
* Process all his options.
*/
next = inp;
while (l) {
orc = CONFACK; /* Assume success */
cip = p = next; /* Remember begining of CI */
if (l < 2 || /* Not enough data for CI header or */
p[1] < 2 || /* CI length too small or */
p[1] > l) { /* CI length too big? */
IPCPDEBUG((LOG_INFO, "ipcp_reqci: bad CI length!\n"));
orc = CONFREJ; /* Reject bad CI */
cilen = l; /* Reject till end of packet */
l = 0; /* Don't loop again */
goto endswitch;
}
GETCHAR(citype, p); /* Parse CI type */
GETCHAR(cilen, p); /* Parse CI length */
l -= cilen; /* Adjust remaining length */
next += cilen; /* Step to next CI */
switch (citype) { /* Check CI type */
#ifdef OLD_CI_ADDRS /* Need to save space... */
case CI_ADDRS:
IPCPDEBUG((LOG_INFO, "ipcp_reqci: received ADDRS\n"));
if (!ao->neg_addr ||
cilen != CILEN_ADDRS) { /* Check CI length */
orc = CONFREJ; /* Reject CI */
break;
}
/*
* If he has no address, or if we both have his address but
* disagree about it, then NAK it with our idea.
* In particular, if we don't know his address, but he does,
* then accept it.
*/
GETLONG(tl, p); /* Parse source address (his) */
ciaddr1 = htonl(tl);
IPCPDEBUG((LOG_INFO, "his addr %s\n", inet_ntoa(ciaddr1)));
if (ciaddr1 != wo->hisaddr
&& (ciaddr1 == 0 || !wo->accept_remote)) {
orc = CONFNAK;
if (!reject_if_disagree) {
DECPTR(sizeof(u32_t), p);
tl = ntohl(wo->hisaddr);
PUTLONG(tl, p);
}
} else if (ciaddr1 == 0 && wo->hisaddr == 0) {
/*
* If neither we nor he knows his address, reject the option.
*/
orc = CONFREJ;
wo->req_addr = 0; /* don't NAK with 0.0.0.0 later */
break;
}
/*
* If he doesn't know our address, or if we both have our address
* but disagree about it, then NAK it with our idea.
*/
GETLONG(tl, p); /* Parse desination address (ours) */
ciaddr2 = htonl(tl);
IPCPDEBUG((LOG_INFO, "our addr %s\n", inet_ntoa(ciaddr2)));
if (ciaddr2 != wo->ouraddr) {
if (ciaddr2 == 0 || !wo->accept_local) {
orc = CONFNAK;
if (!reject_if_disagree) {
DECPTR(sizeof(u32_t), p);
tl = ntohl(wo->ouraddr);
PUTLONG(tl, p);
}
} else {
go->ouraddr = ciaddr2; /* accept peer's idea */
}
}
ho->neg_addr = 1;
ho->old_addrs = 1;
ho->hisaddr = ciaddr1;
ho->ouraddr = ciaddr2;
break;
#endif
case CI_ADDR:
if (!ao->neg_addr) {
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Reject ADDR not allowed\n"));
orc = CONFREJ; /* Reject CI */
break;
} else if (cilen != CILEN_ADDR) { /* Check CI length */
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Reject ADDR bad len\n"));
orc = CONFREJ; /* Reject CI */
break;
}
/*
* If he has no address, or if we both have his address but
* disagree about it, then NAK it with our idea.
* In particular, if we don't know his address, but he does,
* then accept it.
*/
GETLONG(tl, p); /* Parse source address (his) */
ciaddr1 = htonl(tl);
if (ciaddr1 != wo->hisaddr
&& (ciaddr1 == 0 || !wo->accept_remote)) {
orc = CONFNAK;
if (!reject_if_disagree) {
DECPTR(sizeof(u32_t), p);
tl = ntohl(wo->hisaddr);
PUTLONG(tl, p);
}
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Nak ADDR %s\n", inet_ntoa(ciaddr1)));
} else if (ciaddr1 == 0 && wo->hisaddr == 0) {
/*
* Don't ACK an address of 0.0.0.0 - reject it instead.
*/
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Reject ADDR %s\n", inet_ntoa(ciaddr1)));
orc = CONFREJ;
wo->req_addr = 0; /* don't NAK with 0.0.0.0 later */
break;
}
ho->neg_addr = 1;
ho->hisaddr = ciaddr1;
IPCPDEBUG((LOG_INFO, "ipcp_reqci: ADDR %s\n", inet_ntoa(ciaddr1)));
break;
case CI_MS_DNS1:
case CI_MS_DNS2:
/* Microsoft primary or secondary DNS request */
d = citype == CI_MS_DNS2;
/* If we do not have a DNS address then we cannot send it */
if (ao->dnsaddr[d] == 0 ||
cilen != CILEN_ADDR) { /* Check CI length */
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Rejecting DNS%d Request\n", d+1));
orc = CONFREJ; /* Reject CI */
break;
}
GETLONG(tl, p);
if (htonl(tl) != ao->dnsaddr[d]) {
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Naking DNS%d Request %d\n",
d+1, inet_ntoa(tl)));
DECPTR(sizeof(u32_t), p);
tl = ntohl(ao->dnsaddr[d]);
PUTLONG(tl, p);
orc = CONFNAK;
}
IPCPDEBUG((LOG_INFO, "ipcp_reqci: received DNS%d Request\n", d+1));
break;
case CI_MS_WINS1:
case CI_MS_WINS2:
/* Microsoft primary or secondary WINS request */
d = citype == CI_MS_WINS2;
IPCPDEBUG((LOG_INFO, "ipcp_reqci: received WINS%d Request\n", d+1));
/* If we do not have a DNS address then we cannot send it */
if (ao->winsaddr[d] == 0 ||
cilen != CILEN_ADDR) { /* Check CI length */
orc = CONFREJ; /* Reject CI */
break;
}
GETLONG(tl, p);
if (htonl(tl) != ao->winsaddr[d]) {
DECPTR(sizeof(u32_t), p);
tl = ntohl(ao->winsaddr[d]);
PUTLONG(tl, p);
orc = CONFNAK;
}
break;
case CI_COMPRESSTYPE:
if (!ao->neg_vj) {
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Rejecting COMPRESSTYPE not allowed\n"));
orc = CONFREJ;
break;
} else if (cilen != CILEN_VJ && cilen != CILEN_COMPRESS) {
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Rejecting COMPRESSTYPE len=%d\n", cilen));
orc = CONFREJ;
break;
}
GETSHORT(cishort, p);
if (!(cishort == IPCP_VJ_COMP ||
(cishort == IPCP_VJ_COMP_OLD && cilen == CILEN_COMPRESS))) {
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Rejecting COMPRESSTYPE %d\n", cishort));
orc = CONFREJ;
break;
}
ho->neg_vj = 1;
ho->vj_protocol = cishort;
if (cilen == CILEN_VJ) {
GETCHAR(maxslotindex, p);
if (maxslotindex > ao->maxslotindex) {
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Naking VJ max slot %d\n", maxslotindex));
orc = CONFNAK;
if (!reject_if_disagree) {
DECPTR(1, p);
PUTCHAR(ao->maxslotindex, p);
}
}
GETCHAR(cflag, p);
if (cflag && !ao->cflag) {
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Naking VJ cflag %d\n", cflag));
orc = CONFNAK;
if (!reject_if_disagree) {
DECPTR(1, p);
PUTCHAR(wo->cflag, p);
}
}
ho->maxslotindex = maxslotindex;
ho->cflag = cflag;
} else {
ho->old_vj = 1;
ho->maxslotindex = MAX_SLOTS - 1;
ho->cflag = 1;
}
IPCPDEBUG((LOG_INFO,
"ipcp_reqci: received COMPRESSTYPE p=%d old=%d maxslot=%d cflag=%d\n",
ho->vj_protocol, ho->old_vj, ho->maxslotindex, ho->cflag));
break;
default:
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Rejecting unknown CI type %d\n", citype));
orc = CONFREJ;
break;
}
endswitch:
if (orc == CONFACK && /* Good CI */
rc != CONFACK) { /* but prior CI wasnt? */
continue; /* Don't send this one */
}
if (orc == CONFNAK) { /* Nak this CI? */
if (reject_if_disagree) { /* Getting fed up with sending NAKs? */
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Rejecting too many naks\n"));
orc = CONFREJ; /* Get tough if so */
} else {
if (rc == CONFREJ) { /* Rejecting prior CI? */
continue; /* Don't send this one */
}
if (rc == CONFACK) { /* Ack'd all prior CIs? */
rc = CONFNAK; /* Not anymore... */
ucp = inp; /* Backup */
}
}
}
if (orc == CONFREJ && /* Reject this CI */
rc != CONFREJ) { /* but no prior ones? */
rc = CONFREJ;
ucp = inp; /* Backup */
}
/* Need to move CI? */
if (ucp != cip) {
BCOPY(cip, ucp, cilen); /* Move it */
}
/* Update output pointer */
INCPTR(cilen, ucp);
}
/*
* If we aren't rejecting this packet, and we want to negotiate
* their address, and they didn't send their address, then we
* send a NAK with a CI_ADDR option appended. We assume the
* input buffer is long enough that we can append the extra
* option safely.
*/
if (rc != CONFREJ && !ho->neg_addr &&
wo->req_addr && !reject_if_disagree) {
IPCPDEBUG((LOG_INFO, "ipcp_reqci: Requesting peer address\n"));
if (rc == CONFACK) {
rc = CONFNAK;
ucp = inp; /* reset pointer */
wo->req_addr = 0; /* don't ask again */
}
PUTCHAR(CI_ADDR, ucp);
PUTCHAR(CILEN_ADDR, ucp);
tl = ntohl(wo->hisaddr);
PUTLONG(tl, ucp);
}
*len = (int)(ucp - inp); /* Compute output length */
IPCPDEBUG((LOG_INFO, "ipcp_reqci: returning Configure-%s\n", CODENAME(rc)));
return (rc); /* Return final code */
}
#if 0
/*
* ip_check_options - check that any IP-related options are OK,
* and assign appropriate defaults.
*/
static void
ip_check_options(u_long localAddr)
{
ipcp_options *wo = &ipcp_wantoptions[0];
/*
* Load our default IP address but allow the remote host to give us
* a new address.
*/
if (wo->ouraddr == 0 && !ppp_settings.disable_defaultip) {
wo->accept_local = 1; /* don't insist on this default value */
wo->ouraddr = htonl(localAddr);
}
}
#endif
/*
* ipcp_up - IPCP has come UP.
*
* Configure the IP network interface appropriately and bring it up.
*/
static void
ipcp_up(fsm *f)
{
u32_t mask;
ipcp_options *ho = &ipcp_hisoptions[f->unit];
ipcp_options *go = &ipcp_gotoptions[f->unit];
ipcp_options *wo = &ipcp_wantoptions[f->unit];
np_up(f->unit, PPP_IP);
IPCPDEBUG((LOG_INFO, "ipcp: up\n"));
/*
* We must have a non-zero IP address for both ends of the link.
*/
if (!ho->neg_addr) {
ho->hisaddr = wo->hisaddr;
}
if (ho->hisaddr == 0) {
IPCPDEBUG((LOG_ERR, "Could not determine remote IP address\n"));
ipcp_close(f->unit, "Could not determine remote IP address");
return;
}
if (go->ouraddr == 0) {
IPCPDEBUG((LOG_ERR, "Could not determine local IP address\n"));
ipcp_close(f->unit, "Could not determine local IP address");
return;
}
if (ppp_settings.usepeerdns && (go->dnsaddr[0] || go->dnsaddr[1])) {
/*pppGotDNSAddrs(go->dnsaddr[0], go->dnsaddr[1]);*/
}
/*
* Check that the peer is allowed to use the IP address it wants.
*/
if (!auth_ip_addr(f->unit, ho->hisaddr)) {
IPCPDEBUG((LOG_ERR, "Peer is not authorized to use remote address %s\n",
inet_ntoa(ho->hisaddr)));
ipcp_close(f->unit, "Unauthorized remote IP address");
return;
}
/* set tcp compression */
sifvjcomp(f->unit, ho->neg_vj, ho->cflag, ho->maxslotindex);
/*
* Set IP addresses and (if specified) netmask.
*/
mask = GetMask(go->ouraddr);
if (!sifaddr(f->unit, go->ouraddr, ho->hisaddr, mask, go->dnsaddr[0], go->dnsaddr[1])) {
IPCPDEBUG((LOG_WARNING, "sifaddr failed\n"));
ipcp_close(f->unit, "Interface configuration failed");
return;
}
/* bring the interface up for IP */
if (!sifup(f->unit)) {
IPCPDEBUG((LOG_WARNING, "sifup failed\n"));
ipcp_close(f->unit, "Interface configuration failed");
return;
}
sifnpmode(f->unit, PPP_IP, NPMODE_PASS);
/* assign a default route through the interface if required */
if (ipcp_wantoptions[f->unit].default_route) {
if (sifdefaultroute(f->unit, go->ouraddr, ho->hisaddr)) {
default_route_set[f->unit] = 1;
}
}
IPCPDEBUG((LOG_NOTICE, "local IP address %s\n", inet_ntoa(go->ouraddr)));
IPCPDEBUG((LOG_NOTICE, "remote IP address %s\n", inet_ntoa(ho->hisaddr)));
if (go->dnsaddr[0]) {
IPCPDEBUG((LOG_NOTICE, "primary DNS address %s\n", inet_ntoa(go->dnsaddr[0])));
}
if (go->dnsaddr[1]) {
IPCPDEBUG((LOG_NOTICE, "secondary DNS address %s\n", inet_ntoa(go->dnsaddr[1])));
}
}
/*
* ipcp_down - IPCP has gone DOWN.
*
* Take the IP network interface down, clear its addresses
* and delete routes through it.
*/
static void
ipcp_down(fsm *f)
{
IPCPDEBUG((LOG_INFO, "ipcp: down\n"));
np_down(f->unit, PPP_IP);
sifvjcomp(f->unit, 0, 0, 0);
sifdown(f->unit);
ipcp_clear_addrs(f->unit);
}
/*
* ipcp_clear_addrs() - clear the interface addresses, routes, etc.
*/
static void
ipcp_clear_addrs(int unit)
{
u32_t ouraddr, hisaddr;
ouraddr = ipcp_gotoptions[unit].ouraddr;
hisaddr = ipcp_hisoptions[unit].hisaddr;
if (default_route_set[unit]) {
cifdefaultroute(unit, ouraddr, hisaddr);
default_route_set[unit] = 0;
}
cifaddr(unit, ouraddr, hisaddr);
}
/*
* ipcp_finished - possibly shut down the lower layers.
*/
static void
ipcp_finished(fsm *f)
{
np_finished(f->unit, PPP_IP);
}
#if 0
static int
ipcp_printpkt(u_char *p, int plen, void (*printer) (void *, char *, ...), void *arg)
{
LWIP_UNUSED_ARG(p);
LWIP_UNUSED_ARG(plen);
LWIP_UNUSED_ARG(printer);
LWIP_UNUSED_ARG(arg);
return 0;
}
/*
* ip_active_pkt - see if this IP packet is worth bringing the link up for.
* We don't bring the link up for IP fragments or for TCP FIN packets
* with no data.
*/
#define IP_HDRLEN 20 /* bytes */
#define IP_OFFMASK 0x1fff
#define IPPROTO_TCP 6
#define TCP_HDRLEN 20
#define TH_FIN 0x01
/*
* We use these macros because the IP header may be at an odd address,
* and some compilers might use word loads to get th_off or ip_hl.
*/
#define net_short(x) (((x)[0] << 8) + (x)[1])
#define get_iphl(x) (((unsigned char *)(x))[0] & 0xF)
#define get_ipoff(x) net_short((unsigned char *)(x) + 6)
#define get_ipproto(x) (((unsigned char *)(x))[9])
#define get_tcpoff(x) (((unsigned char *)(x))[12] >> 4)
#define get_tcpflags(x) (((unsigned char *)(x))[13])
static int
ip_active_pkt(u_char *pkt, int len)
{
u_char *tcp;
int hlen;
len -= PPP_HDRLEN;
pkt += PPP_HDRLEN;
if (len < IP_HDRLEN) {
return 0;
}
if ((get_ipoff(pkt) & IP_OFFMASK) != 0) {
return 0;
}
if (get_ipproto(pkt) != IPPROTO_TCP) {
return 1;
}
hlen = get_iphl(pkt) * 4;
if (len < hlen + TCP_HDRLEN) {
return 0;
}
tcp = pkt + hlen;
if ((get_tcpflags(tcp) & TH_FIN) != 0 && len == hlen + get_tcpoff(tcp) * 4) {
return 0;
}
return 1;
}
#endif
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/ipcp.c | C | oos | 40,815 |
/*
* Definitions for tcp compression routines.
*
* $Id: vj.h,v 1.5 2007/12/19 20:47:23 fbernon Exp $
*
* Copyright (c) 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
* - Initial distribution.
*/
#ifndef VJ_H
#define VJ_H
#include "vjbsdhdr.h"
#define MAX_SLOTS 16 /* must be > 2 and < 256 */
#define MAX_HDR 128
/*
* Compressed packet format:
*
* The first octet contains the packet type (top 3 bits), TCP
* 'push' bit, and flags that indicate which of the 4 TCP sequence
* numbers have changed (bottom 5 bits). The next octet is a
* conversation number that associates a saved IP/TCP header with
* the compressed packet. The next two octets are the TCP checksum
* from the original datagram. The next 0 to 15 octets are
* sequence number changes, one change per bit set in the header
* (there may be no changes and there are two special cases where
* the receiver implicitly knows what changed -- see below).
*
* There are 5 numbers which can change (they are always inserted
* in the following order): TCP urgent pointer, window,
* acknowlegement, sequence number and IP ID. (The urgent pointer
* is different from the others in that its value is sent, not the
* change in value.) Since typical use of SLIP links is biased
* toward small packets (see comments on MTU/MSS below), changes
* use a variable length coding with one octet for numbers in the
* range 1 - 255 and 3 octets (0, MSB, LSB) for numbers in the
* range 256 - 65535 or 0. (If the change in sequence number or
* ack is more than 65535, an uncompressed packet is sent.)
*/
/*
* Packet types (must not conflict with IP protocol version)
*
* The top nibble of the first octet is the packet type. There are
* three possible types: IP (not proto TCP or tcp with one of the
* control flags set); uncompressed TCP (a normal IP/TCP packet but
* with the 8-bit protocol field replaced by an 8-bit connection id --
* this type of packet syncs the sender & receiver); and compressed
* TCP (described above).
*
* LSB of 4-bit field is TCP "PUSH" bit (a worthless anachronism) and
* is logically part of the 4-bit "changes" field that follows. Top
* three bits are actual packet type. For backward compatibility
* and in the interest of conserving bits, numbers are chosen so the
* IP protocol version number (4) which normally appears in this nibble
* means "IP packet".
*/
/* packet types */
#define TYPE_IP 0x40
#define TYPE_UNCOMPRESSED_TCP 0x70
#define TYPE_COMPRESSED_TCP 0x80
#define TYPE_ERROR 0x00
/* Bits in first octet of compressed packet */
#define NEW_C 0x40 /* flag bits for what changed in a packet */
#define NEW_I 0x20
#define NEW_S 0x08
#define NEW_A 0x04
#define NEW_W 0x02
#define NEW_U 0x01
/* reserved, special-case values of above */
#define SPECIAL_I (NEW_S|NEW_W|NEW_U) /* echoed interactive traffic */
#define SPECIAL_D (NEW_S|NEW_A|NEW_W|NEW_U) /* unidirectional data */
#define SPECIALS_MASK (NEW_S|NEW_A|NEW_W|NEW_U)
#define TCP_PUSH_BIT 0x10
/*
* "state" data for each active tcp conversation on the wire. This is
* basically a copy of the entire IP/TCP header from the last packet
* we saw from the conversation together with a small identifier
* the transmit & receive ends of the line use to locate saved header.
*/
struct cstate {
struct cstate *cs_next; /* next most recently used state (xmit only) */
u_short cs_hlen; /* size of hdr (receive only) */
u_char cs_id; /* connection # associated with this state */
u_char cs_filler;
union {
char csu_hdr[MAX_HDR];
struct ip csu_ip; /* ip/tcp hdr from most recent packet */
} vjcs_u;
};
#define cs_ip vjcs_u.csu_ip
#define cs_hdr vjcs_u.csu_hdr
struct vjstat {
unsigned long vjs_packets; /* outbound packets */
unsigned long vjs_compressed; /* outbound compressed packets */
unsigned long vjs_searches; /* searches for connection state */
unsigned long vjs_misses; /* times couldn't find conn. state */
unsigned long vjs_uncompressedin; /* inbound uncompressed packets */
unsigned long vjs_compressedin; /* inbound compressed packets */
unsigned long vjs_errorin; /* inbound unknown type packets */
unsigned long vjs_tossed; /* inbound packets tossed because of error */
};
/*
* all the state data for one serial line (we need one of these per line).
*/
struct vjcompress {
struct cstate *last_cs; /* most recently used tstate */
u_char last_recv; /* last rcvd conn. id */
u_char last_xmit; /* last sent conn. id */
u_short flags;
u_char maxSlotIndex;
u_char compressSlot; /* Flag indicating OK to compress slot ID. */
#if LINK_STATS
struct vjstat stats;
#endif
struct cstate tstate[MAX_SLOTS]; /* xmit connection states */
struct cstate rstate[MAX_SLOTS]; /* receive connection states */
};
/* flag values */
#define VJF_TOSS 1U /* tossing rcvd frames because of input err */
extern void vj_compress_init (struct vjcompress *comp);
extern u_int vj_compress_tcp (struct vjcompress *comp, struct pbuf *pb);
extern void vj_uncompress_err (struct vjcompress *comp);
extern int vj_uncompress_uncomp(struct pbuf *nb, struct vjcompress *comp);
extern int vj_uncompress_tcp (struct pbuf **nb, struct vjcompress *comp);
#endif /* VJ_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/vj.h | C | oos | 6,326 |
/*****************************************************************************
* chap.h - Network Challenge Handshake Authentication Protocol header file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1998 Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-03 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original built from BSD network code.
******************************************************************************/
/*
* chap.h - Challenge Handshake Authentication Protocol definitions.
*
* Copyright (c) 1993 The Australian National University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the Australian National University. The name of the University
* may not be used to endorse or promote products derived from this
* software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Copyright (c) 1991 Gregory M. Christy
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the author.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* $Id: chap.h,v 1.4 2007/12/19 20:47:22 fbernon Exp $
*/
#ifndef CHAP_H
#define CHAP_H
/*************************
*** PUBLIC DEFINITIONS ***
*************************/
/* Code + ID + length */
#define CHAP_HEADERLEN 4
/*
* CHAP codes.
*/
#define CHAP_DIGEST_MD5 5 /* use MD5 algorithm */
#define MD5_SIGNATURE_SIZE 16 /* 16 bytes in a MD5 message digest */
#define CHAP_MICROSOFT 0x80 /* use Microsoft-compatible alg. */
#define MS_CHAP_RESPONSE_LEN 49 /* Response length for MS-CHAP */
#define CHAP_CHALLENGE 1
#define CHAP_RESPONSE 2
#define CHAP_SUCCESS 3
#define CHAP_FAILURE 4
/*
* Challenge lengths (for challenges we send) and other limits.
*/
#define MIN_CHALLENGE_LENGTH 32
#define MAX_CHALLENGE_LENGTH 64
#define MAX_RESPONSE_LENGTH 64 /* sufficient for MD5 or MS-CHAP */
/*
* Client (peer) states.
*/
#define CHAPCS_INITIAL 0 /* Lower layer down, not opened */
#define CHAPCS_CLOSED 1 /* Lower layer up, not opened */
#define CHAPCS_PENDING 2 /* Auth us to peer when lower up */
#define CHAPCS_LISTEN 3 /* Listening for a challenge */
#define CHAPCS_RESPONSE 4 /* Sent response, waiting for status */
#define CHAPCS_OPEN 5 /* We've received Success */
/*
* Server (authenticator) states.
*/
#define CHAPSS_INITIAL 0 /* Lower layer down, not opened */
#define CHAPSS_CLOSED 1 /* Lower layer up, not opened */
#define CHAPSS_PENDING 2 /* Auth peer when lower up */
#define CHAPSS_INITIAL_CHAL 3 /* We've sent the first challenge */
#define CHAPSS_OPEN 4 /* We've sent a Success msg */
#define CHAPSS_RECHALLENGE 5 /* We've sent another challenge */
#define CHAPSS_BADAUTH 6 /* We've sent a Failure msg */
/************************
*** PUBLIC DATA TYPES ***
************************/
/*
* Each interface is described by a chap structure.
*/
typedef struct chap_state {
int unit; /* Interface unit number */
int clientstate; /* Client state */
int serverstate; /* Server state */
u_char challenge[MAX_CHALLENGE_LENGTH]; /* last challenge string sent */
u_char chal_len; /* challenge length */
u_char chal_id; /* ID of last challenge */
u_char chal_type; /* hash algorithm for challenges */
u_char id; /* Current id */
char *chal_name; /* Our name to use with challenge */
int chal_interval; /* Time until we challenge peer again */
int timeouttime; /* Timeout time in seconds */
int max_transmits; /* Maximum # of challenge transmissions */
int chal_transmits; /* Number of transmissions of challenge */
int resp_transmits; /* Number of transmissions of response */
u_char response[MAX_RESPONSE_LENGTH]; /* Response to send */
u_char resp_length; /* length of response */
u_char resp_id; /* ID for response messages */
u_char resp_type; /* hash algorithm for responses */
char *resp_name; /* Our name to send with response */
} chap_state;
/******************
*** PUBLIC DATA ***
******************/
extern chap_state chap[];
extern struct protent chap_protent;
/***********************
*** PUBLIC FUNCTIONS ***
***********************/
void ChapAuthWithPeer (int, char *, int);
void ChapAuthPeer (int, char *, int);
#endif /* CHAP_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/chap.h | C | oos | 7,089 |
/*****************************************************************************
* randm.c - Random number generator program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* Copyright (c) 1998 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 98-06-03 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Extracted from avos.
*****************************************************************************/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "md5.h"
#include "randm.h"
#include "ppp.h"
#include "pppdebug.h"
#if MD5_SUPPORT /* this module depends on MD5 */
#define RANDPOOLSZ 16 /* Bytes stored in the pool of randomness. */
/*****************************/
/*** LOCAL DATA STRUCTURES ***/
/*****************************/
static char randPool[RANDPOOLSZ]; /* Pool of randomness. */
static long randCount = 0; /* Pseudo-random incrementer */
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
/*
* Initialize the random number generator.
*
* Since this is to be called on power up, we don't have much
* system randomess to work with. Here all we use is the
* real-time clock. We'll accumulate more randomness as soon
* as things start happening.
*/
void
avRandomInit()
{
avChurnRand(NULL, 0);
}
/*
* Churn the randomness pool on a random event. Call this early and often
* on random and semi-random system events to build randomness in time for
* usage. For randomly timed events, pass a null pointer and a zero length
* and this will use the system timer and other sources to add randomness.
* If new random data is available, pass a pointer to that and it will be
* included.
*
* Ref: Applied Cryptography 2nd Ed. by Bruce Schneier p. 427
*/
void
avChurnRand(char *randData, u32_t randLen)
{
MD5_CTX md5;
/* ppp_trace(LOG_INFO, "churnRand: %u@%P\n", randLen, randData); */
MD5Init(&md5);
MD5Update(&md5, (u_char *)randPool, sizeof(randPool));
if (randData) {
MD5Update(&md5, (u_char *)randData, randLen);
} else {
struct {
/* INCLUDE fields for any system sources of randomness */
char foobar;
} sysData;
/* Load sysData fields here. */
MD5Update(&md5, (u_char *)&sysData, sizeof(sysData));
}
MD5Final((u_char *)randPool, &md5);
/* ppp_trace(LOG_INFO, "churnRand: -> 0\n"); */
}
/*
* Use the random pool to generate random data. This degrades to pseudo
* random when used faster than randomness is supplied using churnRand().
* Note: It's important that there be sufficient randomness in randPool
* before this is called for otherwise the range of the result may be
* narrow enough to make a search feasible.
*
* Ref: Applied Cryptography 2nd Ed. by Bruce Schneier p. 427
*
* XXX Why does he not just call churnRand() for each block? Probably
* so that you don't ever publish the seed which could possibly help
* predict future values.
* XXX Why don't we preserve md5 between blocks and just update it with
* randCount each time? Probably there is a weakness but I wish that
* it was documented.
*/
void
avGenRand(char *buf, u32_t bufLen)
{
MD5_CTX md5;
u_char tmp[16];
u32_t n;
while (bufLen > 0) {
n = LWIP_MIN(bufLen, RANDPOOLSZ);
MD5Init(&md5);
MD5Update(&md5, (u_char *)randPool, sizeof(randPool));
MD5Update(&md5, (u_char *)&randCount, sizeof(randCount));
MD5Final(tmp, &md5);
randCount++;
MEMCPY(buf, tmp, n);
buf += n;
bufLen -= n;
}
}
/*
* Return a new random number.
*/
u32_t
avRandom()
{
u32_t newRand;
avGenRand((char *)&newRand, sizeof(newRand));
return newRand;
}
#else /* MD5_SUPPORT */
/*****************************/
/*** LOCAL DATA STRUCTURES ***/
/*****************************/
static int avRandomized = 0; /* Set when truely randomized. */
static u32_t avRandomSeed = 0; /* Seed used for random number generation. */
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
/*
* Initialize the random number generator.
*
* Here we attempt to compute a random number seed but even if
* it isn't random, we'll randomize it later.
*
* The current method uses the fields from the real time clock,
* the idle process counter, the millisecond counter, and the
* hardware timer tick counter. When this is invoked
* in startup(), then the idle counter and timer values may
* repeat after each boot and the real time clock may not be
* operational. Thus we call it again on the first random
* event.
*/
void
avRandomInit()
{
#if 0
/* Get a pointer into the last 4 bytes of clockBuf. */
u32_t *lptr1 = (u32_t *)((char *)&clockBuf[3]);
/*
* Initialize our seed using the real-time clock, the idle
* counter, the millisecond timer, and the hardware timer
* tick counter. The real-time clock and the hardware
* tick counter are the best sources of randomness but
* since the tick counter is only 16 bit (and truncated
* at that), the idle counter and millisecond timer
* (which may be small values) are added to help
* randomize the lower 16 bits of the seed.
*/
readClk();
avRandomSeed += *(u32_t *)clockBuf + *lptr1 + OSIdleCtr
+ ppp_mtime() + ((u32_t)TM1 << 16) + TM1;
#else
avRandomSeed += sys_jiffies(); /* XXX */
#endif
/* Initialize the Borland random number generator. */
srand((unsigned)avRandomSeed);
}
/*
* Randomize our random seed value. Here we use the fact that
* this function is called at *truely random* times by the polling
* and network functions. Here we only get 16 bits of new random
* value but we use the previous value to randomize the other 16
* bits.
*/
void
avRandomize(void)
{
static u32_t last_jiffies;
if (!avRandomized) {
avRandomized = !0;
avRandomInit();
/* The initialization function also updates the seed. */
} else {
/* avRandomSeed += (avRandomSeed << 16) + TM1; */
avRandomSeed += (sys_jiffies() - last_jiffies); /* XXX */
}
last_jiffies = sys_jiffies();
}
/*
* Return a new random number.
* Here we use the Borland rand() function to supply a pseudo random
* number which we make truely random by combining it with our own
* seed which is randomized by truely random events.
* Thus the numbers will be truely random unless there have been no
* operator or network events in which case it will be pseudo random
* seeded by the real time clock.
*/
u32_t
avRandom()
{
return ((((u32_t)rand() << 16) + rand()) + avRandomSeed);
}
#endif /* MD5_SUPPORT */
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/randm.c | C | oos | 8,219 |
/*****************************************************************************
* lcp.c - Network Link Control Protocol program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-01 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original.
*****************************************************************************/
/*
* lcp.c - PPP Link Control Protocol.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "pppdebug.h"
#include "fsm.h"
#include "chap.h"
#include "magic.h"
#include "auth.h"
#include "lcp.h"
#include <string.h>
#if PPPOE_SUPPORT
#include "netif/ppp_oe.h"
#else
#define PPPOE_MAXMTU PPP_MAXMRU
#endif
/*************************/
/*** LOCAL DEFINITIONS ***/
/*************************/
/*
* Length of each type of configuration option (in octets)
*/
#define CILEN_VOID 2
#define CILEN_CHAR 3
#define CILEN_SHORT 4 /* CILEN_VOID + sizeof(short) */
#define CILEN_CHAP 5 /* CILEN_VOID + sizeof(short) + 1 */
#define CILEN_LONG 6 /* CILEN_VOID + sizeof(long) */
#define CILEN_LQR 8 /* CILEN_VOID + sizeof(short) + sizeof(long) */
#define CILEN_CBCP 3
/***********************************/
/*** LOCAL FUNCTION DECLARATIONS ***/
/***********************************/
/*
* Callbacks for fsm code. (CI = Configuration Information)
*/
static void lcp_resetci (fsm*); /* Reset our CI */
static int lcp_cilen (fsm*); /* Return length of our CI */
static void lcp_addci (fsm*, u_char*, int*); /* Add our CI to pkt */
static int lcp_ackci (fsm*, u_char*, int); /* Peer ack'd our CI */
static int lcp_nakci (fsm*, u_char*, int); /* Peer nak'd our CI */
static int lcp_rejci (fsm*, u_char*, int); /* Peer rej'd our CI */
static int lcp_reqci (fsm*, u_char*, int*, int); /* Rcv peer CI */
static void lcp_up (fsm*); /* We're UP */
static void lcp_down (fsm*); /* We're DOWN */
static void lcp_starting (fsm*); /* We need lower layer up */
static void lcp_finished (fsm*); /* We need lower layer down */
static int lcp_extcode (fsm*, int, u_char, u_char*, int);
static void lcp_rprotrej (fsm*, u_char*, int);
/*
* routines to send LCP echos to peer
*/
static void lcp_echo_lowerup (int);
static void lcp_echo_lowerdown (int);
static void LcpEchoTimeout (void*);
static void lcp_received_echo_reply (fsm*, int, u_char*, int);
static void LcpSendEchoRequest (fsm*);
static void LcpLinkFailure (fsm*);
static void LcpEchoCheck (fsm*);
/*
* Protocol entry points.
* Some of these are called directly.
*/
static void lcp_input (int, u_char *, int);
static void lcp_protrej (int);
#define CODENAME(x) ((x) == CONFACK ? "ACK" : (x) == CONFNAK ? "NAK" : "REJ")
/******************************/
/*** PUBLIC DATA STRUCTURES ***/
/******************************/
/* global vars */
LinkPhase lcp_phase[NUM_PPP]; /* Phase of link session (RFC 1661) */
lcp_options lcp_wantoptions[NUM_PPP]; /* Options that we want to request */
lcp_options lcp_gotoptions[NUM_PPP]; /* Options that peer ack'd */
lcp_options lcp_allowoptions[NUM_PPP]; /* Options we allow peer to request */
lcp_options lcp_hisoptions[NUM_PPP]; /* Options that we ack'd */
ext_accm xmit_accm[NUM_PPP]; /* extended transmit ACCM */
/*****************************/
/*** LOCAL DATA STRUCTURES ***/
/*****************************/
static fsm lcp_fsm[NUM_PPP]; /* LCP fsm structure (global)*/
static u_int lcp_echo_interval = LCP_ECHOINTERVAL; /* Interval between LCP echo-requests */
static u_int lcp_echo_fails = LCP_MAXECHOFAILS; /* Tolerance to unanswered echo-requests */
static u32_t lcp_echos_pending = 0; /* Number of outstanding echo msgs */
static u32_t lcp_echo_number = 0; /* ID number of next echo frame */
static u32_t lcp_echo_timer_running = 0; /* TRUE if a timer is running */
static u_char nak_buffer[PPP_MRU]; /* where we construct a nak packet */
static fsm_callbacks lcp_callbacks = { /* LCP callback routines */
lcp_resetci, /* Reset our Configuration Information */
lcp_cilen, /* Length of our Configuration Information */
lcp_addci, /* Add our Configuration Information */
lcp_ackci, /* ACK our Configuration Information */
lcp_nakci, /* NAK our Configuration Information */
lcp_rejci, /* Reject our Configuration Information */
lcp_reqci, /* Request peer's Configuration Information */
lcp_up, /* Called when fsm reaches LS_OPENED state */
lcp_down, /* Called when fsm leaves LS_OPENED state */
lcp_starting, /* Called when we want the lower layer up */
lcp_finished, /* Called when we want the lower layer down */
NULL, /* Called when Protocol-Reject received */
NULL, /* Retransmission is necessary */
lcp_extcode, /* Called to handle LCP-specific codes */
"LCP" /* String name of protocol */
};
struct protent lcp_protent = {
PPP_LCP,
lcp_init,
lcp_input,
lcp_protrej,
lcp_lowerup,
lcp_lowerdown,
lcp_open,
lcp_close,
#if 0
lcp_printpkt,
NULL,
#endif
1,
"LCP",
#if 0
NULL,
NULL,
NULL
#endif
};
int lcp_loopbackfail = DEFLOOPBACKFAIL;
/***********************************/
/*** PUBLIC FUNCTION DEFINITIONS ***/
/***********************************/
/*
* lcp_init - Initialize LCP.
*/
void
lcp_init(int unit)
{
fsm *f = &lcp_fsm[unit];
lcp_options *wo = &lcp_wantoptions[unit];
lcp_options *ao = &lcp_allowoptions[unit];
f->unit = unit;
f->protocol = PPP_LCP;
f->callbacks = &lcp_callbacks;
fsm_init(f);
wo->passive = 0;
wo->silent = 0;
wo->restart = 0; /* Set to 1 in kernels or multi-line implementations */
wo->neg_mru = 1;
wo->mru = PPP_DEFMRU;
wo->neg_asyncmap = 1;
wo->asyncmap = 0x00000000l; /* Assume don't need to escape any ctl chars. */
wo->neg_chap = 0; /* Set to 1 on server */
wo->neg_upap = 0; /* Set to 1 on server */
wo->chap_mdtype = CHAP_DIGEST_MD5;
wo->neg_magicnumber = 1;
wo->neg_pcompression = 1;
wo->neg_accompression = 1;
wo->neg_lqr = 0; /* no LQR implementation yet */
wo->neg_cbcp = 0;
ao->neg_mru = 1;
ao->mru = PPP_MAXMRU;
ao->neg_asyncmap = 1;
ao->asyncmap = 0x00000000l; /* Assume don't need to escape any ctl chars. */
ao->neg_chap = (CHAP_SUPPORT != 0);
ao->chap_mdtype = CHAP_DIGEST_MD5;
ao->neg_upap = (PAP_SUPPORT != 0);
ao->neg_magicnumber = 1;
ao->neg_pcompression = 1;
ao->neg_accompression = 1;
ao->neg_lqr = 0; /* no LQR implementation yet */
ao->neg_cbcp = (CBCP_SUPPORT != 0);
/*
* Set transmit escape for the flag and escape characters plus anything
* set for the allowable options.
*/
memset(xmit_accm[unit], 0, sizeof(xmit_accm[0]));
xmit_accm[unit][15] = 0x60;
xmit_accm[unit][0] = (u_char)((ao->asyncmap & 0xFF));
xmit_accm[unit][1] = (u_char)((ao->asyncmap >> 8) & 0xFF);
xmit_accm[unit][2] = (u_char)((ao->asyncmap >> 16) & 0xFF);
xmit_accm[unit][3] = (u_char)((ao->asyncmap >> 24) & 0xFF);
LCPDEBUG((LOG_INFO, "lcp_init: xmit_accm=%X %X %X %X\n",
xmit_accm[unit][0],
xmit_accm[unit][1],
xmit_accm[unit][2],
xmit_accm[unit][3]));
lcp_phase[unit] = PHASE_INITIALIZE;
}
/*
* lcp_open - LCP is allowed to come up.
*/
void
lcp_open(int unit)
{
fsm *f = &lcp_fsm[unit];
lcp_options *wo = &lcp_wantoptions[unit];
f->flags = 0;
if (wo->passive) {
f->flags |= OPT_PASSIVE;
}
if (wo->silent) {
f->flags |= OPT_SILENT;
}
fsm_open(f);
lcp_phase[unit] = PHASE_ESTABLISH;
}
/*
* lcp_close - Take LCP down.
*/
void
lcp_close(int unit, char *reason)
{
fsm *f = &lcp_fsm[unit];
if (lcp_phase[unit] != PHASE_DEAD) {
lcp_phase[unit] = PHASE_TERMINATE;
}
if (f->state == LS_STOPPED && f->flags & (OPT_PASSIVE|OPT_SILENT)) {
/*
* This action is not strictly according to the FSM in RFC1548,
* but it does mean that the program terminates if you do an
* lcp_close() in passive/silent mode when a connection hasn't
* been established.
*/
f->state = LS_CLOSED;
lcp_finished(f);
} else {
fsm_close(&lcp_fsm[unit], reason);
}
}
/*
* lcp_lowerup - The lower layer is up.
*/
void
lcp_lowerup(int unit)
{
lcp_options *wo = &lcp_wantoptions[unit];
/*
* Don't use A/C or protocol compression on transmission,
* but accept A/C and protocol compressed packets
* if we are going to ask for A/C and protocol compression.
*/
ppp_set_xaccm(unit, &xmit_accm[unit]);
ppp_send_config(unit, PPP_MRU, 0xffffffffl, 0, 0);
ppp_recv_config(unit, PPP_MRU, 0x00000000l,
wo->neg_pcompression, wo->neg_accompression);
peer_mru[unit] = PPP_MRU;
lcp_allowoptions[unit].asyncmap = (u_long)xmit_accm[unit][0]
| ((u_long)xmit_accm[unit][1] << 8)
| ((u_long)xmit_accm[unit][2] << 16)
| ((u_long)xmit_accm[unit][3] << 24);
LCPDEBUG((LOG_INFO, "lcp_lowerup: asyncmap=%X %X %X %X\n",
xmit_accm[unit][3],
xmit_accm[unit][2],
xmit_accm[unit][1],
xmit_accm[unit][0]));
fsm_lowerup(&lcp_fsm[unit]);
}
/*
* lcp_lowerdown - The lower layer is down.
*/
void
lcp_lowerdown(int unit)
{
fsm_lowerdown(&lcp_fsm[unit]);
}
/*
* lcp_sprotrej - Send a Protocol-Reject for some protocol.
*/
void
lcp_sprotrej(int unit, u_char *p, int len)
{
/*
* Send back the protocol and the information field of the
* rejected packet. We only get here if LCP is in the LS_OPENED state.
*/
fsm_sdata(&lcp_fsm[unit], PROTREJ, ++lcp_fsm[unit].id, p, len);
}
/**********************************/
/*** LOCAL FUNCTION DEFINITIONS ***/
/**********************************/
/*
* lcp_input - Input LCP packet.
*/
static void
lcp_input(int unit, u_char *p, int len)
{
fsm *f = &lcp_fsm[unit];
fsm_input(f, p, len);
}
/*
* lcp_extcode - Handle a LCP-specific code.
*/
static int
lcp_extcode(fsm *f, int code, u_char id, u_char *inp, int len)
{
u_char *magp;
switch( code ){
case PROTREJ:
lcp_rprotrej(f, inp, len);
break;
case ECHOREQ:
if (f->state != LS_OPENED) {
break;
}
LCPDEBUG((LOG_INFO, "lcp: Echo-Request, Rcvd id %d\n", id));
magp = inp;
PUTLONG(lcp_gotoptions[f->unit].magicnumber, magp);
fsm_sdata(f, ECHOREP, id, inp, len);
break;
case ECHOREP:
lcp_received_echo_reply(f, id, inp, len);
break;
case DISCREQ:
break;
default:
return 0;
}
return 1;
}
/*
* lcp_rprotrej - Receive an Protocol-Reject.
*
* Figure out which protocol is rejected and inform it.
*/
static void
lcp_rprotrej(fsm *f, u_char *inp, int len)
{
int i;
struct protent *protp;
u_short prot;
if (len < sizeof (u_short)) {
LCPDEBUG((LOG_INFO, "lcp_rprotrej: Rcvd short Protocol-Reject packet!\n"));
return;
}
GETSHORT(prot, inp);
LCPDEBUG((LOG_INFO, "lcp_rprotrej: Rcvd Protocol-Reject packet for %x!\n", prot));
/*
* Protocol-Reject packets received in any state other than the LCP
* LS_OPENED state SHOULD be silently discarded.
*/
if( f->state != LS_OPENED ) {
LCPDEBUG((LOG_INFO, "Protocol-Reject discarded: LCP in state %d\n", f->state));
return;
}
/*
* Upcall the proper Protocol-Reject routine.
*/
for (i = 0; (protp = ppp_protocols[i]) != NULL; ++i) {
if (protp->protocol == prot && protp->enabled_flag) {
(*protp->protrej)(f->unit);
return;
}
}
LCPDEBUG((LOG_WARNING, "Protocol-Reject for unsupported protocol 0x%x\n", prot));
}
/*
* lcp_protrej - A Protocol-Reject was received.
*/
static void
lcp_protrej(int unit)
{
LWIP_UNUSED_ARG(unit);
/*
* Can't reject LCP!
*/
LCPDEBUG((LOG_WARNING, "lcp_protrej: Received Protocol-Reject for LCP!\n"));
fsm_protreject(&lcp_fsm[unit]);
}
/*
* lcp_resetci - Reset our CI.
*/
static void
lcp_resetci(fsm *f)
{
lcp_wantoptions[f->unit].magicnumber = magic();
lcp_wantoptions[f->unit].numloops = 0;
lcp_gotoptions[f->unit] = lcp_wantoptions[f->unit];
peer_mru[f->unit] = PPP_MRU;
auth_reset(f->unit);
}
/*
* lcp_cilen - Return length of our CI.
*/
static int lcp_cilen(fsm *f)
{
lcp_options *go = &lcp_gotoptions[f->unit];
#define LENCIVOID(neg) ((neg) ? CILEN_VOID : 0)
#define LENCICHAP(neg) ((neg) ? CILEN_CHAP : 0)
#define LENCISHORT(neg) ((neg) ? CILEN_SHORT : 0)
#define LENCILONG(neg) ((neg) ? CILEN_LONG : 0)
#define LENCILQR(neg) ((neg) ? CILEN_LQR: 0)
#define LENCICBCP(neg) ((neg) ? CILEN_CBCP: 0)
/*
* NB: we only ask for one of CHAP and UPAP, even if we will
* accept either.
*/
return (LENCISHORT(go->neg_mru && go->mru != PPP_DEFMRU) +
LENCILONG(go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl) +
LENCICHAP(go->neg_chap) +
LENCISHORT(!go->neg_chap && go->neg_upap) +
LENCILQR(go->neg_lqr) +
LENCICBCP(go->neg_cbcp) +
LENCILONG(go->neg_magicnumber) +
LENCIVOID(go->neg_pcompression) +
LENCIVOID(go->neg_accompression));
}
/*
* lcp_addci - Add our desired CIs to a packet.
*/
static void
lcp_addci(fsm *f, u_char *ucp, int *lenp)
{
lcp_options *go = &lcp_gotoptions[f->unit];
u_char *start_ucp = ucp;
#define ADDCIVOID(opt, neg) \
if (neg) { \
LCPDEBUG((LOG_INFO, "lcp_addci: opt=%d\n", opt)); \
PUTCHAR(opt, ucp); \
PUTCHAR(CILEN_VOID, ucp); \
}
#define ADDCISHORT(opt, neg, val) \
if (neg) { \
LCPDEBUG((LOG_INFO, "lcp_addci: INT opt=%d %X\n", opt, val)); \
PUTCHAR(opt, ucp); \
PUTCHAR(CILEN_SHORT, ucp); \
PUTSHORT(val, ucp); \
}
#define ADDCICHAP(opt, neg, val, digest) \
if (neg) { \
LCPDEBUG((LOG_INFO, "lcp_addci: CHAP opt=%d %X\n", opt, val)); \
PUTCHAR(opt, ucp); \
PUTCHAR(CILEN_CHAP, ucp); \
PUTSHORT(val, ucp); \
PUTCHAR(digest, ucp); \
}
#define ADDCILONG(opt, neg, val) \
if (neg) { \
LCPDEBUG((LOG_INFO, "lcp_addci: L opt=%d %lX\n", opt, val)); \
PUTCHAR(opt, ucp); \
PUTCHAR(CILEN_LONG, ucp); \
PUTLONG(val, ucp); \
}
#define ADDCILQR(opt, neg, val) \
if (neg) { \
LCPDEBUG((LOG_INFO, "lcp_addci: LQR opt=%d %lX\n", opt, val)); \
PUTCHAR(opt, ucp); \
PUTCHAR(CILEN_LQR, ucp); \
PUTSHORT(PPP_LQR, ucp); \
PUTLONG(val, ucp); \
}
#define ADDCICHAR(opt, neg, val) \
if (neg) { \
LCPDEBUG((LOG_INFO, "lcp_addci: CHAR opt=%d %X '%z'\n", opt, val, val)); \
PUTCHAR(opt, ucp); \
PUTCHAR(CILEN_CHAR, ucp); \
PUTCHAR(val, ucp); \
}
ADDCISHORT(CI_MRU, go->neg_mru && go->mru != PPP_DEFMRU, go->mru);
ADDCILONG(CI_ASYNCMAP, go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl, go->asyncmap);
ADDCICHAP(CI_AUTHTYPE, go->neg_chap, PPP_CHAP, go->chap_mdtype);
ADDCISHORT(CI_AUTHTYPE, !go->neg_chap && go->neg_upap, PPP_PAP);
ADDCILQR(CI_QUALITY, go->neg_lqr, go->lqr_period);
ADDCICHAR(CI_CALLBACK, go->neg_cbcp, CBCP_OPT);
ADDCILONG(CI_MAGICNUMBER, go->neg_magicnumber, go->magicnumber);
ADDCIVOID(CI_PCOMPRESSION, go->neg_pcompression);
ADDCIVOID(CI_ACCOMPRESSION, go->neg_accompression);
if (ucp - start_ucp != *lenp) {
/* this should never happen, because peer_mtu should be 1500 */
LCPDEBUG((LOG_ERR, "Bug in lcp_addci: wrong length\n"));
}
}
/*
* lcp_ackci - Ack our CIs.
* This should not modify any state if the Ack is bad.
*
* Returns:
* 0 - Ack was bad.
* 1 - Ack was good.
*/
static int
lcp_ackci(fsm *f, u_char *p, int len)
{
lcp_options *go = &lcp_gotoptions[f->unit];
u_char cilen, citype, cichar;
u_short cishort;
u32_t cilong;
/*
* CIs must be in exactly the same order that we sent.
* Check packet length and CI length at each step.
* If we find any deviations, then this packet is bad.
*/
#define ACKCIVOID(opt, neg) \
if (neg) { \
if ((len -= CILEN_VOID) < 0) \
goto bad; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_VOID || citype != opt) \
goto bad; \
}
#define ACKCISHORT(opt, neg, val) \
if (neg) { \
if ((len -= CILEN_SHORT) < 0) \
goto bad; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_SHORT || citype != opt) \
goto bad; \
GETSHORT(cishort, p); \
if (cishort != val) \
goto bad; \
}
#define ACKCICHAR(opt, neg, val) \
if (neg) { \
if ((len -= CILEN_CHAR) < 0) \
goto bad; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_CHAR || citype != opt) \
goto bad; \
GETCHAR(cichar, p); \
if (cichar != val) \
goto bad; \
}
#define ACKCICHAP(opt, neg, val, digest) \
if (neg) { \
if ((len -= CILEN_CHAP) < 0) \
goto bad; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_CHAP || citype != opt) \
goto bad; \
GETSHORT(cishort, p); \
if (cishort != val) \
goto bad; \
GETCHAR(cichar, p); \
if (cichar != digest) \
goto bad; \
}
#define ACKCILONG(opt, neg, val) \
if (neg) { \
if ((len -= CILEN_LONG) < 0) \
goto bad; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_LONG || citype != opt) \
goto bad; \
GETLONG(cilong, p); \
if (cilong != val) \
goto bad; \
}
#define ACKCILQR(opt, neg, val) \
if (neg) { \
if ((len -= CILEN_LQR) < 0) \
goto bad; \
GETCHAR(citype, p); \
GETCHAR(cilen, p); \
if (cilen != CILEN_LQR || citype != opt) \
goto bad; \
GETSHORT(cishort, p); \
if (cishort != PPP_LQR) \
goto bad; \
GETLONG(cilong, p); \
if (cilong != val) \
goto bad; \
}
ACKCISHORT(CI_MRU, go->neg_mru && go->mru != PPP_DEFMRU, go->mru);
ACKCILONG(CI_ASYNCMAP, go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl, go->asyncmap);
ACKCICHAP(CI_AUTHTYPE, go->neg_chap, PPP_CHAP, go->chap_mdtype);
ACKCISHORT(CI_AUTHTYPE, !go->neg_chap && go->neg_upap, PPP_PAP);
ACKCILQR(CI_QUALITY, go->neg_lqr, go->lqr_period);
ACKCICHAR(CI_CALLBACK, go->neg_cbcp, CBCP_OPT);
ACKCILONG(CI_MAGICNUMBER, go->neg_magicnumber, go->magicnumber);
ACKCIVOID(CI_PCOMPRESSION, go->neg_pcompression);
ACKCIVOID(CI_ACCOMPRESSION, go->neg_accompression);
/*
* If there are any remaining CIs, then this packet is bad.
*/
if (len != 0) {
goto bad;
}
LCPDEBUG((LOG_INFO, "lcp_acki: Ack\n"));
return (1);
bad:
LCPDEBUG((LOG_WARNING, "lcp_acki: received bad Ack!\n"));
return (0);
}
/*
* lcp_nakci - Peer has sent a NAK for some of our CIs.
* This should not modify any state if the Nak is bad
* or if LCP is in the LS_OPENED state.
*
* Returns:
* 0 - Nak was bad.
* 1 - Nak was good.
*/
static int
lcp_nakci(fsm *f, u_char *p, int len)
{
lcp_options *go = &lcp_gotoptions[f->unit];
lcp_options *wo = &lcp_wantoptions[f->unit];
u_char citype, cichar, *next;
u_short cishort;
u32_t cilong;
lcp_options no; /* options we've seen Naks for */
lcp_options try; /* options to request next time */
int looped_back = 0;
int cilen;
BZERO(&no, sizeof(no));
try = *go;
/*
* Any Nak'd CIs must be in exactly the same order that we sent.
* Check packet length and CI length at each step.
* If we find any deviations, then this packet is bad.
*/
#define NAKCIVOID(opt, neg, code) \
if (go->neg && \
len >= CILEN_VOID && \
p[1] == CILEN_VOID && \
p[0] == opt) { \
len -= CILEN_VOID; \
INCPTR(CILEN_VOID, p); \
no.neg = 1; \
code \
}
#define NAKCICHAP(opt, neg, code) \
if (go->neg && \
len >= CILEN_CHAP && \
p[1] == CILEN_CHAP && \
p[0] == opt) { \
len -= CILEN_CHAP; \
INCPTR(2, p); \
GETSHORT(cishort, p); \
GETCHAR(cichar, p); \
no.neg = 1; \
code \
}
#define NAKCICHAR(opt, neg, code) \
if (go->neg && \
len >= CILEN_CHAR && \
p[1] == CILEN_CHAR && \
p[0] == opt) { \
len -= CILEN_CHAR; \
INCPTR(2, p); \
GETCHAR(cichar, p); \
no.neg = 1; \
code \
}
#define NAKCISHORT(opt, neg, code) \
if (go->neg && \
len >= CILEN_SHORT && \
p[1] == CILEN_SHORT && \
p[0] == opt) { \
len -= CILEN_SHORT; \
INCPTR(2, p); \
GETSHORT(cishort, p); \
no.neg = 1; \
code \
}
#define NAKCILONG(opt, neg, code) \
if (go->neg && \
len >= CILEN_LONG && \
p[1] == CILEN_LONG && \
p[0] == opt) { \
len -= CILEN_LONG; \
INCPTR(2, p); \
GETLONG(cilong, p); \
no.neg = 1; \
code \
}
#define NAKCILQR(opt, neg, code) \
if (go->neg && \
len >= CILEN_LQR && \
p[1] == CILEN_LQR && \
p[0] == opt) { \
len -= CILEN_LQR; \
INCPTR(2, p); \
GETSHORT(cishort, p); \
GETLONG(cilong, p); \
no.neg = 1; \
code \
}
/*
* We don't care if they want to send us smaller packets than
* we want. Therefore, accept any MRU less than what we asked for,
* but then ignore the new value when setting the MRU in the kernel.
* If they send us a bigger MRU than what we asked, accept it, up to
* the limit of the default MRU we'd get if we didn't negotiate.
*/
if (go->neg_mru && go->mru != PPP_DEFMRU) {
NAKCISHORT(CI_MRU, neg_mru,
if (cishort <= wo->mru || cishort < PPP_DEFMRU) {
try.mru = cishort;
}
);
}
/*
* Add any characters they want to our (receive-side) asyncmap.
*/
if (go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl) {
NAKCILONG(CI_ASYNCMAP, neg_asyncmap,
try.asyncmap = go->asyncmap | cilong;
);
}
/*
* If they've nak'd our authentication-protocol, check whether
* they are proposing a different protocol, or a different
* hash algorithm for CHAP.
*/
if ((go->neg_chap || go->neg_upap)
&& len >= CILEN_SHORT
&& p[0] == CI_AUTHTYPE && p[1] >= CILEN_SHORT && p[1] <= len) {
cilen = p[1];
len -= cilen;
no.neg_chap = go->neg_chap;
no.neg_upap = go->neg_upap;
INCPTR(2, p);
GETSHORT(cishort, p);
if (cishort == PPP_PAP && cilen == CILEN_SHORT) {
/*
* If we were asking for CHAP, they obviously don't want to do it.
* If we weren't asking for CHAP, then we were asking for PAP,
* in which case this Nak is bad.
*/
if (!go->neg_chap) {
goto bad;
}
try.neg_chap = 0;
} else if (cishort == PPP_CHAP && cilen == CILEN_CHAP) {
GETCHAR(cichar, p);
if (go->neg_chap) {
/*
* We were asking for CHAP/MD5; they must want a different
* algorithm. If they can't do MD5, we'll have to stop
* asking for CHAP.
*/
if (cichar != go->chap_mdtype) {
try.neg_chap = 0;
}
} else {
/*
* Stop asking for PAP if we were asking for it.
*/
try.neg_upap = 0;
}
} else {
/*
* We don't recognize what they're suggesting.
* Stop asking for what we were asking for.
*/
if (go->neg_chap) {
try.neg_chap = 0;
} else {
try.neg_upap = 0;
}
p += cilen - CILEN_SHORT;
}
}
/*
* If they can't cope with our link quality protocol, we'll have
* to stop asking for LQR. We haven't got any other protocol.
* If they Nak the reporting period, take their value XXX ?
*/
NAKCILQR(CI_QUALITY, neg_lqr,
if (cishort != PPP_LQR) {
try.neg_lqr = 0;
} else {
try.lqr_period = cilong;
}
);
/*
* Only implementing CBCP...not the rest of the callback options
*/
NAKCICHAR(CI_CALLBACK, neg_cbcp,
try.neg_cbcp = 0;
);
/*
* Check for a looped-back line.
*/
NAKCILONG(CI_MAGICNUMBER, neg_magicnumber,
try.magicnumber = magic();
looped_back = 1;
);
/*
* Peer shouldn't send Nak for protocol compression or
* address/control compression requests; they should send
* a Reject instead. If they send a Nak, treat it as a Reject.
*/
NAKCIVOID(CI_PCOMPRESSION, neg_pcompression,
try.neg_pcompression = 0;
);
NAKCIVOID(CI_ACCOMPRESSION, neg_accompression,
try.neg_accompression = 0;
);
/*
* There may be remaining CIs, if the peer is requesting negotiation
* on an option that we didn't include in our request packet.
* If we see an option that we requested, or one we've already seen
* in this packet, then this packet is bad.
* If we wanted to respond by starting to negotiate on the requested
* option(s), we could, but we don't, because except for the
* authentication type and quality protocol, if we are not negotiating
* an option, it is because we were told not to.
* For the authentication type, the Nak from the peer means
* `let me authenticate myself with you' which is a bit pointless.
* For the quality protocol, the Nak means `ask me to send you quality
* reports', but if we didn't ask for them, we don't want them.
* An option we don't recognize represents the peer asking to
* negotiate some option we don't support, so ignore it.
*/
while (len > CILEN_VOID) {
GETCHAR(citype, p);
GETCHAR(cilen, p);
if (cilen < CILEN_VOID || (len -= cilen) < 0) {
goto bad;
}
next = p + cilen - 2;
switch (citype) {
case CI_MRU:
if ((go->neg_mru && go->mru != PPP_DEFMRU)
|| no.neg_mru || cilen != CILEN_SHORT) {
goto bad;
}
GETSHORT(cishort, p);
if (cishort < PPP_DEFMRU) {
try.mru = cishort;
}
break;
case CI_ASYNCMAP:
if ((go->neg_asyncmap && go->asyncmap != 0xFFFFFFFFl)
|| no.neg_asyncmap || cilen != CILEN_LONG) {
goto bad;
}
break;
case CI_AUTHTYPE:
if (go->neg_chap || no.neg_chap || go->neg_upap || no.neg_upap) {
goto bad;
}
break;
case CI_MAGICNUMBER:
if (go->neg_magicnumber || no.neg_magicnumber ||
cilen != CILEN_LONG) {
goto bad;
}
break;
case CI_PCOMPRESSION:
if (go->neg_pcompression || no.neg_pcompression
|| cilen != CILEN_VOID) {
goto bad;
}
break;
case CI_ACCOMPRESSION:
if (go->neg_accompression || no.neg_accompression
|| cilen != CILEN_VOID) {
goto bad;
}
break;
case CI_QUALITY:
if (go->neg_lqr || no.neg_lqr || cilen != CILEN_LQR) {
goto bad;
}
break;
}
p = next;
}
/* If there is still anything left, this packet is bad. */
if (len != 0) {
goto bad;
}
/*
* OK, the Nak is good. Now we can update state.
*/
if (f->state != LS_OPENED) {
if (looped_back) {
if (++try.numloops >= lcp_loopbackfail) {
LCPDEBUG((LOG_NOTICE, "Serial line is looped back.\n"));
lcp_close(f->unit, "Loopback detected");
}
} else {
try.numloops = 0;
}
*go = try;
}
return 1;
bad:
LCPDEBUG((LOG_WARNING, "lcp_nakci: received bad Nak!\n"));
return 0;
}
/*
* lcp_rejci - Peer has Rejected some of our CIs.
* This should not modify any state if the Reject is bad
* or if LCP is in the LS_OPENED state.
*
* Returns:
* 0 - Reject was bad.
* 1 - Reject was good.
*/
static int
lcp_rejci(fsm *f, u_char *p, int len)
{
lcp_options *go = &lcp_gotoptions[f->unit];
u_char cichar;
u_short cishort;
u32_t cilong;
lcp_options try; /* options to request next time */
try = *go;
/*
* Any Rejected CIs must be in exactly the same order that we sent.
* Check packet length and CI length at each step.
* If we find any deviations, then this packet is bad.
*/
#define REJCIVOID(opt, neg) \
if (go->neg && \
len >= CILEN_VOID && \
p[1] == CILEN_VOID && \
p[0] == opt) { \
len -= CILEN_VOID; \
INCPTR(CILEN_VOID, p); \
try.neg = 0; \
LCPDEBUG((LOG_INFO, "lcp_rejci: void opt %d rejected\n", opt)); \
}
#define REJCISHORT(opt, neg, val) \
if (go->neg && \
len >= CILEN_SHORT && \
p[1] == CILEN_SHORT && \
p[0] == opt) { \
len -= CILEN_SHORT; \
INCPTR(2, p); \
GETSHORT(cishort, p); \
/* Check rejected value. */ \
if (cishort != val) { \
goto bad; \
} \
try.neg = 0; \
LCPDEBUG((LOG_INFO,"lcp_rejci: short opt %d rejected\n", opt)); \
}
#define REJCICHAP(opt, neg, val, digest) \
if (go->neg && \
len >= CILEN_CHAP && \
p[1] == CILEN_CHAP && \
p[0] == opt) { \
len -= CILEN_CHAP; \
INCPTR(2, p); \
GETSHORT(cishort, p); \
GETCHAR(cichar, p); \
/* Check rejected value. */ \
if (cishort != val || cichar != digest) { \
goto bad; \
} \
try.neg = 0; \
try.neg_upap = 0; \
LCPDEBUG((LOG_INFO,"lcp_rejci: chap opt %d rejected\n", opt)); \
}
#define REJCILONG(opt, neg, val) \
if (go->neg && \
len >= CILEN_LONG && \
p[1] == CILEN_LONG && \
p[0] == opt) { \
len -= CILEN_LONG; \
INCPTR(2, p); \
GETLONG(cilong, p); \
/* Check rejected value. */ \
if (cilong != val) { \
goto bad; \
} \
try.neg = 0; \
LCPDEBUG((LOG_INFO,"lcp_rejci: long opt %d rejected\n", opt)); \
}
#define REJCILQR(opt, neg, val) \
if (go->neg && \
len >= CILEN_LQR && \
p[1] == CILEN_LQR && \
p[0] == opt) { \
len -= CILEN_LQR; \
INCPTR(2, p); \
GETSHORT(cishort, p); \
GETLONG(cilong, p); \
/* Check rejected value. */ \
if (cishort != PPP_LQR || cilong != val) { \
goto bad; \
} \
try.neg = 0; \
LCPDEBUG((LOG_INFO,"lcp_rejci: LQR opt %d rejected\n", opt)); \
}
#define REJCICBCP(opt, neg, val) \
if (go->neg && \
len >= CILEN_CBCP && \
p[1] == CILEN_CBCP && \
p[0] == opt) { \
len -= CILEN_CBCP; \
INCPTR(2, p); \
GETCHAR(cichar, p); \
/* Check rejected value. */ \
if (cichar != val) { \
goto bad; \
} \
try.neg = 0; \
LCPDEBUG((LOG_INFO,"lcp_rejci: Callback opt %d rejected\n", opt)); \
}
REJCISHORT(CI_MRU, neg_mru, go->mru);
REJCILONG(CI_ASYNCMAP, neg_asyncmap, go->asyncmap);
REJCICHAP(CI_AUTHTYPE, neg_chap, PPP_CHAP, go->chap_mdtype);
if (!go->neg_chap) {
REJCISHORT(CI_AUTHTYPE, neg_upap, PPP_PAP);
}
REJCILQR(CI_QUALITY, neg_lqr, go->lqr_period);
REJCICBCP(CI_CALLBACK, neg_cbcp, CBCP_OPT);
REJCILONG(CI_MAGICNUMBER, neg_magicnumber, go->magicnumber);
REJCIVOID(CI_PCOMPRESSION, neg_pcompression);
REJCIVOID(CI_ACCOMPRESSION, neg_accompression);
/*
* If there are any remaining CIs, then this packet is bad.
*/
if (len != 0) {
goto bad;
}
/*
* Now we can update state.
*/
if (f->state != LS_OPENED) {
*go = try;
}
return 1;
bad:
LCPDEBUG((LOG_WARNING, "lcp_rejci: received bad Reject!\n"));
return 0;
}
/*
* lcp_reqci - Check the peer's requested CIs and send appropriate response.
*
* Returns: CONFACK, CONFNAK or CONFREJ and input packet modified
* appropriately. If reject_if_disagree is non-zero, doesn't return
* CONFNAK; returns CONFREJ if it can't return CONFACK.
*/
static int
lcp_reqci(fsm *f,
u_char *inp, /* Requested CIs */
int *lenp, /* Length of requested CIs */
int reject_if_disagree)
{
lcp_options *go = &lcp_gotoptions[f->unit];
lcp_options *ho = &lcp_hisoptions[f->unit];
lcp_options *ao = &lcp_allowoptions[f->unit];
u_char *cip, *next; /* Pointer to current and next CIs */
int cilen, citype, cichar; /* Parsed len, type, char value */
u_short cishort; /* Parsed short value */
u32_t cilong; /* Parse long value */
int rc = CONFACK; /* Final packet return code */
int orc; /* Individual option return code */
u_char *p; /* Pointer to next char to parse */
u_char *rejp; /* Pointer to next char in reject frame */
u_char *nakp; /* Pointer to next char in Nak frame */
int l = *lenp; /* Length left */
#if TRACELCP > 0
char traceBuf[80];
int traceNdx = 0;
#endif
/*
* Reset all his options.
*/
BZERO(ho, sizeof(*ho));
/*
* Process all his options.
*/
next = inp;
nakp = nak_buffer;
rejp = inp;
while (l) {
orc = CONFACK; /* Assume success */
cip = p = next; /* Remember begining of CI */
if (l < 2 || /* Not enough data for CI header or */
p[1] < 2 || /* CI length too small or */
p[1] > l) { /* CI length too big? */
LCPDEBUG((LOG_WARNING, "lcp_reqci: bad CI length!\n"));
orc = CONFREJ; /* Reject bad CI */
cilen = l; /* Reject till end of packet */
l = 0; /* Don't loop again */
citype = 0;
goto endswitch;
}
GETCHAR(citype, p); /* Parse CI type */
GETCHAR(cilen, p); /* Parse CI length */
l -= cilen; /* Adjust remaining length */
next += cilen; /* Step to next CI */
switch (citype) { /* Check CI type */
case CI_MRU:
if (!ao->neg_mru) { /* Allow option? */
LCPDEBUG((LOG_INFO, "lcp_reqci: Reject MRU - not allowed\n"));
orc = CONFREJ; /* Reject CI */
break;
} else if (cilen != CILEN_SHORT) { /* Check CI length */
LCPDEBUG((LOG_INFO, "lcp_reqci: Reject MRU - bad length\n"));
orc = CONFREJ; /* Reject CI */
break;
}
GETSHORT(cishort, p); /* Parse MRU */
/*
* He must be able to receive at least our minimum.
* No need to check a maximum. If he sends a large number,
* we'll just ignore it.
*/
if (cishort < PPP_MINMRU) {
LCPDEBUG((LOG_INFO, "lcp_reqci: Nak - MRU too small\n"));
orc = CONFNAK; /* Nak CI */
PUTCHAR(CI_MRU, nakp);
PUTCHAR(CILEN_SHORT, nakp);
PUTSHORT(PPP_MINMRU, nakp); /* Give him a hint */
break;
}
ho->neg_mru = 1; /* Remember he sent MRU */
ho->mru = cishort; /* And remember value */
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " MRU %d", cishort);
traceNdx = strlen(traceBuf);
#endif
break;
case CI_ASYNCMAP:
if (!ao->neg_asyncmap) {
LCPDEBUG((LOG_INFO, "lcp_reqci: Reject ASYNCMAP not allowed\n"));
orc = CONFREJ;
break;
} else if (cilen != CILEN_LONG) {
LCPDEBUG((LOG_INFO, "lcp_reqci: Reject ASYNCMAP bad length\n"));
orc = CONFREJ;
break;
}
GETLONG(cilong, p);
/*
* Asyncmap must have set at least the bits
* which are set in lcp_allowoptions[unit].asyncmap.
*/
if ((ao->asyncmap & ~cilong) != 0) {
LCPDEBUG((LOG_INFO, "lcp_reqci: Nak ASYNCMAP %lX missing %lX\n",
cilong, ao->asyncmap));
orc = CONFNAK;
PUTCHAR(CI_ASYNCMAP, nakp);
PUTCHAR(CILEN_LONG, nakp);
PUTLONG(ao->asyncmap | cilong, nakp);
break;
}
ho->neg_asyncmap = 1;
ho->asyncmap = cilong;
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " ASYNCMAP=%lX", cilong);
traceNdx = strlen(traceBuf);
#endif
break;
case CI_AUTHTYPE:
if (cilen < CILEN_SHORT) {
LCPDEBUG((LOG_INFO, "lcp_reqci: Reject AUTHTYPE missing arg\n"));
orc = CONFREJ;
break;
} else if (!(ao->neg_upap || ao->neg_chap)) {
/*
* Reject the option if we're not willing to authenticate.
*/
LCPDEBUG((LOG_INFO, "lcp_reqci: Reject AUTHTYPE not allowed\n"));
orc = CONFREJ;
break;
}
GETSHORT(cishort, p);
/*
* Authtype must be UPAP or CHAP.
*
* Note: if both ao->neg_upap and ao->neg_chap are set,
* and the peer sends a Configure-Request with two
* authenticate-protocol requests, one for CHAP and one
* for UPAP, then we will reject the second request.
* Whether we end up doing CHAP or UPAP depends then on
* the ordering of the CIs in the peer's Configure-Request.
*/
if (cishort == PPP_PAP) {
if (ho->neg_chap) { /* we've already accepted CHAP */
LCPDEBUG((LOG_WARNING, "lcp_reqci: Reject AUTHTYPE PAP already accepted\n"));
orc = CONFREJ;
break;
} else if (cilen != CILEN_SHORT) {
LCPDEBUG((LOG_WARNING, "lcp_reqci: Reject AUTHTYPE PAP bad len\n"));
orc = CONFREJ;
break;
}
if (!ao->neg_upap) { /* we don't want to do PAP */
LCPDEBUG((LOG_WARNING, "lcp_reqci: Nak AUTHTYPE PAP not allowed\n"));
orc = CONFNAK; /* NAK it and suggest CHAP */
PUTCHAR(CI_AUTHTYPE, nakp);
PUTCHAR(CILEN_CHAP, nakp);
PUTSHORT(PPP_CHAP, nakp);
PUTCHAR(ao->chap_mdtype, nakp);
break;
}
ho->neg_upap = 1;
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " PAP (%X)", cishort);
traceNdx = strlen(traceBuf);
#endif
break;
}
if (cishort == PPP_CHAP) {
if (ho->neg_upap) { /* we've already accepted PAP */
LCPDEBUG((LOG_WARNING, "lcp_reqci: Reject AUTHTYPE CHAP accepted PAP\n"));
orc = CONFREJ;
break;
} else if (cilen != CILEN_CHAP) {
LCPDEBUG((LOG_WARNING, "lcp_reqci: Reject AUTHTYPE CHAP bad len\n"));
orc = CONFREJ;
break;
}
if (!ao->neg_chap) { /* we don't want to do CHAP */
LCPDEBUG((LOG_WARNING, "lcp_reqci: Nak AUTHTYPE CHAP not allowed\n"));
orc = CONFNAK; /* NAK it and suggest PAP */
PUTCHAR(CI_AUTHTYPE, nakp);
PUTCHAR(CILEN_SHORT, nakp);
PUTSHORT(PPP_PAP, nakp);
break;
}
GETCHAR(cichar, p); /* get digest type*/
if (cichar != CHAP_DIGEST_MD5
#ifdef CHAPMS
&& cichar != CHAP_MICROSOFT
#endif
) {
LCPDEBUG((LOG_WARNING, "lcp_reqci: Nak AUTHTYPE CHAP digest=%d\n", cichar));
orc = CONFNAK;
PUTCHAR(CI_AUTHTYPE, nakp);
PUTCHAR(CILEN_CHAP, nakp);
PUTSHORT(PPP_CHAP, nakp);
PUTCHAR(ao->chap_mdtype, nakp);
break;
}
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " CHAP %X,%d", cishort, cichar);
traceNdx = strlen(traceBuf);
#endif
ho->chap_mdtype = cichar; /* save md type */
ho->neg_chap = 1;
break;
}
/*
* We don't recognize the protocol they're asking for.
* Nak it with something we're willing to do.
* (At this point we know ao->neg_upap || ao->neg_chap.)
*/
orc = CONFNAK;
PUTCHAR(CI_AUTHTYPE, nakp);
if (ao->neg_chap) {
LCPDEBUG((LOG_WARNING, "lcp_reqci: Nak AUTHTYPE %d req CHAP\n", cishort));
PUTCHAR(CILEN_CHAP, nakp);
PUTSHORT(PPP_CHAP, nakp);
PUTCHAR(ao->chap_mdtype, nakp);
} else {
LCPDEBUG((LOG_WARNING, "lcp_reqci: Nak AUTHTYPE %d req PAP\n", cishort));
PUTCHAR(CILEN_SHORT, nakp);
PUTSHORT(PPP_PAP, nakp);
}
break;
case CI_QUALITY:
GETSHORT(cishort, p);
GETLONG(cilong, p);
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " QUALITY (%x %x)", cishort, (unsigned int) cilong);
traceNdx = strlen(traceBuf);
#endif
if (!ao->neg_lqr ||
cilen != CILEN_LQR) {
orc = CONFREJ;
break;
}
/*
* Check the protocol and the reporting period.
* XXX When should we Nak this, and what with?
*/
if (cishort != PPP_LQR) {
orc = CONFNAK;
PUTCHAR(CI_QUALITY, nakp);
PUTCHAR(CILEN_LQR, nakp);
PUTSHORT(PPP_LQR, nakp);
PUTLONG(ao->lqr_period, nakp);
break;
}
break;
case CI_MAGICNUMBER:
if (!(ao->neg_magicnumber || go->neg_magicnumber) ||
cilen != CILEN_LONG) {
orc = CONFREJ;
break;
}
GETLONG(cilong, p);
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " MAGICNUMBER (%lX)", cilong);
traceNdx = strlen(traceBuf);
#endif
/*
* He must have a different magic number.
*/
if (go->neg_magicnumber &&
cilong == go->magicnumber) {
cilong = magic(); /* Don't put magic() inside macro! */
orc = CONFNAK;
PUTCHAR(CI_MAGICNUMBER, nakp);
PUTCHAR(CILEN_LONG, nakp);
PUTLONG(cilong, nakp);
break;
}
ho->neg_magicnumber = 1;
ho->magicnumber = cilong;
break;
case CI_PCOMPRESSION:
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " PCOMPRESSION");
traceNdx = strlen(traceBuf);
#endif
if (!ao->neg_pcompression ||
cilen != CILEN_VOID) {
orc = CONFREJ;
break;
}
ho->neg_pcompression = 1;
break;
case CI_ACCOMPRESSION:
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " ACCOMPRESSION");
traceNdx = strlen(traceBuf);
#endif
if (!ao->neg_accompression ||
cilen != CILEN_VOID) {
orc = CONFREJ;
break;
}
ho->neg_accompression = 1;
break;
case CI_MRRU:
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " CI_MRRU");
traceNdx = strlen(traceBuf);
#endif
orc = CONFREJ;
break;
case CI_SSNHF:
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " CI_SSNHF");
traceNdx = strlen(traceBuf);
#endif
orc = CONFREJ;
break;
case CI_EPDISC:
#if TRACELCP > 0
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " CI_EPDISC");
traceNdx = strlen(traceBuf);
#endif
orc = CONFREJ;
break;
default:
#if TRACELCP
snprintf(&traceBuf[traceNdx], sizeof(traceBuf), " unknown %d", citype);
traceNdx = strlen(traceBuf);
#endif
orc = CONFREJ;
break;
}
endswitch:
#if TRACELCP
if (traceNdx >= 80 - 32) {
LCPDEBUG((LOG_INFO, "lcp_reqci: rcvd%s\n", traceBuf));
traceNdx = 0;
}
#endif
if (orc == CONFACK && /* Good CI */
rc != CONFACK) { /* but prior CI wasnt? */
continue; /* Don't send this one */
}
if (orc == CONFNAK) { /* Nak this CI? */
if (reject_if_disagree /* Getting fed up with sending NAKs? */
&& citype != CI_MAGICNUMBER) {
orc = CONFREJ; /* Get tough if so */
} else {
if (rc == CONFREJ) { /* Rejecting prior CI? */
continue; /* Don't send this one */
}
rc = CONFNAK;
}
}
if (orc == CONFREJ) { /* Reject this CI */
rc = CONFREJ;
if (cip != rejp) { /* Need to move rejected CI? */
BCOPY(cip, rejp, cilen); /* Move it */
}
INCPTR(cilen, rejp); /* Update output pointer */
}
}
/*
* If we wanted to send additional NAKs (for unsent CIs), the
* code would go here. The extra NAKs would go at *nakp.
* At present there are no cases where we want to ask the
* peer to negotiate an option.
*/
switch (rc) {
case CONFACK:
*lenp = (int)(next - inp);
break;
case CONFNAK:
/*
* Copy the Nak'd options from the nak_buffer to the caller's buffer.
*/
*lenp = (int)(nakp - nak_buffer);
BCOPY(nak_buffer, inp, *lenp);
break;
case CONFREJ:
*lenp = (int)(rejp - inp);
break;
}
#if TRACELCP > 0
if (traceNdx > 0) {
LCPDEBUG((LOG_INFO, "lcp_reqci: %s\n", traceBuf));
}
#endif
LCPDEBUG((LOG_INFO, "lcp_reqci: returning CONF%s.\n", CODENAME(rc)));
return (rc); /* Return final code */
}
/*
* lcp_up - LCP has come UP.
*/
static void
lcp_up(fsm *f)
{
lcp_options *wo = &lcp_wantoptions[f->unit];
lcp_options *ho = &lcp_hisoptions[f->unit];
lcp_options *go = &lcp_gotoptions[f->unit];
lcp_options *ao = &lcp_allowoptions[f->unit];
if (!go->neg_magicnumber) {
go->magicnumber = 0;
}
if (!ho->neg_magicnumber) {
ho->magicnumber = 0;
}
/*
* Set our MTU to the smaller of the MTU we wanted and
* the MRU our peer wanted. If we negotiated an MRU,
* set our MRU to the larger of value we wanted and
* the value we got in the negotiation.
*/
ppp_send_config(f->unit, LWIP_MIN(ao->mru, (ho->neg_mru? ho->mru: PPP_MRU)),
(ho->neg_asyncmap? ho->asyncmap: 0xffffffffl),
ho->neg_pcompression, ho->neg_accompression);
/*
* If the asyncmap hasn't been negotiated, we really should
* set the receive asyncmap to ffffffff, but we set it to 0
* for backwards contemptibility.
*/
ppp_recv_config(f->unit, (go->neg_mru? LWIP_MAX(wo->mru, go->mru): PPP_MRU),
(go->neg_asyncmap? go->asyncmap: 0x00000000),
go->neg_pcompression, go->neg_accompression);
if (ho->neg_mru) {
peer_mru[f->unit] = ho->mru;
}
lcp_echo_lowerup(f->unit); /* Enable echo messages */
link_established(f->unit);
}
/*
* lcp_down - LCP has gone DOWN.
*
* Alert other protocols.
*/
static void
lcp_down(fsm *f)
{
lcp_options *go = &lcp_gotoptions[f->unit];
lcp_echo_lowerdown(f->unit);
link_down(f->unit);
ppp_send_config(f->unit, PPP_MRU, 0xffffffffl, 0, 0);
ppp_recv_config(f->unit, PPP_MRU,
(go->neg_asyncmap? go->asyncmap: 0x00000000),
go->neg_pcompression, go->neg_accompression);
peer_mru[f->unit] = PPP_MRU;
}
/*
* lcp_starting - LCP needs the lower layer up.
*/
static void
lcp_starting(fsm *f)
{
link_required(f->unit);
}
/*
* lcp_finished - LCP has finished with the lower layer.
*/
static void
lcp_finished(fsm *f)
{
link_terminated(f->unit);
}
#if 0
/*
* print_string - print a readable representation of a string using
* printer.
*/
static void
print_string( char *p, int len, void (*printer) (void *, char *, ...), void *arg)
{
int c;
printer(arg, "\"");
for (; len > 0; --len) {
c = *p++;
if (' ' <= c && c <= '~') {
if (c == '\\' || c == '"') {
printer(arg, "\\");
}
printer(arg, "%c", c);
} else {
switch (c) {
case '\n':
printer(arg, "\\n");
break;
case '\r':
printer(arg, "\\r");
break;
case '\t':
printer(arg, "\\t");
break;
default:
printer(arg, "\\%.3o", c);
}
}
}
printer(arg, "\"");
}
/*
* lcp_printpkt - print the contents of an LCP packet.
*/
static char *lcp_codenames[] = {
"ConfReq", "ConfAck", "ConfNak", "ConfRej",
"TermReq", "TermAck", "CodeRej", "ProtRej",
"EchoReq", "EchoRep", "DiscReq"
};
static int
lcp_printpkt( u_char *p, int plen, void (*printer) (void *, char *, ...), void *arg)
{
int code, id, len, olen;
u_char *pstart, *optend;
u_short cishort;
u32_t cilong;
if (plen < HEADERLEN) {
return 0;
}
pstart = p;
GETCHAR(code, p);
GETCHAR(id, p);
GETSHORT(len, p);
if (len < HEADERLEN || len > plen) {
return 0;
}
if (code >= 1 && code <= sizeof(lcp_codenames) / sizeof(char *)) {
printer(arg, " %s", lcp_codenames[code-1]);
} else {
printer(arg, " code=0x%x", code);
}
printer(arg, " id=0x%x", id);
len -= HEADERLEN;
switch (code) {
case CONFREQ:
case CONFACK:
case CONFNAK:
case CONFREJ:
/* print option list */
while (len >= 2) {
GETCHAR(code, p);
GETCHAR(olen, p);
p -= 2;
if (olen < 2 || olen > len) {
break;
}
printer(arg, " <");
len -= olen;
optend = p + olen;
switch (code) {
case CI_MRU:
if (olen == CILEN_SHORT) {
p += 2;
GETSHORT(cishort, p);
printer(arg, "mru %d", cishort);
}
break;
case CI_ASYNCMAP:
if (olen == CILEN_LONG) {
p += 2;
GETLONG(cilong, p);
printer(arg, "asyncmap 0x%lx", cilong);
}
break;
case CI_AUTHTYPE:
if (olen >= CILEN_SHORT) {
p += 2;
printer(arg, "auth ");
GETSHORT(cishort, p);
switch (cishort) {
case PPP_PAP:
printer(arg, "pap");
break;
case PPP_CHAP:
printer(arg, "chap");
break;
default:
printer(arg, "0x%x", cishort);
}
}
break;
case CI_QUALITY:
if (olen >= CILEN_SHORT) {
p += 2;
printer(arg, "quality ");
GETSHORT(cishort, p);
switch (cishort) {
case PPP_LQR:
printer(arg, "lqr");
break;
default:
printer(arg, "0x%x", cishort);
}
}
break;
case CI_CALLBACK:
if (olen >= CILEN_CHAR) {
p += 2;
printer(arg, "callback ");
GETSHORT(cishort, p);
switch (cishort) {
case CBCP_OPT:
printer(arg, "CBCP");
break;
default:
printer(arg, "0x%x", cishort);
}
}
break;
case CI_MAGICNUMBER:
if (olen == CILEN_LONG) {
p += 2;
GETLONG(cilong, p);
printer(arg, "magic 0x%x", cilong);
}
break;
case CI_PCOMPRESSION:
if (olen == CILEN_VOID) {
p += 2;
printer(arg, "pcomp");
}
break;
case CI_ACCOMPRESSION:
if (olen == CILEN_VOID) {
p += 2;
printer(arg, "accomp");
}
break;
}
while (p < optend) {
GETCHAR(code, p);
printer(arg, " %.2x", code);
}
printer(arg, ">");
}
break;
case TERMACK:
case TERMREQ:
if (len > 0 && *p >= ' ' && *p < 0x7f) {
printer(arg, " ");
print_string((char*)p, len, printer, arg);
p += len;
len = 0;
}
break;
case ECHOREQ:
case ECHOREP:
case DISCREQ:
if (len >= 4) {
GETLONG(cilong, p);
printer(arg, " magic=0x%x", cilong);
p += 4;
len -= 4;
}
break;
}
/* print the rest of the bytes in the packet */
for (; len > 0; --len) {
GETCHAR(code, p);
printer(arg, " %.2x", code);
}
return (int)(p - pstart);
}
#endif
/*
* Time to shut down the link because there is nothing out there.
*/
static void
LcpLinkFailure (fsm *f)
{
if (f->state == LS_OPENED) {
LCPDEBUG((LOG_INFO, "No response to %d echo-requests\n", lcp_echos_pending));
LCPDEBUG((LOG_NOTICE, "Serial link appears to be disconnected.\n"));
lcp_close(f->unit, "Peer not responding");
}
}
/*
* Timer expired for the LCP echo requests from this process.
*/
static void
LcpEchoCheck (fsm *f)
{
LcpSendEchoRequest (f);
/*
* Start the timer for the next interval.
*/
LWIP_ASSERT("lcp_echo_timer_running == 0", lcp_echo_timer_running == 0);
TIMEOUT (LcpEchoTimeout, f, lcp_echo_interval);
lcp_echo_timer_running = 1;
}
/*
* LcpEchoTimeout - Timer expired on the LCP echo
*/
static void
LcpEchoTimeout (void *arg)
{
if (lcp_echo_timer_running != 0) {
lcp_echo_timer_running = 0;
LcpEchoCheck ((fsm *) arg);
}
}
/*
* LcpEchoReply - LCP has received a reply to the echo
*/
static void
lcp_received_echo_reply (fsm *f, int id, u_char *inp, int len)
{
u32_t magic;
LWIP_UNUSED_ARG(id);
/* Check the magic number - don't count replies from ourselves. */
if (len < 4) {
LCPDEBUG((LOG_WARNING, "lcp: received short Echo-Reply, length %d\n", len));
return;
}
GETLONG(magic, inp);
if (lcp_gotoptions[f->unit].neg_magicnumber && magic == lcp_gotoptions[f->unit].magicnumber) {
LCPDEBUG((LOG_WARNING, "appear to have received our own echo-reply!\n"));
return;
}
/* Reset the number of outstanding echo frames */
lcp_echos_pending = 0;
}
/*
* LcpSendEchoRequest - Send an echo request frame to the peer
*/
static void
LcpSendEchoRequest (fsm *f)
{
u32_t lcp_magic;
u_char pkt[4], *pktp;
/*
* Detect the failure of the peer at this point.
*/
if (lcp_echo_fails != 0) {
if (lcp_echos_pending++ >= lcp_echo_fails) {
LcpLinkFailure(f);
lcp_echos_pending = 0;
}
}
/*
* Make and send the echo request frame.
*/
if (f->state == LS_OPENED) {
lcp_magic = lcp_gotoptions[f->unit].magicnumber;
pktp = pkt;
PUTLONG(lcp_magic, pktp);
fsm_sdata(f, ECHOREQ, (u_char)(lcp_echo_number++ & 0xFF), pkt, (int)(pktp - pkt));
}
}
/*
* lcp_echo_lowerup - Start the timer for the LCP frame
*/
static void
lcp_echo_lowerup (int unit)
{
fsm *f = &lcp_fsm[unit];
/* Clear the parameters for generating echo frames */
lcp_echos_pending = 0;
lcp_echo_number = 0;
lcp_echo_timer_running = 0;
/* If a timeout interval is specified then start the timer */
if (lcp_echo_interval != 0) {
LcpEchoCheck (f);
}
}
/*
* lcp_echo_lowerdown - Stop the timer for the LCP frame
*/
static void
lcp_echo_lowerdown (int unit)
{
fsm *f = &lcp_fsm[unit];
if (lcp_echo_timer_running != 0) {
UNTIMEOUT (LcpEchoTimeout, f);
lcp_echo_timer_running = 0;
}
}
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/lcp.c | C | oos | 58,860 |
/*****************************************************************************
* pap.h - PPP Password Authentication Protocol header file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1997 Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-04 Guy Lancaster <glanca@gesn.com>, Global Election Systems Inc.
* Original derived from BSD codes.
*****************************************************************************/
/*
* upap.h - User/Password Authentication Protocol definitions.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef PAP_H
#define PAP_H
#if PAP_SUPPORT /* don't build if not configured for use in lwipopts.h */
/*************************
*** PUBLIC DEFINITIONS ***
*************************/
/*
* Packet header = Code, id, length.
*/
#define UPAP_HEADERLEN (sizeof (u_char) + sizeof (u_char) + sizeof (u_short))
/*
* UPAP codes.
*/
#define UPAP_AUTHREQ 1 /* Authenticate-Request */
#define UPAP_AUTHACK 2 /* Authenticate-Ack */
#define UPAP_AUTHNAK 3 /* Authenticate-Nak */
/*
* Client states.
*/
#define UPAPCS_INITIAL 0 /* Connection down */
#define UPAPCS_CLOSED 1 /* Connection up, haven't requested auth */
#define UPAPCS_PENDING 2 /* Connection down, have requested auth */
#define UPAPCS_AUTHREQ 3 /* We've sent an Authenticate-Request */
#define UPAPCS_OPEN 4 /* We've received an Ack */
#define UPAPCS_BADAUTH 5 /* We've received a Nak */
/*
* Server states.
*/
#define UPAPSS_INITIAL 0 /* Connection down */
#define UPAPSS_CLOSED 1 /* Connection up, haven't requested auth */
#define UPAPSS_PENDING 2 /* Connection down, have requested auth */
#define UPAPSS_LISTEN 3 /* Listening for an Authenticate */
#define UPAPSS_OPEN 4 /* We've sent an Ack */
#define UPAPSS_BADAUTH 5 /* We've sent a Nak */
/************************
*** PUBLIC DATA TYPES ***
************************/
/*
* Each interface is described by upap structure.
*/
typedef struct upap_state {
int us_unit; /* Interface unit number */
const char *us_user; /* User */
int us_userlen; /* User length */
const char *us_passwd; /* Password */
int us_passwdlen; /* Password length */
int us_clientstate; /* Client state */
int us_serverstate; /* Server state */
u_char us_id; /* Current id */
int us_timeouttime; /* Timeout (seconds) for auth-req retrans. */
int us_transmits; /* Number of auth-reqs sent */
int us_maxtransmits; /* Maximum number of auth-reqs to send */
int us_reqtimeout; /* Time to wait for auth-req from peer */
} upap_state;
/***********************
*** PUBLIC FUNCTIONS ***
***********************/
extern upap_state upap[];
void upap_setloginpasswd(int unit, const char *luser, const char *lpassword);
void upap_authwithpeer (int, char *, char *);
void upap_authpeer (int);
extern struct protent pap_protent;
#endif /* PAP_SUPPORT */
#endif /* PAP_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/pap.h | C | oos | 5,112 |
/*
* Routines to compress and uncompess tcp packets (for transmission
* over low speed serial lines.
*
* Copyright (c) 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
* Initial distribution.
*
* Modified June 1993 by Paul Mackerras, paulus@cs.anu.edu.au,
* so that the entire packet being decompressed doesn't have
* to be in contiguous memory (just the compressed header).
*
* Modified March 1998 by Guy Lancaster, glanca@gesn.com,
* for a 16 bit processor.
*/
#include "lwip/opt.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "pppdebug.h"
#include "vj.h"
#include <string.h>
#if VJ_SUPPORT
#if LINK_STATS
#define INCR(counter) ++comp->stats.counter
#else
#define INCR(counter)
#endif
#if defined(NO_CHAR_BITFIELDS)
#define getip_hl(base) ((base).ip_hl_v&0xf)
#define getth_off(base) (((base).th_x2_off&0xf0)>>4)
#else
#define getip_hl(base) ((base).ip_hl)
#define getth_off(base) ((base).th_off)
#endif
void
vj_compress_init(struct vjcompress *comp)
{
register u_int i;
register struct cstate *tstate = comp->tstate;
#if MAX_SLOTS == 0
memset((char *)comp, 0, sizeof(*comp));
#endif
comp->maxSlotIndex = MAX_SLOTS - 1;
comp->compressSlot = 0; /* Disable slot ID compression by default. */
for (i = MAX_SLOTS - 1; i > 0; --i) {
tstate[i].cs_id = i;
tstate[i].cs_next = &tstate[i - 1];
}
tstate[0].cs_next = &tstate[MAX_SLOTS - 1];
tstate[0].cs_id = 0;
comp->last_cs = &tstate[0];
comp->last_recv = 255;
comp->last_xmit = 255;
comp->flags = VJF_TOSS;
}
/* ENCODE encodes a number that is known to be non-zero. ENCODEZ
* checks for zero (since zero has to be encoded in the long, 3 byte
* form).
*/
#define ENCODE(n) { \
if ((u_short)(n) >= 256) { \
*cp++ = 0; \
cp[1] = (n); \
cp[0] = (n) >> 8; \
cp += 2; \
} else { \
*cp++ = (n); \
} \
}
#define ENCODEZ(n) { \
if ((u_short)(n) >= 256 || (u_short)(n) == 0) { \
*cp++ = 0; \
cp[1] = (n); \
cp[0] = (n) >> 8; \
cp += 2; \
} else { \
*cp++ = (n); \
} \
}
#define DECODEL(f) { \
if (*cp == 0) {\
u32_t tmp = ntohl(f) + ((cp[1] << 8) | cp[2]); \
(f) = htonl(tmp); \
cp += 3; \
} else { \
u32_t tmp = ntohl(f) + (u32_t)*cp++; \
(f) = htonl(tmp); \
} \
}
#define DECODES(f) { \
if (*cp == 0) {\
u_short tmp = ntohs(f) + (((u_short)cp[1] << 8) | cp[2]); \
(f) = htons(tmp); \
cp += 3; \
} else { \
u_short tmp = ntohs(f) + (u_short)*cp++; \
(f) = htons(tmp); \
} \
}
#define DECODEU(f) { \
if (*cp == 0) {\
(f) = htons(((u_short)cp[1] << 8) | cp[2]); \
cp += 3; \
} else { \
(f) = htons((u_short)*cp++); \
} \
}
/*
* vj_compress_tcp - Attempt to do Van Jacobsen header compression on a
* packet. This assumes that nb and comp are not null and that the first
* buffer of the chain contains a valid IP header.
* Return the VJ type code indicating whether or not the packet was
* compressed.
*/
u_int
vj_compress_tcp(struct vjcompress *comp, struct pbuf *pb)
{
register struct ip *ip = (struct ip *)pb->payload;
register struct cstate *cs = comp->last_cs->cs_next;
register u_short hlen = getip_hl(*ip);
register struct tcphdr *oth;
register struct tcphdr *th;
register u_short deltaS, deltaA;
register u_long deltaL;
register u_int changes = 0;
u_char new_seq[16];
register u_char *cp = new_seq;
/*
* Check that the packet is IP proto TCP.
*/
if (ip->ip_p != IPPROTO_TCP) {
return (TYPE_IP);
}
/*
* Bail if this is an IP fragment or if the TCP packet isn't
* `compressible' (i.e., ACK isn't set or some other control bit is
* set).
*/
if ((ip->ip_off & htons(0x3fff)) || pb->tot_len < 40) {
return (TYPE_IP);
}
th = (struct tcphdr *)&((long *)ip)[hlen];
if ((th->th_flags & (TCP_SYN|TCP_FIN|TCP_RST|TCP_ACK)) != TCP_ACK) {
return (TYPE_IP);
}
/*
* Packet is compressible -- we're going to send either a
* COMPRESSED_TCP or UNCOMPRESSED_TCP packet. Either way we need
* to locate (or create) the connection state. Special case the
* most recently used connection since it's most likely to be used
* again & we don't have to do any reordering if it's used.
*/
INCR(vjs_packets);
if (ip->ip_src.s_addr != cs->cs_ip.ip_src.s_addr
|| ip->ip_dst.s_addr != cs->cs_ip.ip_dst.s_addr
|| *(long *)th != ((long *)&cs->cs_ip)[getip_hl(cs->cs_ip)]) {
/*
* Wasn't the first -- search for it.
*
* States are kept in a circularly linked list with
* last_cs pointing to the end of the list. The
* list is kept in lru order by moving a state to the
* head of the list whenever it is referenced. Since
* the list is short and, empirically, the connection
* we want is almost always near the front, we locate
* states via linear search. If we don't find a state
* for the datagram, the oldest state is (re-)used.
*/
register struct cstate *lcs;
register struct cstate *lastcs = comp->last_cs;
do {
lcs = cs; cs = cs->cs_next;
INCR(vjs_searches);
if (ip->ip_src.s_addr == cs->cs_ip.ip_src.s_addr
&& ip->ip_dst.s_addr == cs->cs_ip.ip_dst.s_addr
&& *(long *)th == ((long *)&cs->cs_ip)[getip_hl(cs->cs_ip)]) {
goto found;
}
} while (cs != lastcs);
/*
* Didn't find it -- re-use oldest cstate. Send an
* uncompressed packet that tells the other side what
* connection number we're using for this conversation.
* Note that since the state list is circular, the oldest
* state points to the newest and we only need to set
* last_cs to update the lru linkage.
*/
INCR(vjs_misses);
comp->last_cs = lcs;
hlen += getth_off(*th);
hlen <<= 2;
/* Check that the IP/TCP headers are contained in the first buffer. */
if (hlen > pb->len) {
return (TYPE_IP);
}
goto uncompressed;
found:
/*
* Found it -- move to the front on the connection list.
*/
if (cs == lastcs) {
comp->last_cs = lcs;
} else {
lcs->cs_next = cs->cs_next;
cs->cs_next = lastcs->cs_next;
lastcs->cs_next = cs;
}
}
oth = (struct tcphdr *)&((long *)&cs->cs_ip)[hlen];
deltaS = hlen;
hlen += getth_off(*th);
hlen <<= 2;
/* Check that the IP/TCP headers are contained in the first buffer. */
if (hlen > pb->len) {
PPPDEBUG((LOG_INFO, "vj_compress_tcp: header len %d spans buffers\n", hlen));
return (TYPE_IP);
}
/*
* Make sure that only what we expect to change changed. The first
* line of the `if' checks the IP protocol version, header length &
* type of service. The 2nd line checks the "Don't fragment" bit.
* The 3rd line checks the time-to-live and protocol (the protocol
* check is unnecessary but costless). The 4th line checks the TCP
* header length. The 5th line checks IP options, if any. The 6th
* line checks TCP options, if any. If any of these things are
* different between the previous & current datagram, we send the
* current datagram `uncompressed'.
*/
if (((u_short *)ip)[0] != ((u_short *)&cs->cs_ip)[0]
|| ((u_short *)ip)[3] != ((u_short *)&cs->cs_ip)[3]
|| ((u_short *)ip)[4] != ((u_short *)&cs->cs_ip)[4]
|| getth_off(*th) != getth_off(*oth)
|| (deltaS > 5 && BCMP(ip + 1, &cs->cs_ip + 1, (deltaS - 5) << 2))
|| (getth_off(*th) > 5 && BCMP(th + 1, oth + 1, (getth_off(*th) - 5) << 2))) {
goto uncompressed;
}
/*
* Figure out which of the changing fields changed. The
* receiver expects changes in the order: urgent, window,
* ack, seq (the order minimizes the number of temporaries
* needed in this section of code).
*/
if (th->th_flags & TCP_URG) {
deltaS = ntohs(th->th_urp);
ENCODEZ(deltaS);
changes |= NEW_U;
} else if (th->th_urp != oth->th_urp) {
/* argh! URG not set but urp changed -- a sensible
* implementation should never do this but RFC793
* doesn't prohibit the change so we have to deal
* with it. */
goto uncompressed;
}
if ((deltaS = (u_short)(ntohs(th->th_win) - ntohs(oth->th_win))) != 0) {
ENCODE(deltaS);
changes |= NEW_W;
}
if ((deltaL = ntohl(th->th_ack) - ntohl(oth->th_ack)) != 0) {
if (deltaL > 0xffff) {
goto uncompressed;
}
deltaA = (u_short)deltaL;
ENCODE(deltaA);
changes |= NEW_A;
}
if ((deltaL = ntohl(th->th_seq) - ntohl(oth->th_seq)) != 0) {
if (deltaL > 0xffff) {
goto uncompressed;
}
deltaS = (u_short)deltaL;
ENCODE(deltaS);
changes |= NEW_S;
}
switch(changes) {
case 0:
/*
* Nothing changed. If this packet contains data and the
* last one didn't, this is probably a data packet following
* an ack (normal on an interactive connection) and we send
* it compressed. Otherwise it's probably a retransmit,
* retransmitted ack or window probe. Send it uncompressed
* in case the other side missed the compressed version.
*/
if (ip->ip_len != cs->cs_ip.ip_len &&
ntohs(cs->cs_ip.ip_len) == hlen) {
break;
}
/* (fall through) */
case SPECIAL_I:
case SPECIAL_D:
/*
* actual changes match one of our special case encodings --
* send packet uncompressed.
*/
goto uncompressed;
case NEW_S|NEW_A:
if (deltaS == deltaA && deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
/* special case for echoed terminal traffic */
changes = SPECIAL_I;
cp = new_seq;
}
break;
case NEW_S:
if (deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
/* special case for data xfer */
changes = SPECIAL_D;
cp = new_seq;
}
break;
}
deltaS = (u_short)(ntohs(ip->ip_id) - ntohs(cs->cs_ip.ip_id));
if (deltaS != 1) {
ENCODEZ(deltaS);
changes |= NEW_I;
}
if (th->th_flags & TCP_PSH) {
changes |= TCP_PUSH_BIT;
}
/*
* Grab the cksum before we overwrite it below. Then update our
* state with this packet's header.
*/
deltaA = ntohs(th->th_sum);
BCOPY(ip, &cs->cs_ip, hlen);
/*
* We want to use the original packet as our compressed packet.
* (cp - new_seq) is the number of bytes we need for compressed
* sequence numbers. In addition we need one byte for the change
* mask, one for the connection id and two for the tcp checksum.
* So, (cp - new_seq) + 4 bytes of header are needed. hlen is how
* many bytes of the original packet to toss so subtract the two to
* get the new packet size.
*/
deltaS = (u_short)(cp - new_seq);
if (!comp->compressSlot || comp->last_xmit != cs->cs_id) {
comp->last_xmit = cs->cs_id;
hlen -= deltaS + 4;
if(pbuf_header(pb, -hlen)){
/* Can we cope with this failing? Just assert for now */
LWIP_ASSERT("pbuf_header failed\n", 0);
}
cp = (u_char *)pb->payload;
*cp++ = changes | NEW_C;
*cp++ = cs->cs_id;
} else {
hlen -= deltaS + 3;
if(pbuf_header(pb, -hlen)) {
/* Can we cope with this failing? Just assert for now */
LWIP_ASSERT("pbuf_header failed\n", 0);
}
cp = (u_char *)pb->payload;
*cp++ = changes;
}
*cp++ = deltaA >> 8;
*cp++ = deltaA;
BCOPY(new_seq, cp, deltaS);
INCR(vjs_compressed);
return (TYPE_COMPRESSED_TCP);
/*
* Update connection state cs & send uncompressed packet (that is,
* a regular ip/tcp packet but with the 'conversation id' we hope
* to use on future compressed packets in the protocol field).
*/
uncompressed:
BCOPY(ip, &cs->cs_ip, hlen);
ip->ip_p = cs->cs_id;
comp->last_xmit = cs->cs_id;
return (TYPE_UNCOMPRESSED_TCP);
}
/*
* Called when we may have missed a packet.
*/
void
vj_uncompress_err(struct vjcompress *comp)
{
comp->flags |= VJF_TOSS;
INCR(vjs_errorin);
}
/*
* "Uncompress" a packet of type TYPE_UNCOMPRESSED_TCP.
* Return 0 on success, -1 on failure.
*/
int
vj_uncompress_uncomp(struct pbuf *nb, struct vjcompress *comp)
{
register u_int hlen;
register struct cstate *cs;
register struct ip *ip;
ip = (struct ip *)nb->payload;
hlen = getip_hl(*ip) << 2;
if (ip->ip_p >= MAX_SLOTS
|| hlen + sizeof(struct tcphdr) > nb->len
|| (hlen += getth_off(*((struct tcphdr *)&((char *)ip)[hlen])) << 2)
> nb->len
|| hlen > MAX_HDR) {
PPPDEBUG((LOG_INFO, "vj_uncompress_uncomp: bad cid=%d, hlen=%d buflen=%d\n",
ip->ip_p, hlen, nb->len));
comp->flags |= VJF_TOSS;
INCR(vjs_errorin);
return -1;
}
cs = &comp->rstate[comp->last_recv = ip->ip_p];
comp->flags &=~ VJF_TOSS;
ip->ip_p = IPPROTO_TCP;
BCOPY(ip, &cs->cs_ip, hlen);
cs->cs_hlen = hlen;
INCR(vjs_uncompressedin);
return 0;
}
/*
* Uncompress a packet of type TYPE_COMPRESSED_TCP.
* The packet is composed of a buffer chain and the first buffer
* must contain an accurate chain length.
* The first buffer must include the entire compressed TCP/IP header.
* This procedure replaces the compressed header with the uncompressed
* header and returns the length of the VJ header.
*/
int
vj_uncompress_tcp(struct pbuf **nb, struct vjcompress *comp)
{
u_char *cp;
struct tcphdr *th;
struct cstate *cs;
u_short *bp;
struct pbuf *n0 = *nb;
u32_t tmp;
u_int vjlen, hlen, changes;
INCR(vjs_compressedin);
cp = (u_char *)n0->payload;
changes = *cp++;
if (changes & NEW_C) {
/*
* Make sure the state index is in range, then grab the state.
* If we have a good state index, clear the 'discard' flag.
*/
if (*cp >= MAX_SLOTS) {
PPPDEBUG((LOG_INFO, "vj_uncompress_tcp: bad cid=%d\n", *cp));
goto bad;
}
comp->flags &=~ VJF_TOSS;
comp->last_recv = *cp++;
} else {
/*
* this packet has an implicit state index. If we've
* had a line error since the last time we got an
* explicit state index, we have to toss the packet.
*/
if (comp->flags & VJF_TOSS) {
PPPDEBUG((LOG_INFO, "vj_uncompress_tcp: tossing\n"));
INCR(vjs_tossed);
return (-1);
}
}
cs = &comp->rstate[comp->last_recv];
hlen = getip_hl(cs->cs_ip) << 2;
th = (struct tcphdr *)&((u_char *)&cs->cs_ip)[hlen];
th->th_sum = htons((*cp << 8) | cp[1]);
cp += 2;
if (changes & TCP_PUSH_BIT) {
th->th_flags |= TCP_PSH;
} else {
th->th_flags &=~ TCP_PSH;
}
switch (changes & SPECIALS_MASK) {
case SPECIAL_I:
{
register u32_t i = ntohs(cs->cs_ip.ip_len) - cs->cs_hlen;
/* some compilers can't nest inline assembler.. */
tmp = ntohl(th->th_ack) + i;
th->th_ack = htonl(tmp);
tmp = ntohl(th->th_seq) + i;
th->th_seq = htonl(tmp);
}
break;
case SPECIAL_D:
/* some compilers can't nest inline assembler.. */
tmp = ntohl(th->th_seq) + ntohs(cs->cs_ip.ip_len) - cs->cs_hlen;
th->th_seq = htonl(tmp);
break;
default:
if (changes & NEW_U) {
th->th_flags |= TCP_URG;
DECODEU(th->th_urp);
} else {
th->th_flags &=~ TCP_URG;
}
if (changes & NEW_W) {
DECODES(th->th_win);
}
if (changes & NEW_A) {
DECODEL(th->th_ack);
}
if (changes & NEW_S) {
DECODEL(th->th_seq);
}
break;
}
if (changes & NEW_I) {
DECODES(cs->cs_ip.ip_id);
} else {
cs->cs_ip.ip_id = ntohs(cs->cs_ip.ip_id) + 1;
cs->cs_ip.ip_id = htons(cs->cs_ip.ip_id);
}
/*
* At this point, cp points to the first byte of data in the
* packet. Fill in the IP total length and update the IP
* header checksum.
*/
vjlen = (u_short)(cp - (u_char*)n0->payload);
if (n0->len < vjlen) {
/*
* We must have dropped some characters (crc should detect
* this but the old slip framing won't)
*/
PPPDEBUG((LOG_INFO, "vj_uncompress_tcp: head buffer %d too short %d\n",
n0->len, vjlen));
goto bad;
}
#if BYTE_ORDER == LITTLE_ENDIAN
tmp = n0->tot_len - vjlen + cs->cs_hlen;
cs->cs_ip.ip_len = htons(tmp);
#else
cs->cs_ip.ip_len = htons(n0->tot_len - vjlen + cs->cs_hlen);
#endif
/* recompute the ip header checksum */
bp = (u_short *) &cs->cs_ip;
cs->cs_ip.ip_sum = 0;
for (tmp = 0; hlen > 0; hlen -= 2) {
tmp += *bp++;
}
tmp = (tmp & 0xffff) + (tmp >> 16);
tmp = (tmp & 0xffff) + (tmp >> 16);
cs->cs_ip.ip_sum = (u_short)(~tmp);
/* Remove the compressed header and prepend the uncompressed header. */
if(pbuf_header(n0, -((s16_t)(vjlen)))) {
/* Can we cope with this failing? Just assert for now */
LWIP_ASSERT("pbuf_header failed\n", 0);
goto bad;
}
if(LWIP_MEM_ALIGN(n0->payload) != n0->payload) {
struct pbuf *np, *q;
u8_t *bufptr;
np = pbuf_alloc(PBUF_RAW, n0->len + cs->cs_hlen, PBUF_POOL);
if(!np) {
PPPDEBUG((LOG_WARNING, "vj_uncompress_tcp: realign failed\n"));
goto bad;
}
if(pbuf_header(np, -cs->cs_hlen)) {
/* Can we cope with this failing? Just assert for now */
LWIP_ASSERT("pbuf_header failed\n", 0);
goto bad;
}
bufptr = n0->payload;
for(q = np; q != NULL; q = q->next) {
MEMCPY(q->payload, bufptr, q->len);
bufptr += q->len;
}
if(n0->next) {
pbuf_chain(np, n0->next);
pbuf_dechain(n0);
}
pbuf_free(n0);
n0 = np;
}
if(pbuf_header(n0, cs->cs_hlen)) {
struct pbuf *np;
LWIP_ASSERT("vj_uncompress_tcp: cs->cs_hlen <= PBUF_POOL_BUFSIZE", cs->cs_hlen <= PBUF_POOL_BUFSIZE);
np = pbuf_alloc(PBUF_RAW, cs->cs_hlen, PBUF_POOL);
if(!np) {
PPPDEBUG((LOG_WARNING, "vj_uncompress_tcp: prepend failed\n"));
goto bad;
}
pbuf_cat(np, n0);
n0 = np;
}
LWIP_ASSERT("n0->len >= cs->cs_hlen", n0->len >= cs->cs_hlen);
MEMCPY(n0->payload, &cs->cs_ip, cs->cs_hlen);
*nb = n0;
return vjlen;
bad:
comp->flags |= VJF_TOSS;
INCR(vjs_errorin);
return (-1);
}
#endif /* VJ_SUPPORT */
#endif /* PPP_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/vj.c | C | oos | 19,375 |
/*****************************************************************************
* auth.h - PPP Authentication and phase control header file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1998 Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 97-12-04 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original derived from BSD pppd.h.
*****************************************************************************/
/*
* pppd.h - PPP daemon global declarations.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef AUTH_H
#define AUTH_H
/***********************
*** PUBLIC FUNCTIONS ***
***********************/
/* we are starting to use the link */
void link_required (int);
/* we are finished with the link */
void link_terminated (int);
/* the LCP layer has left the Opened state */
void link_down (int);
/* the link is up; authenticate now */
void link_established (int);
/* a network protocol has come up */
void np_up (int, u16_t);
/* a network protocol has gone down */
void np_down (int, u16_t);
/* a network protocol no longer needs link */
void np_finished (int, u16_t);
/* peer failed to authenticate itself */
void auth_peer_fail (int, u16_t);
/* peer successfully authenticated itself */
void auth_peer_success (int, u16_t, char *, int);
/* we failed to authenticate ourselves */
void auth_withpeer_fail (int, u16_t);
/* we successfully authenticated ourselves */
void auth_withpeer_success (int, u16_t);
/* check authentication options supplied */
void auth_check_options (void);
/* check what secrets we have */
void auth_reset (int);
/* Check peer-supplied username/password */
int check_passwd (int, char *, int, char *, int, char **, int *);
/* get "secret" for chap */
int get_secret (int, char *, char *, char *, int *, int);
/* check if IP address is authorized */
int auth_ip_addr (int, u32_t);
/* check if IP address is unreasonable */
int bad_ip_adrs (u32_t);
#endif /* AUTH_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/auth.h | C | oos | 4,146 |
/*****************************************************************************
* ppp_oe.c - PPP Over Ethernet implementation for lwIP.
*
* Copyright (c) 2006 by Marc Boucher, Services Informatiques (MBSI) inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 06-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
*****************************************************************************/
/* based on NetBSD: if_pppoe.c,v 1.64 2006/01/31 23:50:15 martin Exp */
/*-
* Copyright (c) 2002 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Martin Husemann <martin@NetBSD.org>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "lwip/opt.h"
#if PPPOE_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "ppp.h"
#include "pppdebug.h"
#include "lwip/sys.h"
#include "netif/ppp_oe.h"
#include "netif/etharp.h"
#include <string.h>
#include <stdio.h>
/** @todo Replace this part with a simple list like other lwIP lists */
#ifndef _SYS_QUEUE_H_
#define _SYS_QUEUE_H_
/*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may only be traversed in the forward direction.
*
* For details on the use of these macros, see the queue(3) manual page.
*/
/*
* List declarations.
*/
#define LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
}
#define LIST_HEAD_INITIALIZER(head) \
{ NULL }
#define LIST_ENTRY(type) \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}
/*
* List functions.
*/
#define LIST_EMPTY(head) ((head)->lh_first == NULL)
#define LIST_FIRST(head) ((head)->lh_first)
#define LIST_FOREACH(var, head, field) \
for ((var) = LIST_FIRST((head)); \
(var); \
(var) = LIST_NEXT((var), field))
#define LIST_INIT(head) do { \
LIST_FIRST((head)) = NULL; \
} while (0)
#define LIST_INSERT_AFTER(listelm, elm, field) do { \
if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL) \
LIST_NEXT((listelm), field)->field.le_prev = \
&LIST_NEXT((elm), field); \
LIST_NEXT((listelm), field) = (elm); \
(elm)->field.le_prev = &LIST_NEXT((listelm), field); \
} while (0)
#define LIST_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.le_prev = (listelm)->field.le_prev; \
LIST_NEXT((elm), field) = (listelm); \
*(listelm)->field.le_prev = (elm); \
(listelm)->field.le_prev = &LIST_NEXT((elm), field); \
} while (0)
#define LIST_INSERT_HEAD(head, elm, field) do { \
if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \
LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field); \
LIST_FIRST((head)) = (elm); \
(elm)->field.le_prev = &LIST_FIRST((head)); \
} while (0)
#define LIST_NEXT(elm, field) ((elm)->field.le_next)
#define LIST_REMOVE(elm, field) do { \
if (LIST_NEXT((elm), field) != NULL) \
LIST_NEXT((elm), field)->field.le_prev = \
(elm)->field.le_prev; \
*(elm)->field.le_prev = LIST_NEXT((elm), field); \
} while (0)
#endif /* !_SYS_QUEUE_H_ */
/* Add a 16 bit unsigned value to a buffer pointed to by PTR */
#define PPPOE_ADD_16(PTR, VAL) \
*(PTR)++ = (VAL) / 256; \
*(PTR)++ = (VAL) % 256
/* Add a complete PPPoE header to the buffer pointed to by PTR */
#define PPPOE_ADD_HEADER(PTR, CODE, SESS, LEN) \
*(PTR)++ = PPPOE_VERTYPE; \
*(PTR)++ = (CODE); \
PPPOE_ADD_16(PTR, SESS); \
PPPOE_ADD_16(PTR, LEN)
#define PPPOE_DISC_TIMEOUT (5*1000) /* base for quick timeout calculation */
#define PPPOE_SLOW_RETRY (60*1000) /* persistent retry interval */
#define PPPOE_DISC_MAXPADI 4 /* retry PADI four times (quickly) */
#define PPPOE_DISC_MAXPADR 2 /* retry PADR twice */
#ifdef PPPOE_SERVER
/* from if_spppsubr.c */
#define IFF_PASSIVE IFF_LINK0 /* wait passively for connection */
#endif
struct pppoe_softc {
LIST_ENTRY(pppoe_softc) sc_list;
struct netif *sc_ethif; /* ethernet interface we are using */
int sc_pd; /* ppp unit number */
void (*sc_linkStatusCB)(int pd, int up);
int sc_state; /* discovery phase or session connected */
struct eth_addr sc_dest; /* hardware address of concentrator */
u16_t sc_session; /* PPPoE session id */
char *sc_service_name; /* if != NULL: requested name of service */
char *sc_concentrator_name; /* if != NULL: requested concentrator id */
u8_t *sc_ac_cookie; /* content of AC cookie we must echo back */
size_t sc_ac_cookie_len; /* length of cookie data */
#ifdef PPPOE_SERVER
u8_t *sc_hunique; /* content of host unique we must echo back */
size_t sc_hunique_len; /* length of host unique */
#endif
int sc_padi_retried; /* number of PADI retries already done */
int sc_padr_retried; /* number of PADR retries already done */
};
/* input routines */
static void pppoe_dispatch_disc_pkt(struct netif *, struct pbuf *);
/* management routines */
static int pppoe_do_disconnect(struct pppoe_softc *);
static void pppoe_abort_connect(struct pppoe_softc *);
static void pppoe_clear_softc(struct pppoe_softc *, const char *);
/* internal timeout handling */
static void pppoe_timeout(void *);
/* sending actual protocol controll packets */
static err_t pppoe_send_padi(struct pppoe_softc *);
static err_t pppoe_send_padr(struct pppoe_softc *);
#ifdef PPPOE_SERVER
static err_t pppoe_send_pado(struct pppoe_softc *);
static err_t pppoe_send_pads(struct pppoe_softc *);
#endif
static err_t pppoe_send_padt(struct netif *, u_int, const u8_t *);
/* internal helper functions */
static struct pppoe_softc * pppoe_find_softc_by_session(u_int, struct netif *);
static struct pppoe_softc * pppoe_find_softc_by_hunique(u8_t *, size_t, struct netif *);
static LIST_HEAD(pppoe_softc_head, pppoe_softc) pppoe_softc_list;
int pppoe_hdrlen;
void
pppoe_init(void)
{
pppoe_hdrlen = sizeof(struct eth_hdr) + PPPOE_HEADERLEN;
LIST_INIT(&pppoe_softc_list);
}
err_t
pppoe_create(struct netif *ethif, int pd, void (*linkStatusCB)(int pd, int up), struct pppoe_softc **scptr)
{
struct pppoe_softc *sc;
sc = mem_malloc(sizeof(struct pppoe_softc));
if(!sc) {
*scptr = NULL;
return ERR_MEM;
}
memset(sc, 0, sizeof(struct pppoe_softc));
/* changed to real address later */
MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest));
sc->sc_pd = pd;
sc->sc_linkStatusCB = linkStatusCB;
sc->sc_ethif = ethif;
LIST_INSERT_HEAD(&pppoe_softc_list, sc, sc_list);
*scptr = sc;
return ERR_OK;
}
err_t
pppoe_destroy(struct netif *ifp)
{
struct pppoe_softc * sc;
LIST_FOREACH(sc, &pppoe_softc_list, sc_list) {
if (sc->sc_ethif == ifp) {
break;
}
}
if(!(sc && (sc->sc_ethif == ifp))) {
return ERR_IF;
}
tcpip_untimeout(pppoe_timeout, sc);
LIST_REMOVE(sc, sc_list);
if (sc->sc_concentrator_name) {
mem_free(sc->sc_concentrator_name);
}
if (sc->sc_service_name) {
mem_free(sc->sc_service_name);
}
if (sc->sc_ac_cookie) {
mem_free(sc->sc_ac_cookie);
}
mem_free(sc);
return ERR_OK;
}
/*
* Find the interface handling the specified session.
* Note: O(number of sessions open), this is a client-side only, mean
* and lean implementation, so number of open sessions typically should
* be 1.
*/
static struct pppoe_softc *
pppoe_find_softc_by_session(u_int session, struct netif *rcvif)
{
struct pppoe_softc *sc;
if (session == 0) {
return NULL;
}
LIST_FOREACH(sc, &pppoe_softc_list, sc_list) {
if (sc->sc_state == PPPOE_STATE_SESSION
&& sc->sc_session == session) {
if (sc->sc_ethif == rcvif) {
return sc;
} else {
return NULL;
}
}
}
return NULL;
}
/* Check host unique token passed and return appropriate softc pointer,
* or NULL if token is bogus. */
static struct pppoe_softc *
pppoe_find_softc_by_hunique(u8_t *token, size_t len, struct netif *rcvif)
{
struct pppoe_softc *sc, *t;
if (LIST_EMPTY(&pppoe_softc_list)) {
return NULL;
}
if (len != sizeof sc) {
return NULL;
}
MEMCPY(&t, token, len);
LIST_FOREACH(sc, &pppoe_softc_list, sc_list) {
if (sc == t) {
break;
}
}
if (sc == NULL) {
PPPDEBUG((LOG_DEBUG, "pppoe: alien host unique tag, no session found\n"));
return NULL;
}
/* should be safe to access *sc now */
if (sc->sc_state < PPPOE_STATE_PADI_SENT || sc->sc_state >= PPPOE_STATE_SESSION) {
printf("%c%c%"U16_F": host unique tag found, but it belongs to a connection in state %d\n",
sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, sc->sc_state);
return NULL;
}
if (sc->sc_ethif != rcvif) {
printf("%c%c%"U16_F": wrong interface, not accepting host unique\n",
sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num);
return NULL;
}
return sc;
}
static void
pppoe_linkstatus_up(void *arg)
{
struct pppoe_softc *sc = (struct pppoe_softc*)arg;
sc->sc_linkStatusCB(sc->sc_pd, 1);
}
/* analyze and handle a single received packet while not in session state */
static void
pppoe_dispatch_disc_pkt(struct netif *netif, struct pbuf *pb)
{
u16_t tag, len;
u16_t session, plen;
struct pppoe_softc *sc;
const char *err_msg;
char devname[6];
char *error;
u8_t *ac_cookie;
size_t ac_cookie_len;
#ifdef PPPOE_SERVER
u8_t *hunique;
size_t hunique_len;
#endif
struct pppoehdr *ph;
struct pppoetag pt;
int off = 0, err, errortag;
struct eth_hdr *ethhdr;
pb = pppSingleBuf(pb);
strcpy(devname, "pppoe"); /* as long as we don't know which instance */
err_msg = NULL;
errortag = 0;
if (pb->len < sizeof(*ethhdr)) {
goto done;
}
ethhdr = (struct eth_hdr *)pb->payload;
off += sizeof(*ethhdr);
ac_cookie = NULL;
ac_cookie_len = 0;
#ifdef PPPOE_SERVER
hunique = NULL;
hunique_len = 0;
#endif
session = 0;
if (pb->len - off <= PPPOE_HEADERLEN) {
printf("pppoe: packet too short: %d\n", pb->len);
goto done;
}
ph = (struct pppoehdr *) (ethhdr + 1);
if (ph->vertype != PPPOE_VERTYPE) {
printf("pppoe: unknown version/type packet: 0x%x\n", ph->vertype);
goto done;
}
session = ntohs(ph->session);
plen = ntohs(ph->plen);
off += sizeof(*ph);
if (plen + off > pb->len) {
printf("pppoe: packet content does not fit: data available = %d, packet size = %u\n",
pb->len - off, plen);
goto done;
}
if(pb->tot_len == pb->len) {
pb->tot_len = pb->len = off + plen; /* ignore trailing garbage */
}
tag = 0;
len = 0;
sc = NULL;
while (off + sizeof(pt) <= pb->len) {
MEMCPY(&pt, (u8_t*)pb->payload + off, sizeof(pt));
tag = ntohs(pt.tag);
len = ntohs(pt.len);
if (off + sizeof(pt) + len > pb->len) {
printf("pppoe: tag 0x%x len 0x%x is too long\n", tag, len);
goto done;
}
switch (tag) {
case PPPOE_TAG_EOL:
goto breakbreak;
case PPPOE_TAG_SNAME:
break; /* ignored */
case PPPOE_TAG_ACNAME:
break; /* ignored */
case PPPOE_TAG_HUNIQUE:
if (sc != NULL) {
break;
}
#ifdef PPPOE_SERVER
hunique = (u8_t*)pb->payload + off + sizeof(pt);
hunique_len = len;
#endif
sc = pppoe_find_softc_by_hunique((u8_t*)pb->payload + off + sizeof(pt), len, netif);
if (sc != NULL) {
snprintf(devname, sizeof(devname), "%c%c%"U16_F, sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num);
}
break;
case PPPOE_TAG_ACCOOKIE:
if (ac_cookie == NULL) {
ac_cookie = (u8_t*)pb->payload + off + sizeof(pt);
ac_cookie_len = len;
}
break;
case PPPOE_TAG_SNAME_ERR:
err_msg = "SERVICE NAME ERROR";
errortag = 1;
break;
case PPPOE_TAG_ACSYS_ERR:
err_msg = "AC SYSTEM ERROR";
errortag = 1;
break;
case PPPOE_TAG_GENERIC_ERR:
err_msg = "GENERIC ERROR";
errortag = 1;
break;
}
if (err_msg) {
error = NULL;
if (errortag && len) {
error = mem_malloc(len+1);
if (error) {
strncpy(error, (char*)pb->payload + off + sizeof(pt), len);
error[len-1] = '\0';
}
}
if (error) {
printf("%s: %s: %s\n", devname, err_msg, error);
mem_free(error);
} else {
printf("%s: %s\n", devname, err_msg);
}
if (errortag) {
goto done;
}
}
off += sizeof(pt) + len;
}
breakbreak:;
switch (ph->code) {
case PPPOE_CODE_PADI:
#ifdef PPPOE_SERVER
/*
* got service name, concentrator name, and/or host unique.
* ignore if we have no interfaces with IFF_PASSIVE|IFF_UP.
*/
if (LIST_EMPTY(&pppoe_softc_list)) {
goto done;
}
LIST_FOREACH(sc, &pppoe_softc_list, sc_list) {
if (!(sc->sc_sppp.pp_if.if_flags & IFF_UP)) {
continue;
}
if (!(sc->sc_sppp.pp_if.if_flags & IFF_PASSIVE)) {
continue;
}
if (sc->sc_state == PPPOE_STATE_INITIAL) {
break;
}
}
if (sc == NULL) {
/* printf("pppoe: free passive interface is not found\n"); */
goto done;
}
if (hunique) {
if (sc->sc_hunique) {
mem_free(sc->sc_hunique);
}
sc->sc_hunique = mem_malloc(hunique_len);
if (sc->sc_hunique == NULL) {
goto done;
}
sc->sc_hunique_len = hunique_len;
MEMCPY(sc->sc_hunique, hunique, hunique_len);
}
MEMCPY(&sc->sc_dest, eh->ether_shost, sizeof sc->sc_dest);
sc->sc_state = PPPOE_STATE_PADO_SENT;
pppoe_send_pado(sc);
break;
#endif /* PPPOE_SERVER */
case PPPOE_CODE_PADR:
#ifdef PPPOE_SERVER
/*
* get sc from ac_cookie if IFF_PASSIVE
*/
if (ac_cookie == NULL) {
/* be quiet if there is not a single pppoe instance */
printf("pppoe: received PADR but not includes ac_cookie\n");
goto done;
}
sc = pppoe_find_softc_by_hunique(ac_cookie, ac_cookie_len, netif);
if (sc == NULL) {
/* be quiet if there is not a single pppoe instance */
if (!LIST_EMPTY(&pppoe_softc_list)) {
printf("pppoe: received PADR but could not find request for it\n");
}
goto done;
}
if (sc->sc_state != PPPOE_STATE_PADO_SENT) {
printf("%c%c%"U16_F": received unexpected PADR\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num);
goto done;
}
if (hunique) {
if (sc->sc_hunique) {
mem_free(sc->sc_hunique);
}
sc->sc_hunique = mem_malloc(hunique_len);
if (sc->sc_hunique == NULL) {
goto done;
}
sc->sc_hunique_len = hunique_len;
MEMCPY(sc->sc_hunique, hunique, hunique_len);
}
pppoe_send_pads(sc);
sc->sc_state = PPPOE_STATE_SESSION;
tcpip_timeout (100, pppoe_linkstatus_up, sc); /* notify upper layers */
break;
#else
/* ignore, we are no access concentrator */
goto done;
#endif /* PPPOE_SERVER */
case PPPOE_CODE_PADO:
if (sc == NULL) {
/* be quiet if there is not a single pppoe instance */
if (!LIST_EMPTY(&pppoe_softc_list)) {
printf("pppoe: received PADO but could not find request for it\n");
}
goto done;
}
if (sc->sc_state != PPPOE_STATE_PADI_SENT) {
printf("%c%c%"U16_F": received unexpected PADO\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num);
goto done;
}
if (ac_cookie) {
if (sc->sc_ac_cookie) {
mem_free(sc->sc_ac_cookie);
}
sc->sc_ac_cookie = mem_malloc(ac_cookie_len);
if (sc->sc_ac_cookie == NULL) {
goto done;
}
sc->sc_ac_cookie_len = ac_cookie_len;
MEMCPY(sc->sc_ac_cookie, ac_cookie, ac_cookie_len);
}
MEMCPY(&sc->sc_dest, ethhdr->src.addr, sizeof(sc->sc_dest.addr));
tcpip_untimeout(pppoe_timeout, sc);
sc->sc_padr_retried = 0;
sc->sc_state = PPPOE_STATE_PADR_SENT;
if ((err = pppoe_send_padr(sc)) != 0) {
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": failed to send PADR, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err));
}
tcpip_timeout(PPPOE_DISC_TIMEOUT * (1 + sc->sc_padr_retried), pppoe_timeout, sc);
break;
case PPPOE_CODE_PADS:
if (sc == NULL) {
goto done;
}
sc->sc_session = session;
tcpip_untimeout(pppoe_timeout, sc);
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": session 0x%x connected\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, session));
sc->sc_state = PPPOE_STATE_SESSION;
tcpip_timeout (100, pppoe_linkstatus_up, sc); /* notify upper layers */
break;
case PPPOE_CODE_PADT:
if (sc == NULL) {
goto done;
}
pppoe_clear_softc(sc, "received PADT");
break;
default:
if(sc) {
printf("%c%c%"U16_F": unknown code (0x%04x) session = 0x%04x\n",
sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num,
ph->code, session);
} else {
printf("pppoe: unknown code (0x%04x) session = 0x%04x\n", ph->code, session);
}
break;
}
done:
pbuf_free(pb);
return;
}
void
pppoe_disc_input(struct netif *netif, struct pbuf *p)
{
/* avoid error messages if there is not a single pppoe instance */
if (!LIST_EMPTY(&pppoe_softc_list)) {
pppoe_dispatch_disc_pkt(netif, p);
} else {
pbuf_free(p);
}
}
void
pppoe_data_input(struct netif *netif, struct pbuf *pb)
{
u16_t session, plen;
struct pppoe_softc *sc;
struct pppoehdr *ph;
#ifdef PPPOE_TERM_UNKNOWN_SESSIONS
u8_t shost[ETHER_ADDR_LEN];
#endif
#ifdef PPPOE_TERM_UNKNOWN_SESSIONS
MEMCPY(shost, ((struct eth_hdr *)pb->payload)->src.addr, sizeof(shost));
#endif
if (pbuf_header(pb, -(int)sizeof(struct eth_hdr)) != 0) {
/* bail out */
PPPDEBUG((LOG_ERR, "pppoe_data_input: pbuf_header failed\n"));
LINK_STATS_INC(link.lenerr);
goto drop;
}
pb = pppSingleBuf (pb);
if (pb->len <= PPPOE_HEADERLEN) {
printf("pppoe (data): dropping too short packet: %d bytes\n", pb->len);
goto drop;
}
if (pb->len < sizeof(*ph)) {
printf("pppoe_data_input: could not get PPPoE header\n");
goto drop;
}
ph = (struct pppoehdr *)pb->payload;
if (ph->vertype != PPPOE_VERTYPE) {
printf("pppoe (data): unknown version/type packet: 0x%x\n", ph->vertype);
goto drop;
}
if (ph->code != 0) {
goto drop;
}
session = ntohs(ph->session);
sc = pppoe_find_softc_by_session(session, netif);
if (sc == NULL) {
#ifdef PPPOE_TERM_UNKNOWN_SESSIONS
printf("pppoe: input for unknown session 0x%x, sending PADT\n", session);
pppoe_send_padt(netif, session, shost);
#endif
goto drop;
}
plen = ntohs(ph->plen);
if (pbuf_header(pb, -(int)(PPPOE_HEADERLEN)) != 0) {
/* bail out */
PPPDEBUG((LOG_ERR, "pppoe_data_input: pbuf_header PPPOE_HEADERLEN failed\n"));
LINK_STATS_INC(link.lenerr);
goto drop;
}
PPPDEBUG((LOG_DEBUG, "pppoe_data_input: %c%c%"U16_F": pkthdr.len=%d, pppoe.len=%d\n",
sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num,
pb->len, plen));
if (pb->len < plen) {
goto drop;
}
pppInProcOverEthernet(sc->sc_pd, pb);
return;
drop:
pbuf_free(pb);
}
static err_t
pppoe_output(struct pppoe_softc *sc, struct pbuf *pb)
{
struct eth_hdr *ethhdr;
u16_t etype;
err_t res;
if (!sc->sc_ethif) {
pbuf_free(pb);
return ERR_IF;
}
ethhdr = (struct eth_hdr *)pb->payload;
etype = sc->sc_state == PPPOE_STATE_SESSION ? ETHTYPE_PPPOE : ETHTYPE_PPPOEDISC;
ethhdr->type = htons(etype);
MEMCPY(ethhdr->dest.addr, sc->sc_dest.addr, sizeof(ethhdr->dest.addr));
MEMCPY(ethhdr->src.addr, ((struct eth_addr *)sc->sc_ethif->hwaddr)->addr, sizeof(ethhdr->src.addr));
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F" (%x) state=%d, session=0x%x output -> %02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F", len=%d\n",
sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, etype,
sc->sc_state, sc->sc_session,
sc->sc_dest.addr[0], sc->sc_dest.addr[1], sc->sc_dest.addr[2], sc->sc_dest.addr[3], sc->sc_dest.addr[4], sc->sc_dest.addr[5],
pb->tot_len));
res = sc->sc_ethif->linkoutput(sc->sc_ethif, pb);
pbuf_free(pb);
return res;
}
static err_t
pppoe_send_padi(struct pppoe_softc *sc)
{
struct pbuf *pb;
u8_t *p;
int len, l1 = 0, l2 = 0; /* XXX: gcc */
if (sc->sc_state >PPPOE_STATE_PADI_SENT) {
PPPDEBUG((LOG_ERR, "ERROR: pppoe_send_padi in state %d", sc->sc_state));
}
/* calculate length of frame (excluding ethernet header + pppoe header) */
len = 2 + 2 + 2 + 2 + sizeof sc; /* service name tag is required, host unique is send too */
if (sc->sc_service_name != NULL) {
l1 = strlen(sc->sc_service_name);
len += l1;
}
if (sc->sc_concentrator_name != NULL) {
l2 = strlen(sc->sc_concentrator_name);
len += 2 + 2 + l2;
}
/* allocate a buffer */
pb = pbuf_alloc(PBUF_LINK, sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len, PBUF_RAM);
if (!pb) {
return ERR_MEM;
}
p = (u8_t*)pb->payload + sizeof (struct eth_hdr);
/* fill in pkt */
PPPOE_ADD_HEADER(p, PPPOE_CODE_PADI, 0, len);
PPPOE_ADD_16(p, PPPOE_TAG_SNAME);
if (sc->sc_service_name != NULL) {
PPPOE_ADD_16(p, l1);
MEMCPY(p, sc->sc_service_name, l1);
p += l1;
} else {
PPPOE_ADD_16(p, 0);
}
if (sc->sc_concentrator_name != NULL) {
PPPOE_ADD_16(p, PPPOE_TAG_ACNAME);
PPPOE_ADD_16(p, l2);
MEMCPY(p, sc->sc_concentrator_name, l2);
p += l2;
}
PPPOE_ADD_16(p, PPPOE_TAG_HUNIQUE);
PPPOE_ADD_16(p, sizeof(sc));
MEMCPY(p, &sc, sizeof sc);
/* send pkt */
return pppoe_output(sc, pb);
}
static void
pppoe_timeout(void *arg)
{
int retry_wait, err;
struct pppoe_softc *sc = (struct pppoe_softc*)arg;
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": timeout\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num));
switch (sc->sc_state) {
case PPPOE_STATE_PADI_SENT:
/*
* We have two basic ways of retrying:
* - Quick retry mode: try a few times in short sequence
* - Slow retry mode: we already had a connection successfully
* established and will try infinitely (without user
* intervention)
* We only enter slow retry mode if IFF_LINK1 (aka autodial)
* is not set.
*/
/* initialize for quick retry mode */
retry_wait = PPPOE_DISC_TIMEOUT * (1 + sc->sc_padi_retried);
sc->sc_padi_retried++;
if (sc->sc_padi_retried >= PPPOE_DISC_MAXPADI) {
#if 0
if ((sc->sc_sppp.pp_if.if_flags & IFF_LINK1) == 0) {
/* slow retry mode */
retry_wait = PPPOE_SLOW_RETRY;
} else
#endif
{
pppoe_abort_connect(sc);
return;
}
}
if ((err = pppoe_send_padi(sc)) != 0) {
sc->sc_padi_retried--;
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": failed to transmit PADI, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err));
}
tcpip_timeout(retry_wait, pppoe_timeout, sc);
break;
case PPPOE_STATE_PADR_SENT:
sc->sc_padr_retried++;
if (sc->sc_padr_retried >= PPPOE_DISC_MAXPADR) {
MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest));
sc->sc_state = PPPOE_STATE_PADI_SENT;
sc->sc_padr_retried = 0;
if ((err = pppoe_send_padi(sc)) != 0) {
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": failed to send PADI, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err));
}
tcpip_timeout(PPPOE_DISC_TIMEOUT * (1 + sc->sc_padi_retried), pppoe_timeout, sc);
return;
}
if ((err = pppoe_send_padr(sc)) != 0) {
sc->sc_padr_retried--;
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": failed to send PADR, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err));
}
tcpip_timeout(PPPOE_DISC_TIMEOUT * (1 + sc->sc_padr_retried), pppoe_timeout, sc);
break;
case PPPOE_STATE_CLOSING:
pppoe_do_disconnect(sc);
break;
default:
return; /* all done, work in peace */
}
}
/* Start a connection (i.e. initiate discovery phase) */
int
pppoe_connect(struct pppoe_softc *sc)
{
int err;
if (sc->sc_state != PPPOE_STATE_INITIAL) {
return EBUSY;
}
#ifdef PPPOE_SERVER
/* wait PADI if IFF_PASSIVE */
if ((sc->sc_sppp.pp_if.if_flags & IFF_PASSIVE)) {
return 0;
}
#endif
/* save state, in case we fail to send PADI */
sc->sc_state = PPPOE_STATE_PADI_SENT;
sc->sc_padr_retried = 0;
err = pppoe_send_padi(sc);
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": failed to send PADI, error=%d\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, err));
tcpip_timeout(PPPOE_DISC_TIMEOUT, pppoe_timeout, sc);
return err;
}
/* disconnect */
void
pppoe_disconnect(struct pppoe_softc *sc)
{
if (sc->sc_state < PPPOE_STATE_SESSION) {
return;
}
/*
* Do not call pppoe_disconnect here, the upper layer state
* machine gets confused by this. We must return from this
* function and defer disconnecting to the timeout handler.
*/
sc->sc_state = PPPOE_STATE_CLOSING;
tcpip_timeout(20, pppoe_timeout, sc);
}
static int
pppoe_do_disconnect(struct pppoe_softc *sc)
{
int err;
if (sc->sc_state < PPPOE_STATE_SESSION) {
err = EBUSY;
} else {
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": disconnecting\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num));
err = pppoe_send_padt(sc->sc_ethif, sc->sc_session, (const u8_t *)&sc->sc_dest);
}
/* cleanup softc */
sc->sc_state = PPPOE_STATE_INITIAL;
MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest));
if (sc->sc_ac_cookie) {
mem_free(sc->sc_ac_cookie);
sc->sc_ac_cookie = NULL;
}
sc->sc_ac_cookie_len = 0;
#ifdef PPPOE_SERVER
if (sc->sc_hunique) {
mem_free(sc->sc_hunique);
sc->sc_hunique = NULL;
}
sc->sc_hunique_len = 0;
#endif
sc->sc_session = 0;
sc->sc_linkStatusCB(sc->sc_pd, 0); /* notify upper layers */
return err;
}
/* Connection attempt aborted */
static void
pppoe_abort_connect(struct pppoe_softc *sc)
{
printf("%c%c%"U16_F": could not establish connection\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num);
sc->sc_state = PPPOE_STATE_CLOSING;
sc->sc_linkStatusCB(sc->sc_pd, 0); /* notify upper layers */
/* clear connection state */
MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest));
sc->sc_state = PPPOE_STATE_INITIAL;
}
/* Send a PADR packet */
static err_t
pppoe_send_padr(struct pppoe_softc *sc)
{
struct pbuf *pb;
u8_t *p;
size_t len, l1 = 0; /* XXX: gcc */
if (sc->sc_state != PPPOE_STATE_PADR_SENT) {
return ERR_CONN;
}
len = 2 + 2 + 2 + 2 + sizeof(sc); /* service name, host unique */
if (sc->sc_service_name != NULL) { /* service name tag maybe empty */
l1 = strlen(sc->sc_service_name);
len += l1;
}
if (sc->sc_ac_cookie_len > 0) {
len += 2 + 2 + sc->sc_ac_cookie_len; /* AC cookie */
}
pb = pbuf_alloc(PBUF_LINK, sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len, PBUF_RAM);
if (!pb) {
return ERR_MEM;
}
p = (u8_t*)pb->payload + sizeof (struct eth_hdr);
PPPOE_ADD_HEADER(p, PPPOE_CODE_PADR, 0, len);
PPPOE_ADD_16(p, PPPOE_TAG_SNAME);
if (sc->sc_service_name != NULL) {
PPPOE_ADD_16(p, l1);
MEMCPY(p, sc->sc_service_name, l1);
p += l1;
} else {
PPPOE_ADD_16(p, 0);
}
if (sc->sc_ac_cookie_len > 0) {
PPPOE_ADD_16(p, PPPOE_TAG_ACCOOKIE);
PPPOE_ADD_16(p, sc->sc_ac_cookie_len);
MEMCPY(p, sc->sc_ac_cookie, sc->sc_ac_cookie_len);
p += sc->sc_ac_cookie_len;
}
PPPOE_ADD_16(p, PPPOE_TAG_HUNIQUE);
PPPOE_ADD_16(p, sizeof(sc));
MEMCPY(p, &sc, sizeof sc);
return pppoe_output(sc, pb);
}
/* send a PADT packet */
static err_t
pppoe_send_padt(struct netif *outgoing_if, u_int session, const u8_t *dest)
{
struct pbuf *pb;
struct eth_hdr *ethhdr;
err_t res;
u8_t *p;
pb = pbuf_alloc(PBUF_LINK, sizeof(struct eth_hdr) + PPPOE_HEADERLEN, PBUF_RAM);
if (!pb) {
return ERR_MEM;
}
ethhdr = (struct eth_hdr *)pb->payload;
ethhdr->type = htons(ETHTYPE_PPPOEDISC);
MEMCPY(ethhdr->dest.addr, dest, sizeof(ethhdr->dest.addr));
MEMCPY(ethhdr->src.addr, ((struct eth_addr *)outgoing_if->hwaddr)->addr, sizeof(ethhdr->src.addr));
p = (u8_t*)(ethhdr + 1);
PPPOE_ADD_HEADER(p, PPPOE_CODE_PADT, session, 0);
res = outgoing_if->linkoutput(outgoing_if, pb);
pbuf_free(pb);
return res;
}
#ifdef PPPOE_SERVER
static err_t
pppoe_send_pado(struct pppoe_softc *sc)
{
struct pbuf *pb;
u8_t *p;
size_t len;
if (sc->sc_state != PPPOE_STATE_PADO_SENT) {
return ERR_CONN;
}
/* calc length */
len = 0;
/* include ac_cookie */
len += 2 + 2 + sizeof(sc);
/* include hunique */
len += 2 + 2 + sc->sc_hunique_len;
pb = pbuf_alloc(PBUF_LINK, sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len, PBUF_RAM);
if (!pb) {
return ERR_MEM;
}
p = (u8_t*)pb->payload + sizeof (struct eth_hdr);
PPPOE_ADD_HEADER(p, PPPOE_CODE_PADO, 0, len);
PPPOE_ADD_16(p, PPPOE_TAG_ACCOOKIE);
PPPOE_ADD_16(p, sizeof(sc));
MEMCPY(p, &sc, sizeof(sc));
p += sizeof(sc);
PPPOE_ADD_16(p, PPPOE_TAG_HUNIQUE);
PPPOE_ADD_16(p, sc->sc_hunique_len);
MEMCPY(p, sc->sc_hunique, sc->sc_hunique_len);
return pppoe_output(sc, pb);
}
static err_t
pppoe_send_pads(struct pppoe_softc *sc)
{
struct pbuf *pb;
u8_t *p;
size_t len, l1 = 0; /* XXX: gcc */
if (sc->sc_state != PPPOE_STATE_PADO_SENT) {
return ERR_CONN;
}
sc->sc_session = mono_time.tv_sec % 0xff + 1;
/* calc length */
len = 0;
/* include hunique */
len += 2 + 2 + 2 + 2 + sc->sc_hunique_len; /* service name, host unique*/
if (sc->sc_service_name != NULL) { /* service name tag maybe empty */
l1 = strlen(sc->sc_service_name);
len += l1;
}
pb = pbuf_alloc(PBUF_LINK, sizeof(struct eth_hdr) + PPPOE_HEADERLEN + len, PBUF_RAM);
if (!pb) {
return ERR_MEM;
}
p = (u8_t*)pb->payload + sizeof (struct eth_hdr);
PPPOE_ADD_HEADER(p, PPPOE_CODE_PADS, sc->sc_session, len);
PPPOE_ADD_16(p, PPPOE_TAG_SNAME);
if (sc->sc_service_name != NULL) {
PPPOE_ADD_16(p, l1);
MEMCPY(p, sc->sc_service_name, l1);
p += l1;
} else {
PPPOE_ADD_16(p, 0);
}
PPPOE_ADD_16(p, PPPOE_TAG_HUNIQUE);
PPPOE_ADD_16(p, sc->sc_hunique_len);
MEMCPY(p, sc->sc_hunique, sc->sc_hunique_len);
return pppoe_output(sc, pb);
}
#endif
err_t
pppoe_xmit(struct pppoe_softc *sc, struct pbuf *pb)
{
u8_t *p;
size_t len;
/* are we ready to process data yet? */
if (sc->sc_state < PPPOE_STATE_SESSION) {
/*sppp_flush(&sc->sc_sppp.pp_if);*/
pbuf_free(pb);
return ERR_CONN;
}
len = pb->tot_len;
/* make room for Ethernet header - should not fail */
if (pbuf_header(pb, sizeof(struct eth_hdr) + PPPOE_HEADERLEN) != 0) {
/* bail out */
PPPDEBUG((LOG_ERR, "pppoe: %c%c%"U16_F": pppoe_xmit: could not allocate room for header\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num));
LINK_STATS_INC(link.lenerr);
pbuf_free(pb);
return ERR_BUF;
}
p = (u8_t*)pb->payload + sizeof(struct eth_hdr);
PPPOE_ADD_HEADER(p, 0, sc->sc_session, len);
return pppoe_output(sc, pb);
}
#if 0 /*def PFIL_HOOKS*/
static int
pppoe_ifattach_hook(void *arg, struct pbuf **mp, struct netif *ifp, int dir)
{
struct pppoe_softc *sc;
int s;
if (mp != (struct pbuf **)PFIL_IFNET_DETACH) {
return 0;
}
LIST_FOREACH(sc, &pppoe_softc_list, sc_list) {
if (sc->sc_ethif != ifp) {
continue;
}
if (sc->sc_sppp.pp_if.if_flags & IFF_UP) {
sc->sc_sppp.pp_if.if_flags &= ~(IFF_UP|IFF_RUNNING);
printf("%c%c%"U16_F": ethernet interface detached, going down\n",
sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num);
}
sc->sc_ethif = NULL;
pppoe_clear_softc(sc, "ethernet interface detached");
}
return 0;
}
#endif
static void
pppoe_clear_softc(struct pppoe_softc *sc, const char *message)
{
LWIP_UNUSED_ARG(message);
/* stop timer */
tcpip_untimeout(pppoe_timeout, sc);
PPPDEBUG((LOG_DEBUG, "pppoe: %c%c%"U16_F": session 0x%x terminated, %s\n", sc->sc_ethif->name[0], sc->sc_ethif->name[1], sc->sc_ethif->num, sc->sc_session, message));
/* fix our state */
sc->sc_state = PPPOE_STATE_INITIAL;
/* notify upper layers */
sc->sc_linkStatusCB(sc->sc_pd, 0);
/* clean up softc */
MEMCPY(&sc->sc_dest, ethbroadcast.addr, sizeof(sc->sc_dest));
if (sc->sc_ac_cookie) {
mem_free(sc->sc_ac_cookie);
sc->sc_ac_cookie = NULL;
}
sc->sc_ac_cookie_len = 0;
sc->sc_session = 0;
}
#endif /* PPPOE_SUPPORT */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/ppp_oe.c | C | oos | 38,755 |
/*****************************************************************************
* randm.h - Random number generator header file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* Copyright (c) 1998 Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 98-05-29 Guy Lancaster <glanca@gesn.com>, Global Election Systems Inc.
* Extracted from avos.
*****************************************************************************/
#ifndef RANDM_H
#define RANDM_H
/***********************
*** PUBLIC FUNCTIONS ***
***********************/
/*
* Initialize the random number generator.
*/
void avRandomInit(void);
/*
* Churn the randomness pool on a random event. Call this early and often
* on random and semi-random system events to build randomness in time for
* usage. For randomly timed events, pass a null pointer and a zero length
* and this will use the system timer and other sources to add randomness.
* If new random data is available, pass a pointer to that and it will be
* included.
*/
void avChurnRand(char *randData, u32_t randLen);
/*
* Randomize our random seed value. To be called for truely random events
* such as user operations and network traffic.
*/
#if MD5_SUPPORT
#define avRandomize() avChurnRand(NULL, 0)
#else /* MD5_SUPPORT */
void avRandomize(void);
#endif /* MD5_SUPPORT */
/*
* Use the random pool to generate random data. This degrades to pseudo
* random when used faster than randomness is supplied using churnRand().
* Thus it's important to make sure that the results of this are not
* published directly because one could predict the next result to at
* least some degree. Also, it's important to get a good seed before
* the first use.
*/
void avGenRand(char *buf, u32_t bufLen);
/*
* Return a new random number.
*/
u32_t avRandom(void);
#endif /* RANDM_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/randm.h | C | oos | 3,211 |
/*****************************************************************************
* pppdebug.h - System debugging utilities.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1998 Global Election Systems Inc.
* portions Copyright (c) 2001 by Cognizant Pty Ltd.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY (please don't use tabs!)
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 98-07-29 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original.
*
*****************************************************************************
*/
#ifndef PPPDEBUG_H
#define PPPDEBUG_H
/************************
*** PUBLIC DATA TYPES ***
************************/
/* Trace levels. */
typedef enum {
LOG_CRITICAL = 0,
LOG_ERR = 1,
LOG_NOTICE = 2,
LOG_WARNING = 3,
LOG_INFO = 5,
LOG_DETAIL = 6,
LOG_DEBUG = 7
} LogCodes;
/***********************
*** PUBLIC FUNCTIONS ***
***********************/
/*
* ppp_trace - a form of printf to send tracing information to stderr
*/
void ppp_trace(int level, const char *format,...);
#define TRACELCP PPP_DEBUG
#if PPP_DEBUG
#define AUTHDEBUG(a) ppp_trace a
#define IPCPDEBUG(a) ppp_trace a
#define UPAPDEBUG(a) ppp_trace a
#define LCPDEBUG(a) ppp_trace a
#define FSMDEBUG(a) ppp_trace a
#define CHAPDEBUG(a) ppp_trace a
#define PPPDEBUG(a) ppp_trace a
#else /* PPP_DEBUG */
#define AUTHDEBUG(a)
#define IPCPDEBUG(a)
#define UPAPDEBUG(a)
#define LCPDEBUG(a)
#define FSMDEBUG(a)
#define CHAPDEBUG(a)
#define PPPDEBUG(a)
#endif /* PPP_DEBUG */
#endif /* PPPDEBUG_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/pppdebug.h | C | oos | 2,878 |
/*****************************************************************************
* chpms.h - Network Microsoft Challenge Handshake Protocol header file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* portions Copyright (c) 1998 Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 98-01-30 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Original built from BSD network code.
******************************************************************************/
/*
* chap.h - Challenge Handshake Authentication Protocol definitions.
*
* Copyright (c) 1995 Eric Rosenquist, Strata Software Limited.
* http://www.strataware.com/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Eric Rosenquist. The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* $Id: chpms.h,v 1.5 2007/12/19 20:47:23 fbernon Exp $
*/
#ifndef CHPMS_H
#define CHPMS_H
#define MAX_NT_PASSWORD 256 /* Maximum number of (Unicode) chars in an NT password */
void ChapMS (chap_state *, char *, int, char *, int);
#endif /* CHPMS_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/ppp/chpms.h | C | oos | 3,006 |
/**
* @file
* SLIP Interface
*
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is built upon the file: src/arch/rtxc/netif/sioslip.c
*
* Author: Magnus Ivarsson <magnus.ivarsson(at)volvo.com>
*/
/*
* This is an arch independent SLIP netif. The specific serial hooks must be
* provided by another file. They are sio_open, sio_recv and sio_send
*/
#include "netif/slipif.h"
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/pbuf.h"
#include "lwip/sys.h"
#include "lwip/stats.h"
#include "lwip/snmp.h"
#include "lwip/sio.h"
#define SLIP_END 0300 /* 0xC0 */
#define SLIP_ESC 0333 /* 0xDB */
#define SLIP_ESC_END 0334 /* 0xDC */
#define SLIP_ESC_ESC 0335 /* 0xDD */
#define MAX_SIZE 1500
/**
* Send a pbuf doing the necessary SLIP encapsulation
*
* Uses the serial layer's sio_send()
*
* @param netif the lwip network interface structure for this slipif
* @param p the pbuf chaing packet to send
* @param ipaddr the ip address to send the packet to (not used for slipif)
* @return always returns ERR_OK since the serial layer does not provide return values
*/
err_t
slipif_output(struct netif *netif, struct pbuf *p, struct ip_addr *ipaddr)
{
struct pbuf *q;
u16_t i;
u8_t c;
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("netif->state != NULL", (netif->state != NULL));
LWIP_ASSERT("p != NULL", (p != NULL));
LWIP_UNUSED_ARG(ipaddr);
/* Send pbuf out on the serial I/O device. */
sio_send(SLIP_END, netif->state);
for (q = p; q != NULL; q = q->next) {
for (i = 0; i < q->len; i++) {
c = ((u8_t *)q->payload)[i];
switch (c) {
case SLIP_END:
sio_send(SLIP_ESC, netif->state);
sio_send(SLIP_ESC_END, netif->state);
break;
case SLIP_ESC:
sio_send(SLIP_ESC, netif->state);
sio_send(SLIP_ESC_ESC, netif->state);
break;
default:
sio_send(c, netif->state);
break;
}
}
}
sio_send(SLIP_END, netif->state);
return ERR_OK;
}
/**
* Handle the incoming SLIP stream character by character
*
* Poll the serial layer by calling sio_recv()
*
* @param netif the lwip network interface structure for this slipif
* @return The IP packet when SLIP_END is received
*/
static struct pbuf *
slipif_input(struct netif *netif)
{
u8_t c;
/* q is the whole pbuf chain for a packet, p is the current pbuf in the chain */
struct pbuf *p, *q;
u16_t recved;
u16_t i;
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("netif->state != NULL", (netif->state != NULL));
q = p = NULL;
recved = i = 0;
c = 0;
while (1) {
c = sio_recv(netif->state);
switch (c) {
case SLIP_END:
if (recved > 0) {
/* Received whole packet. */
/* Trim the pbuf to the size of the received packet. */
pbuf_realloc(q, recved);
LINK_STATS_INC(link.recv);
LWIP_DEBUGF(SLIP_DEBUG, ("slipif: Got packet\n"));
return q;
}
break;
case SLIP_ESC:
c = sio_recv(netif->state);
switch (c) {
case SLIP_ESC_END:
c = SLIP_END;
break;
case SLIP_ESC_ESC:
c = SLIP_ESC;
break;
}
/* FALLTHROUGH */
default:
/* byte received, packet not yet completely received */
if (p == NULL) {
/* allocate a new pbuf */
LWIP_DEBUGF(SLIP_DEBUG, ("slipif_input: alloc\n"));
p = pbuf_alloc(PBUF_LINK, PBUF_POOL_BUFSIZE, PBUF_POOL);
if (p == NULL) {
LINK_STATS_INC(link.drop);
LWIP_DEBUGF(SLIP_DEBUG, ("slipif_input: no new pbuf! (DROP)\n"));
/* don't process any further since we got no pbuf to receive to */
break;
}
if (q != NULL) {
/* 'chain' the pbuf to the existing chain */
pbuf_cat(q, p);
} else {
/* p is the first pbuf in the chain */
q = p;
}
}
/* this automatically drops bytes if > MAX_SIZE */
if ((p != NULL) && (recved <= MAX_SIZE)) {
((u8_t *)p->payload)[i] = c;
recved++;
i++;
if (i >= p->len) {
/* on to the next pbuf */
i = 0;
if (p->next != NULL && p->next->len > 0) {
/* p is a chain, on to the next in the chain */
p = p->next;
} else {
/* p is a single pbuf, set it to NULL so next time a new
* pbuf is allocated */
p = NULL;
}
}
}
break;
}
}
return NULL;
}
#if !NO_SYS
/**
* The SLIP input thread.
*
* Feed the IP layer with incoming packets
*
* @param nf the lwip network interface structure for this slipif
*/
static void
slipif_loop(void *nf)
{
struct pbuf *p;
struct netif *netif = (struct netif *)nf;
while (1) {
p = slipif_input(netif);
if (p != NULL) {
if (netif->input(p, netif) != ERR_OK) {
pbuf_free(p);
p = NULL;
}
}
}
}
#endif /* !NO_SYS */
/**
* SLIP netif initialization
*
* Call the arch specific sio_open and remember
* the opened device in the state field of the netif.
*
* @param netif the lwip network interface structure for this slipif
* @return ERR_OK if serial line could be opened,
* ERR_IF is serial line couldn't be opened
*
* @note netif->num must contain the number of the serial port to open
* (0 by default)
*/
err_t
slipif_init(struct netif *netif)
{
LWIP_DEBUGF(SLIP_DEBUG, ("slipif_init: netif->num=%"U16_F"\n", (u16_t)netif->num));
netif->name[0] = 's';
netif->name[1] = 'l';
netif->output = slipif_output;
netif->mtu = MAX_SIZE;
netif->flags = NETIF_FLAG_POINTTOPOINT;
/* Try to open the serial port (netif->num contains the port number). */
netif->state = sio_open(netif->num);
if (!netif->state) {
/* Opening the serial port failed. */
return ERR_IF;
}
/* initialize the snmp variables and counters inside the struct netif
* ifSpeed: no assumption can be made without knowing more about the
* serial line!
*/
NETIF_INIT_SNMP(netif, snmp_ifType_slip, 0);
/* Create a thread to poll the serial line. */
sys_thread_new(SLIPIF_THREAD_NAME, slipif_loop, netif, SLIPIF_THREAD_STACKSIZE, SLIPIF_THREAD_PRIO);
return ERR_OK;
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/slipif.c | C | oos | 8,132 |
/**
* @file
* Address Resolution Protocol module for IP over Ethernet
*
* Functionally, ARP is divided into two parts. The first maps an IP address
* to a physical address when sending a packet, and the second part answers
* requests from other machines for our physical address.
*
* This implementation complies with RFC 826 (Ethernet ARP). It supports
* Gratuitious ARP from RFC3220 (IP Mobility Support for IPv4) section 4.6
* if an interface calls etharp_query(our_netif, its_ip_addr, NULL) upon
* address change.
*/
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* Copyright (c) 2003-2004 Leon Woestenberg <leon.woestenberg@axon.tv>
* Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
*/
#include "lwip/opt.h"
#if LWIP_ARP /* don't build if not configured for use in lwipopts.h */
#include "lwip/inet.h"
#include "lwip/ip.h"
#include "lwip/stats.h"
#include "lwip/snmp.h"
#include "lwip/dhcp.h"
#include "lwip/autoip.h"
#include "netif/etharp.h"
#if PPPOE_SUPPORT
#include "netif/ppp_oe.h"
#endif /* PPPOE_SUPPORT */
#include <string.h>
/** the time an ARP entry stays valid after its last update,
* for ARP_TMR_INTERVAL = 5000, this is
* (240 * 5) seconds = 20 minutes.
*/
#define ARP_MAXAGE 240
/** the time an ARP entry stays pending after first request,
* for ARP_TMR_INTERVAL = 5000, this is
* (2 * 5) seconds = 10 seconds.
*
* @internal Keep this number at least 2, otherwise it might
* run out instantly if the timeout occurs directly after a request.
*/
#define ARP_MAXPENDING 2
#define HWTYPE_ETHERNET 1
#define ARPH_HWLEN(hdr) (ntohs((hdr)->_hwlen_protolen) >> 8)
#define ARPH_PROTOLEN(hdr) (ntohs((hdr)->_hwlen_protolen) & 0xff)
#define ARPH_HWLEN_SET(hdr, len) (hdr)->_hwlen_protolen = htons(ARPH_PROTOLEN(hdr) | ((len) << 8))
#define ARPH_PROTOLEN_SET(hdr, len) (hdr)->_hwlen_protolen = htons((len) | (ARPH_HWLEN(hdr) << 8))
enum etharp_state {
ETHARP_STATE_EMPTY = 0,
ETHARP_STATE_PENDING,
ETHARP_STATE_STABLE
};
struct etharp_entry {
#if ARP_QUEUEING
/**
* Pointer to queue of pending outgoing packets on this ARP entry.
*/
struct etharp_q_entry *q;
#endif
struct ip_addr ipaddr;
struct eth_addr ethaddr;
enum etharp_state state;
u8_t ctime;
struct netif *netif;
};
const struct eth_addr ethbroadcast = {{0xff,0xff,0xff,0xff,0xff,0xff}};
const struct eth_addr ethzero = {{0,0,0,0,0,0}};
static struct etharp_entry arp_table[ARP_TABLE_SIZE];
#if !LWIP_NETIF_HWADDRHINT
static u8_t etharp_cached_entry;
#endif
/**
* Try hard to create a new entry - we want the IP address to appear in
* the cache (even if this means removing an active entry or so). */
#define ETHARP_TRY_HARD 1
#define ETHARP_FIND_ONLY 2
#if LWIP_NETIF_HWADDRHINT
#define NETIF_SET_HINT(netif, hint) if (((netif) != NULL) && ((netif)->addr_hint != NULL)) \
*((netif)->addr_hint) = (hint);
static s8_t find_entry(struct ip_addr *ipaddr, u8_t flags, struct netif *netif);
#else /* LWIP_NETIF_HWADDRHINT */
static s8_t find_entry(struct ip_addr *ipaddr, u8_t flags);
#endif /* LWIP_NETIF_HWADDRHINT */
static err_t update_arp_entry(struct netif *netif, struct ip_addr *ipaddr, struct eth_addr *ethaddr, u8_t flags);
/* Some checks, instead of etharp_init(): */
#if (LWIP_ARP && (ARP_TABLE_SIZE > 0x7f))
#error "If you want to use ARP, ARP_TABLE_SIZE must fit in an s8_t, so, you have to reduce it in your lwipopts.h"
#endif
#if ARP_QUEUEING
/**
* Free a complete queue of etharp entries
*
* @param q a qeueue of etharp_q_entry's to free
*/
static void
free_etharp_q(struct etharp_q_entry *q)
{
struct etharp_q_entry *r;
LWIP_ASSERT("q != NULL", q != NULL);
LWIP_ASSERT("q->p != NULL", q->p != NULL);
while (q) {
r = q;
q = q->next;
LWIP_ASSERT("r->p != NULL", (r->p != NULL));
pbuf_free(r->p);
memp_free(MEMP_ARP_QUEUE, r);
}
}
#endif
/**
* Clears expired entries in the ARP table.
*
* This function should be called every ETHARP_TMR_INTERVAL microseconds (5 seconds),
* in order to expire entries in the ARP table.
*/
void
etharp_tmr(void)
{
u8_t i;
LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer\n"));
/* remove expired entries from the ARP table */
for (i = 0; i < ARP_TABLE_SIZE; ++i) {
arp_table[i].ctime++;
if (((arp_table[i].state == ETHARP_STATE_STABLE) &&
(arp_table[i].ctime >= ARP_MAXAGE)) ||
((arp_table[i].state == ETHARP_STATE_PENDING) &&
(arp_table[i].ctime >= ARP_MAXPENDING))) {
/* pending or stable entry has become old! */
LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer: expired %s entry %"U16_F".\n",
arp_table[i].state == ETHARP_STATE_STABLE ? "stable" : "pending", (u16_t)i));
/* clean up entries that have just been expired */
/* remove from SNMP ARP index tree */
snmp_delete_arpidx_tree(arp_table[i].netif, &arp_table[i].ipaddr);
#if ARP_QUEUEING
/* and empty packet queue */
if (arp_table[i].q != NULL) {
/* remove all queued packets */
LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer: freeing entry %"U16_F", packet queue %p.\n", (u16_t)i, (void *)(arp_table[i].q)));
free_etharp_q(arp_table[i].q);
arp_table[i].q = NULL;
}
#endif
/* recycle entry for re-use */
arp_table[i].state = ETHARP_STATE_EMPTY;
}
#if ARP_QUEUEING
/* still pending entry? (not expired) */
if (arp_table[i].state == ETHARP_STATE_PENDING) {
/* resend an ARP query here? */
}
#endif
}
}
/**
* Search the ARP table for a matching or new entry.
*
* If an IP address is given, return a pending or stable ARP entry that matches
* the address. If no match is found, create a new entry with this address set,
* but in state ETHARP_EMPTY. The caller must check and possibly change the
* state of the returned entry.
*
* If ipaddr is NULL, return a initialized new entry in state ETHARP_EMPTY.
*
* In all cases, attempt to create new entries from an empty entry. If no
* empty entries are available and ETHARP_TRY_HARD flag is set, recycle
* old entries. Heuristic choose the least important entry for recycling.
*
* @param ipaddr IP address to find in ARP cache, or to add if not found.
* @param flags
* - ETHARP_TRY_HARD: Try hard to create a entry by allowing recycling of
* active (stable or pending) entries.
*
* @return The ARP entry index that matched or is created, ERR_MEM if no
* entry is found or could be recycled.
*/
static s8_t
#if LWIP_NETIF_HWADDRHINT
find_entry(struct ip_addr *ipaddr, u8_t flags, struct netif *netif)
#else /* LWIP_NETIF_HWADDRHINT */
find_entry(struct ip_addr *ipaddr, u8_t flags)
#endif /* LWIP_NETIF_HWADDRHINT */
{
s8_t old_pending = ARP_TABLE_SIZE, old_stable = ARP_TABLE_SIZE;
s8_t empty = ARP_TABLE_SIZE;
u8_t i = 0, age_pending = 0, age_stable = 0;
#if ARP_QUEUEING
/* oldest entry with packets on queue */
s8_t old_queue = ARP_TABLE_SIZE;
/* its age */
u8_t age_queue = 0;
#endif
/* First, test if the last call to this function asked for the
* same address. If so, we're really fast! */
if (ipaddr) {
/* ipaddr to search for was given */
#if LWIP_NETIF_HWADDRHINT
if ((netif != NULL) && (netif->addr_hint != NULL)) {
/* per-pcb cached entry was given */
u8_t per_pcb_cache = *(netif->addr_hint);
if ((per_pcb_cache < ARP_TABLE_SIZE) && arp_table[per_pcb_cache].state == ETHARP_STATE_STABLE) {
/* the per-pcb-cached entry is stable */
if (ip_addr_cmp(ipaddr, &arp_table[per_pcb_cache].ipaddr)) {
/* per-pcb cached entry was the right one! */
ETHARP_STATS_INC(etharp.cachehit);
return per_pcb_cache;
}
}
}
#else /* #if LWIP_NETIF_HWADDRHINT */
if (arp_table[etharp_cached_entry].state == ETHARP_STATE_STABLE) {
/* the cached entry is stable */
if (ip_addr_cmp(ipaddr, &arp_table[etharp_cached_entry].ipaddr)) {
/* cached entry was the right one! */
ETHARP_STATS_INC(etharp.cachehit);
return etharp_cached_entry;
}
}
#endif /* #if LWIP_NETIF_HWADDRHINT */
}
/**
* a) do a search through the cache, remember candidates
* b) select candidate entry
* c) create new entry
*/
/* a) in a single search sweep, do all of this
* 1) remember the first empty entry (if any)
* 2) remember the oldest stable entry (if any)
* 3) remember the oldest pending entry without queued packets (if any)
* 4) remember the oldest pending entry with queued packets (if any)
* 5) search for a matching IP entry, either pending or stable
* until 5 matches, or all entries are searched for.
*/
for (i = 0; i < ARP_TABLE_SIZE; ++i) {
/* no empty entry found yet and now we do find one? */
if ((empty == ARP_TABLE_SIZE) && (arp_table[i].state == ETHARP_STATE_EMPTY)) {
LWIP_DEBUGF(ETHARP_DEBUG, ("find_entry: found empty entry %"U16_F"\n", (u16_t)i));
/* remember first empty entry */
empty = i;
}
/* pending entry? */
else if (arp_table[i].state == ETHARP_STATE_PENDING) {
/* if given, does IP address match IP address in ARP entry? */
if (ipaddr && ip_addr_cmp(ipaddr, &arp_table[i].ipaddr)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: found matching pending entry %"U16_F"\n", (u16_t)i));
/* found exact IP address match, simply bail out */
#if LWIP_NETIF_HWADDRHINT
NETIF_SET_HINT(netif, i);
#else /* #if LWIP_NETIF_HWADDRHINT */
etharp_cached_entry = i;
#endif /* #if LWIP_NETIF_HWADDRHINT */
return i;
#if ARP_QUEUEING
/* pending with queued packets? */
} else if (arp_table[i].q != NULL) {
if (arp_table[i].ctime >= age_queue) {
old_queue = i;
age_queue = arp_table[i].ctime;
}
#endif
/* pending without queued packets? */
} else {
if (arp_table[i].ctime >= age_pending) {
old_pending = i;
age_pending = arp_table[i].ctime;
}
}
}
/* stable entry? */
else if (arp_table[i].state == ETHARP_STATE_STABLE) {
/* if given, does IP address match IP address in ARP entry? */
if (ipaddr && ip_addr_cmp(ipaddr, &arp_table[i].ipaddr)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: found matching stable entry %"U16_F"\n", (u16_t)i));
/* found exact IP address match, simply bail out */
#if LWIP_NETIF_HWADDRHINT
NETIF_SET_HINT(netif, i);
#else /* #if LWIP_NETIF_HWADDRHINT */
etharp_cached_entry = i;
#endif /* #if LWIP_NETIF_HWADDRHINT */
return i;
/* remember entry with oldest stable entry in oldest, its age in maxtime */
} else if (arp_table[i].ctime >= age_stable) {
old_stable = i;
age_stable = arp_table[i].ctime;
}
}
}
/* { we have no match } => try to create a new entry */
/* no empty entry found and not allowed to recycle? */
if (((empty == ARP_TABLE_SIZE) && ((flags & ETHARP_TRY_HARD) == 0))
/* or don't create new entry, only search? */
|| ((flags & ETHARP_FIND_ONLY) != 0)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: no empty entry found and not allowed to recycle\n"));
return (s8_t)ERR_MEM;
}
/* b) choose the least destructive entry to recycle:
* 1) empty entry
* 2) oldest stable entry
* 3) oldest pending entry without queued packets
* 4) oldest pending entry without queued packets
*
* { ETHARP_TRY_HARD is set at this point }
*/
/* 1) empty entry available? */
if (empty < ARP_TABLE_SIZE) {
i = empty;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: selecting empty entry %"U16_F"\n", (u16_t)i));
}
/* 2) found recyclable stable entry? */
else if (old_stable < ARP_TABLE_SIZE) {
/* recycle oldest stable*/
i = old_stable;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: selecting oldest stable entry %"U16_F"\n", (u16_t)i));
#if ARP_QUEUEING
/* no queued packets should exist on stable entries */
LWIP_ASSERT("arp_table[i].q == NULL", arp_table[i].q == NULL);
#endif
/* 3) found recyclable pending entry without queued packets? */
} else if (old_pending < ARP_TABLE_SIZE) {
/* recycle oldest pending */
i = old_pending;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: selecting oldest pending entry %"U16_F" (without queue)\n", (u16_t)i));
#if ARP_QUEUEING
/* 4) found recyclable pending entry with queued packets? */
} else if (old_queue < ARP_TABLE_SIZE) {
/* recycle oldest pending */
i = old_queue;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("find_entry: selecting oldest pending entry %"U16_F", freeing packet queue %p\n", (u16_t)i, (void *)(arp_table[i].q)));
free_etharp_q(arp_table[i].q);
arp_table[i].q = NULL;
#endif
/* no empty or recyclable entries found */
} else {
return (s8_t)ERR_MEM;
}
/* { empty or recyclable entry found } */
LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE);
if (arp_table[i].state != ETHARP_STATE_EMPTY)
{
snmp_delete_arpidx_tree(arp_table[i].netif, &arp_table[i].ipaddr);
}
/* recycle entry (no-op for an already empty entry) */
arp_table[i].state = ETHARP_STATE_EMPTY;
/* IP address given? */
if (ipaddr != NULL) {
/* set IP address */
ip_addr_set(&arp_table[i].ipaddr, ipaddr);
}
arp_table[i].ctime = 0;
#if LWIP_NETIF_HWADDRHINT
NETIF_SET_HINT(netif, i);
#else /* #if LWIP_NETIF_HWADDRHINT */
etharp_cached_entry = i;
#endif /* #if LWIP_NETIF_HWADDRHINT */
return (err_t)i;
}
/**
* Send an IP packet on the network using netif->linkoutput
* The ethernet header is filled in before sending.
*
* @params netif the lwIP network interface on which to send the packet
* @params p the packet to send, p->payload pointing to the (uninitialized) ethernet header
* @params src the source MAC address to be copied into the ethernet header
* @params dst the destination MAC address to be copied into the ethernet header
* @return ERR_OK if the packet was sent, any other err_t on failure
*/
static err_t
etharp_send_ip(struct netif *netif, struct pbuf *p, struct eth_addr *src, struct eth_addr *dst)
{
struct eth_hdr *ethhdr = p->payload;
u8_t k;
LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!",
(netif->hwaddr_len == ETHARP_HWADDR_LEN));
k = ETHARP_HWADDR_LEN;
while(k > 0) {
k--;
ethhdr->dest.addr[k] = dst->addr[k];
ethhdr->src.addr[k] = src->addr[k];
}
ethhdr->type = htons(ETHTYPE_IP);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_send_ip: sending packet %p\n", (void *)p));
/* send the packet */
return netif->linkoutput(netif, p);
}
/**
* Update (or insert) a IP/MAC address pair in the ARP cache.
*
* If a pending entry is resolved, any queued packets will be sent
* at this point.
*
* @param ipaddr IP address of the inserted ARP entry.
* @param ethaddr Ethernet address of the inserted ARP entry.
* @param flags Defines behaviour:
* - ETHARP_TRY_HARD Allows ARP to insert this as a new item. If not specified,
* only existing ARP entries will be updated.
*
* @return
* - ERR_OK Succesfully updated ARP cache.
* - ERR_MEM If we could not add a new ARP entry when ETHARP_TRY_HARD was set.
* - ERR_ARG Non-unicast address given, those will not appear in ARP cache.
*
* @see pbuf_free()
*/
static err_t
update_arp_entry(struct netif *netif, struct ip_addr *ipaddr, struct eth_addr *ethaddr, u8_t flags)
{
s8_t i;
u8_t k;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | 3, ("update_arp_entry()\n"));
LWIP_ASSERT("netif->hwaddr_len == ETHARP_HWADDR_LEN", netif->hwaddr_len == ETHARP_HWADDR_LEN);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("update_arp_entry: %"U16_F".%"U16_F".%"U16_F".%"U16_F" - %02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F":%02"X16_F"\n",
ip4_addr1(ipaddr), ip4_addr2(ipaddr), ip4_addr3(ipaddr), ip4_addr4(ipaddr),
ethaddr->addr[0], ethaddr->addr[1], ethaddr->addr[2],
ethaddr->addr[3], ethaddr->addr[4], ethaddr->addr[5]));
/* non-unicast address? */
if (ip_addr_isany(ipaddr) ||
ip_addr_isbroadcast(ipaddr, netif) ||
ip_addr_ismulticast(ipaddr)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("update_arp_entry: will not add non-unicast IP address to ARP cache\n"));
return ERR_ARG;
}
/* find or create ARP entry */
#if LWIP_NETIF_HWADDRHINT
i = find_entry(ipaddr, flags, netif);
#else /* LWIP_NETIF_HWADDRHINT */
i = find_entry(ipaddr, flags);
#endif /* LWIP_NETIF_HWADDRHINT */
/* bail out if no entry could be found */
if (i < 0)
return (err_t)i;
/* mark it stable */
arp_table[i].state = ETHARP_STATE_STABLE;
/* record network interface */
arp_table[i].netif = netif;
/* insert in SNMP ARP index tree */
snmp_insert_arpidx_tree(netif, &arp_table[i].ipaddr);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("update_arp_entry: updating stable entry %"S16_F"\n", (s16_t)i));
/* update address */
k = ETHARP_HWADDR_LEN;
while (k > 0) {
k--;
arp_table[i].ethaddr.addr[k] = ethaddr->addr[k];
}
/* reset time stamp */
arp_table[i].ctime = 0;
#if ARP_QUEUEING
/* this is where we will send out queued packets! */
while (arp_table[i].q != NULL) {
struct pbuf *p;
/* remember remainder of queue */
struct etharp_q_entry *q = arp_table[i].q;
/* pop first item off the queue */
arp_table[i].q = q->next;
/* get the packet pointer */
p = q->p;
/* now queue entry can be freed */
memp_free(MEMP_ARP_QUEUE, q);
/* send the queued IP packet */
etharp_send_ip(netif, p, (struct eth_addr*)(netif->hwaddr), ethaddr);
/* free the queued IP packet */
pbuf_free(p);
}
#endif
return ERR_OK;
}
/**
* Finds (stable) ethernet/IP address pair from ARP table
* using interface and IP address index.
* @note the addresses in the ARP table are in network order!
*
* @param netif points to interface index
* @param ipaddr points to the (network order) IP address index
* @param eth_ret points to return pointer
* @param ip_ret points to return pointer
* @return table index if found, -1 otherwise
*/
s8_t
etharp_find_addr(struct netif *netif, struct ip_addr *ipaddr,
struct eth_addr **eth_ret, struct ip_addr **ip_ret)
{
s8_t i;
LWIP_UNUSED_ARG(netif);
#if LWIP_NETIF_HWADDRHINT
i = find_entry(ipaddr, ETHARP_FIND_ONLY, NULL);
#else /* LWIP_NETIF_HWADDRHINT */
i = find_entry(ipaddr, ETHARP_FIND_ONLY);
#endif /* LWIP_NETIF_HWADDRHINT */
if((i >= 0) && arp_table[i].state == ETHARP_STATE_STABLE) {
*eth_ret = &arp_table[i].ethaddr;
*ip_ret = &arp_table[i].ipaddr;
return i;
}
return -1;
}
/**
* Updates the ARP table using the given IP packet.
*
* Uses the incoming IP packet's source address to update the
* ARP cache for the local network. The function does not alter
* or free the packet. This function must be called before the
* packet p is passed to the IP layer.
*
* @param netif The lwIP network interface on which the IP packet pbuf arrived.
* @param p The IP packet that arrived on netif.
*
* @return NULL
*
* @see pbuf_free()
*/
void
etharp_ip_input(struct netif *netif, struct pbuf *p)
{
struct ethip_hdr *hdr;
LWIP_ERROR("netif != NULL", (netif != NULL), return;);
/* Only insert an entry if the source IP address of the
incoming IP packet comes from a host on the local network. */
hdr = p->payload;
/* source is not on the local network? */
if (!ip_addr_netcmp(&(hdr->ip.src), &(netif->ip_addr), &(netif->netmask))) {
/* do nothing */
return;
}
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_ip_input: updating ETHARP table.\n"));
/* update ARP table */
/* @todo We could use ETHARP_TRY_HARD if we think we are going to talk
* back soon (for example, if the destination IP address is ours. */
update_arp_entry(netif, &(hdr->ip.src), &(hdr->eth.src), 0);
}
/**
* Responds to ARP requests to us. Upon ARP replies to us, add entry to cache
* send out queued IP packets. Updates cache with snooped address pairs.
*
* Should be called for incoming ARP packets. The pbuf in the argument
* is freed by this function.
*
* @param netif The lwIP network interface on which the ARP packet pbuf arrived.
* @param ethaddr Ethernet address of netif.
* @param p The ARP packet that arrived on netif. Is freed by this function.
*
* @return NULL
*
* @see pbuf_free()
*/
void
etharp_arp_input(struct netif *netif, struct eth_addr *ethaddr, struct pbuf *p)
{
struct etharp_hdr *hdr;
/* these are aligned properly, whereas the ARP header fields might not be */
struct ip_addr sipaddr, dipaddr;
u8_t i;
u8_t for_us;
#if LWIP_AUTOIP
const u8_t * ethdst_hwaddr;
#endif /* LWIP_AUTOIP */
LWIP_ERROR("netif != NULL", (netif != NULL), return;);
/* drop short ARP packets: we have to check for p->len instead of p->tot_len here
since a struct etharp_hdr is pointed to p->payload, so it musn't be chained! */
if (p->len < sizeof(struct etharp_hdr)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | 1, ("etharp_arp_input: packet dropped, too short (%"S16_F"/%"S16_F")\n", p->tot_len, (s16_t)sizeof(struct etharp_hdr)));
ETHARP_STATS_INC(etharp.lenerr);
ETHARP_STATS_INC(etharp.drop);
pbuf_free(p);
return;
}
hdr = p->payload;
/* RFC 826 "Packet Reception": */
if ((hdr->hwtype != htons(HWTYPE_ETHERNET)) ||
(hdr->_hwlen_protolen != htons((ETHARP_HWADDR_LEN << 8) | sizeof(struct ip_addr))) ||
(hdr->proto != htons(ETHTYPE_IP)) ||
(hdr->ethhdr.type != htons(ETHTYPE_ARP))) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | 1,
("etharp_arp_input: packet dropped, wrong hw type, hwlen, proto, protolen or ethernet type (%"U16_F"/%"U16_F"/%"U16_F"/%"U16_F"/%"U16_F")\n",
hdr->hwtype, ARPH_HWLEN(hdr), hdr->proto, ARPH_PROTOLEN(hdr), hdr->ethhdr.type));
ETHARP_STATS_INC(etharp.proterr);
ETHARP_STATS_INC(etharp.drop);
pbuf_free(p);
return;
}
ETHARP_STATS_INC(etharp.recv);
#if LWIP_AUTOIP
/* We have to check if a host already has configured our random
* created link local address and continously check if there is
* a host with this IP-address so we can detect collisions */
autoip_arp_reply(netif, hdr);
#endif /* LWIP_AUTOIP */
/* Copy struct ip_addr2 to aligned ip_addr, to support compilers without
* structure packing (not using structure copy which breaks strict-aliasing rules). */
SMEMCPY(&sipaddr, &hdr->sipaddr, sizeof(sipaddr));
SMEMCPY(&dipaddr, &hdr->dipaddr, sizeof(dipaddr));
/* this interface is not configured? */
if (netif->ip_addr.addr == 0) {
for_us = 0;
} else {
/* ARP packet directed to us? */
for_us = ip_addr_cmp(&dipaddr, &(netif->ip_addr));
}
/* ARP message directed to us? */
if (for_us) {
/* add IP address in ARP cache; assume requester wants to talk to us.
* can result in directly sending the queued packets for this host. */
update_arp_entry(netif, &sipaddr, &(hdr->shwaddr), ETHARP_TRY_HARD);
/* ARP message not directed to us? */
} else {
/* update the source IP address in the cache, if present */
update_arp_entry(netif, &sipaddr, &(hdr->shwaddr), 0);
}
/* now act on the message itself */
switch (htons(hdr->opcode)) {
/* ARP request? */
case ARP_REQUEST:
/* ARP request. If it asked for our address, we send out a
* reply. In any case, we time-stamp any existing ARP entry,
* and possiby send out an IP packet that was queued on it. */
LWIP_DEBUGF (ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: incoming ARP request\n"));
/* ARP request for our address? */
if (for_us) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: replying to ARP request for our IP address\n"));
/* Re-use pbuf to send ARP reply.
Since we are re-using an existing pbuf, we can't call etharp_raw since
that would allocate a new pbuf. */
hdr->opcode = htons(ARP_REPLY);
hdr->dipaddr = hdr->sipaddr;
hdr->sipaddr = *(struct ip_addr2 *)&netif->ip_addr;
LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!",
(netif->hwaddr_len == ETHARP_HWADDR_LEN));
i = ETHARP_HWADDR_LEN;
#if LWIP_AUTOIP
/* If we are using Link-Local, ARP packets must be broadcast on the
* link layer. (See RFC3927 Section 2.5) */
ethdst_hwaddr = ((netif->autoip != NULL) && (netif->autoip->state != AUTOIP_STATE_OFF)) ? (u8_t*)(ethbroadcast.addr) : hdr->shwaddr.addr;
#endif /* LWIP_AUTOIP */
while(i > 0) {
i--;
hdr->dhwaddr.addr[i] = hdr->shwaddr.addr[i];
#if LWIP_AUTOIP
hdr->ethhdr.dest.addr[i] = ethdst_hwaddr[i];
#else /* LWIP_AUTOIP */
hdr->ethhdr.dest.addr[i] = hdr->shwaddr.addr[i];
#endif /* LWIP_AUTOIP */
hdr->shwaddr.addr[i] = ethaddr->addr[i];
hdr->ethhdr.src.addr[i] = ethaddr->addr[i];
}
/* hwtype, hwaddr_len, proto, protolen and the type in the ethernet header
are already correct, we tested that before */
/* return ARP reply */
netif->linkoutput(netif, p);
/* we are not configured? */
} else if (netif->ip_addr.addr == 0) {
/* { for_us == 0 and netif->ip_addr.addr == 0 } */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: we are unconfigured, ARP request ignored.\n"));
/* request was not directed to us */
} else {
/* { for_us == 0 and netif->ip_addr.addr != 0 } */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: ARP request was not for us.\n"));
}
break;
case ARP_REPLY:
/* ARP reply. We already updated the ARP cache earlier. */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: incoming ARP reply\n"));
#if (LWIP_DHCP && DHCP_DOES_ARP_CHECK)
/* DHCP wants to know about ARP replies from any host with an
* IP address also offered to us by the DHCP server. We do not
* want to take a duplicate IP address on a single network.
* @todo How should we handle redundant (fail-over) interfaces? */
dhcp_arp_reply(netif, &sipaddr);
#endif
break;
default:
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_arp_input: ARP unknown opcode type %"S16_F"\n", htons(hdr->opcode)));
ETHARP_STATS_INC(etharp.err);
break;
}
/* free ARP packet */
pbuf_free(p);
}
/**
* Resolve and fill-in Ethernet address header for outgoing IP packet.
*
* For IP multicast and broadcast, corresponding Ethernet addresses
* are selected and the packet is transmitted on the link.
*
* For unicast addresses, the packet is submitted to etharp_query(). In
* case the IP address is outside the local network, the IP address of
* the gateway is used.
*
* @param netif The lwIP network interface which the IP packet will be sent on.
* @param q The pbuf(s) containing the IP packet to be sent.
* @param ipaddr The IP address of the packet destination.
*
* @return
* - ERR_RTE No route to destination (no gateway to external networks),
* or the return type of either etharp_query() or etharp_send_ip().
*/
err_t
etharp_output(struct netif *netif, struct pbuf *q, struct ip_addr *ipaddr)
{
struct eth_addr *dest, mcastaddr;
/* make room for Ethernet header - should not fail */
if (pbuf_header(q, sizeof(struct eth_hdr)) != 0) {
/* bail out */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | 2, ("etharp_output: could not allocate room for header.\n"));
LINK_STATS_INC(link.lenerr);
return ERR_BUF;
}
/* assume unresolved Ethernet address */
dest = NULL;
/* Determine on destination hardware address. Broadcasts and multicasts
* are special, other IP addresses are looked up in the ARP table. */
/* broadcast destination IP address? */
if (ip_addr_isbroadcast(ipaddr, netif)) {
/* broadcast on Ethernet also */
dest = (struct eth_addr *)ðbroadcast;
/* multicast destination IP address? */
} else if (ip_addr_ismulticast(ipaddr)) {
/* Hash IP multicast address to MAC address.*/
mcastaddr.addr[0] = 0x01;
mcastaddr.addr[1] = 0x00;
mcastaddr.addr[2] = 0x5e;
mcastaddr.addr[3] = ip4_addr2(ipaddr) & 0x7f;
mcastaddr.addr[4] = ip4_addr3(ipaddr);
mcastaddr.addr[5] = ip4_addr4(ipaddr);
/* destination Ethernet address is multicast */
dest = &mcastaddr;
/* unicast destination IP address? */
} else {
/* outside local network? */
if (!ip_addr_netcmp(ipaddr, &(netif->ip_addr), &(netif->netmask))) {
/* interface has default gateway? */
if (netif->gw.addr != 0) {
/* send to hardware address of default gateway IP address */
ipaddr = &(netif->gw);
/* no default gateway available */
} else {
/* no route to destination error (default gateway missing) */
return ERR_RTE;
}
}
/* queue on destination Ethernet address belonging to ipaddr */
return etharp_query(netif, ipaddr, q);
}
/* continuation for multicast/broadcast destinations */
/* obtain source Ethernet address of the given interface */
/* send packet directly on the link */
return etharp_send_ip(netif, q, (struct eth_addr*)(netif->hwaddr), dest);
}
/**
* Send an ARP request for the given IP address and/or queue a packet.
*
* If the IP address was not yet in the cache, a pending ARP cache entry
* is added and an ARP request is sent for the given address. The packet
* is queued on this entry.
*
* If the IP address was already pending in the cache, a new ARP request
* is sent for the given address. The packet is queued on this entry.
*
* If the IP address was already stable in the cache, and a packet is
* given, it is directly sent and no ARP request is sent out.
*
* If the IP address was already stable in the cache, and no packet is
* given, an ARP request is sent out.
*
* @param netif The lwIP network interface on which ipaddr
* must be queried for.
* @param ipaddr The IP address to be resolved.
* @param q If non-NULL, a pbuf that must be delivered to the IP address.
* q is not freed by this function.
*
* @note q must only be ONE packet, not a packet queue!
*
* @return
* - ERR_BUF Could not make room for Ethernet header.
* - ERR_MEM Hardware address unknown, and no more ARP entries available
* to query for address or queue the packet.
* - ERR_MEM Could not queue packet due to memory shortage.
* - ERR_RTE No route to destination (no gateway to external networks).
* - ERR_ARG Non-unicast address given, those will not appear in ARP cache.
*
*/
err_t
etharp_query(struct netif *netif, struct ip_addr *ipaddr, struct pbuf *q)
{
struct eth_addr * srcaddr = (struct eth_addr *)netif->hwaddr;
err_t result = ERR_MEM;
s8_t i; /* ARP entry index */
/* non-unicast address? */
if (ip_addr_isbroadcast(ipaddr, netif) ||
ip_addr_ismulticast(ipaddr) ||
ip_addr_isany(ipaddr)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: will not add non-unicast IP address to ARP cache\n"));
return ERR_ARG;
}
/* find entry in ARP cache, ask to create entry if queueing packet */
#if LWIP_NETIF_HWADDRHINT
i = find_entry(ipaddr, ETHARP_TRY_HARD, netif);
#else /* LWIP_NETIF_HWADDRHINT */
i = find_entry(ipaddr, ETHARP_TRY_HARD);
#endif /* LWIP_NETIF_HWADDRHINT */
/* could not find or create entry? */
if (i < 0) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not create ARP entry\n"));
if (q) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: packet dropped\n"));
ETHARP_STATS_INC(etharp.memerr);
}
return (err_t)i;
}
/* mark a fresh entry as pending (we just sent a request) */
if (arp_table[i].state == ETHARP_STATE_EMPTY) {
arp_table[i].state = ETHARP_STATE_PENDING;
}
/* { i is either a STABLE or (new or existing) PENDING entry } */
LWIP_ASSERT("arp_table[i].state == PENDING or STABLE",
((arp_table[i].state == ETHARP_STATE_PENDING) ||
(arp_table[i].state == ETHARP_STATE_STABLE)));
/* do we have a pending entry? or an implicit query request? */
if ((arp_table[i].state == ETHARP_STATE_PENDING) || (q == NULL)) {
/* try to resolve it; send out ARP request */
result = etharp_request(netif, ipaddr);
if (result != ERR_OK) {
/* ARP request couldn't be sent */
/* We don't re-send arp request in etharp_tmr, but we still queue packets,
since this failure could be temporary, and the next packet calling
etharp_query again could lead to sending the queued packets. */
}
}
/* packet given? */
if (q != NULL) {
/* stable entry? */
if (arp_table[i].state == ETHARP_STATE_STABLE) {
/* we have a valid IP->Ethernet address mapping */
/* send the packet */
result = etharp_send_ip(netif, q, srcaddr, &(arp_table[i].ethaddr));
/* pending entry? (either just created or already pending */
} else if (arp_table[i].state == ETHARP_STATE_PENDING) {
#if ARP_QUEUEING /* queue the given q packet */
struct pbuf *p;
int copy_needed = 0;
/* IF q includes a PBUF_REF, PBUF_POOL or PBUF_RAM, we have no choice but
* to copy the whole queue into a new PBUF_RAM (see bug #11400)
* PBUF_ROMs can be left as they are, since ROM must not get changed. */
p = q;
while (p) {
LWIP_ASSERT("no packet queues allowed!", (p->len != p->tot_len) || (p->next == 0));
if(p->type != PBUF_ROM) {
copy_needed = 1;
break;
}
p = p->next;
}
if(copy_needed) {
/* copy the whole packet into new pbufs */
p = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
if(p != NULL) {
if (pbuf_copy(p, q) != ERR_OK) {
pbuf_free(p);
p = NULL;
}
}
} else {
/* referencing the old pbuf is enough */
p = q;
pbuf_ref(p);
}
/* packet could be taken over? */
if (p != NULL) {
/* queue packet ... */
struct etharp_q_entry *new_entry;
/* allocate a new arp queue entry */
new_entry = memp_malloc(MEMP_ARP_QUEUE);
if (new_entry != NULL) {
new_entry->next = 0;
new_entry->p = p;
if(arp_table[i].q != NULL) {
/* queue was already existent, append the new entry to the end */
struct etharp_q_entry *r;
r = arp_table[i].q;
while (r->next != NULL) {
r = r->next;
}
r->next = new_entry;
} else {
/* queue did not exist, first item in queue */
arp_table[i].q = new_entry;
}
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %"S16_F"\n", (void *)q, (s16_t)i));
result = ERR_OK;
} else {
/* the pool MEMP_ARP_QUEUE is empty */
pbuf_free(p);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not queue a copy of PBUF_REF packet %p (out of memory)\n", (void *)q));
/* { result == ERR_MEM } through initialization */
}
} else {
ETHARP_STATS_INC(etharp.memerr);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not queue a copy of PBUF_REF packet %p (out of memory)\n", (void *)q));
/* { result == ERR_MEM } through initialization */
}
#else /* ARP_QUEUEING == 0 */
/* q && state == PENDING && ARP_QUEUEING == 0 => result = ERR_MEM */
/* { result == ERR_MEM } through initialization */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: Ethernet destination address unknown, queueing disabled, packet %p dropped\n", (void *)q));
#endif
}
}
return result;
}
/**
* Send a raw ARP packet (opcode and all addresses can be modified)
*
* @param netif the lwip network interface on which to send the ARP packet
* @param ethsrc_addr the source MAC address for the ethernet header
* @param ethdst_addr the destination MAC address for the ethernet header
* @param hwsrc_addr the source MAC address for the ARP protocol header
* @param ipsrc_addr the source IP address for the ARP protocol header
* @param hwdst_addr the destination MAC address for the ARP protocol header
* @param ipdst_addr the destination IP address for the ARP protocol header
* @param opcode the type of the ARP packet
* @return ERR_OK if the ARP packet has been sent
* ERR_MEM if the ARP packet couldn't be allocated
* any other err_t on failure
*/
#if !LWIP_AUTOIP
static
#endif /* LWIP_AUTOIP */
err_t
etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr,
const struct eth_addr *ethdst_addr,
const struct eth_addr *hwsrc_addr, const struct ip_addr *ipsrc_addr,
const struct eth_addr *hwdst_addr, const struct ip_addr *ipdst_addr,
const u16_t opcode)
{
struct pbuf *p;
err_t result = ERR_OK;
u8_t k; /* ARP entry index */
struct etharp_hdr *hdr;
#if LWIP_AUTOIP
const u8_t * ethdst_hwaddr;
#endif /* LWIP_AUTOIP */
/* allocate a pbuf for the outgoing ARP request packet */
p = pbuf_alloc(PBUF_LINK, sizeof(struct etharp_hdr), PBUF_RAM);
/* could allocate a pbuf for an ARP request? */
if (p == NULL) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | 2, ("etharp_raw: could not allocate pbuf for ARP request.\n"));
ETHARP_STATS_INC(etharp.memerr);
return ERR_MEM;
}
LWIP_ASSERT("check that first pbuf can hold struct etharp_hdr",
(p->len >= sizeof(struct etharp_hdr)));
hdr = p->payload;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_raw: sending raw ARP packet.\n"));
hdr->opcode = htons(opcode);
LWIP_ASSERT("netif->hwaddr_len must be the same as ETHARP_HWADDR_LEN for etharp!",
(netif->hwaddr_len == ETHARP_HWADDR_LEN));
k = ETHARP_HWADDR_LEN;
#if LWIP_AUTOIP
/* If we are using Link-Local, ARP packets must be broadcast on the
* link layer. (See RFC3927 Section 2.5) */
ethdst_hwaddr = ((netif->autoip != NULL) && (netif->autoip->state != AUTOIP_STATE_OFF)) ? (u8_t*)(ethbroadcast.addr) : ethdst_addr->addr;
#endif /* LWIP_AUTOIP */
/* Write MAC-Addresses (combined loop for both headers) */
while(k > 0) {
k--;
/* Write the ARP MAC-Addresses */
hdr->shwaddr.addr[k] = hwsrc_addr->addr[k];
hdr->dhwaddr.addr[k] = hwdst_addr->addr[k];
/* Write the Ethernet MAC-Addresses */
#if LWIP_AUTOIP
hdr->ethhdr.dest.addr[k] = ethdst_hwaddr[k];
#else /* LWIP_AUTOIP */
hdr->ethhdr.dest.addr[k] = ethdst_addr->addr[k];
#endif /* LWIP_AUTOIP */
hdr->ethhdr.src.addr[k] = ethsrc_addr->addr[k];
}
hdr->sipaddr = *(struct ip_addr2 *)ipsrc_addr;
hdr->dipaddr = *(struct ip_addr2 *)ipdst_addr;
hdr->hwtype = htons(HWTYPE_ETHERNET);
hdr->proto = htons(ETHTYPE_IP);
/* set hwlen and protolen together */
hdr->_hwlen_protolen = htons((ETHARP_HWADDR_LEN << 8) | sizeof(struct ip_addr));
hdr->ethhdr.type = htons(ETHTYPE_ARP);
/* send ARP query */
result = netif->linkoutput(netif, p);
ETHARP_STATS_INC(etharp.xmit);
/* free ARP query packet */
pbuf_free(p);
p = NULL;
/* could not allocate pbuf for ARP request */
return result;
}
/**
* Send an ARP request packet asking for ipaddr.
*
* @param netif the lwip network interface on which to send the request
* @param ipaddr the IP address for which to ask
* @return ERR_OK if the request has been sent
* ERR_MEM if the ARP packet couldn't be allocated
* any other err_t on failure
*/
err_t
etharp_request(struct netif *netif, struct ip_addr *ipaddr)
{
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_request: sending ARP request.\n"));
return etharp_raw(netif, (struct eth_addr *)netif->hwaddr, ðbroadcast,
(struct eth_addr *)netif->hwaddr, &netif->ip_addr, ðzero,
ipaddr, ARP_REQUEST);
}
/**
* Process received ethernet frames. Using this function instead of directly
* calling ip_input and passing ARP frames through etharp in ethernetif_input,
* the ARP cache is protected from concurrent access.
*
* @param p the recevied packet, p->payload pointing to the ethernet header
* @param netif the network interface on which the packet was received
*/
err_t
ethernet_input(struct pbuf *p, struct netif *netif)
{
struct eth_hdr* ethhdr;
/* points to packet payload, which starts with an Ethernet header */
ethhdr = p->payload;
switch (htons(ethhdr->type)) {
/* IP packet? */
case ETHTYPE_IP:
#if ETHARP_TRUST_IP_MAC
/* update ARP table */
etharp_ip_input(netif, p);
#endif /* ETHARP_TRUST_IP_MAC */
/* skip Ethernet header */
if(pbuf_header(p, -(s16_t)sizeof(struct eth_hdr))) {
LWIP_ASSERT("Can't move over header in packet", 0);
pbuf_free(p);
p = NULL;
} else {
/* pass to IP layer */
ip_input(p, netif);
}
break;
case ETHTYPE_ARP:
/* pass p to ARP module */
etharp_arp_input(netif, (struct eth_addr*)(netif->hwaddr), p);
break;
#if PPPOE_SUPPORT
case ETHTYPE_PPPOEDISC: /* PPP Over Ethernet Discovery Stage */
pppoe_disc_input(netif, p);
break;
case ETHTYPE_PPPOE: /* PPP Over Ethernet Session Stage */
pppoe_data_input(netif, p);
break;
#endif /* PPPOE_SUPPORT */
default:
pbuf_free(p);
p = NULL;
break;
}
/* This means the pbuf is freed or consumed,
so the caller doesn't have to free it again */
return ERR_OK;
}
#endif /* LWIP_ARP */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/etharp.c | C | oos | 44,344 |
/**
* @file
* Loop Interface
*
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include "lwip/opt.h"
#if LWIP_HAVE_LOOPIF
#include "netif/loopif.h"
#include "lwip/pbuf.h"
#include "lwip/snmp.h"
#include <string.h>
#if !LWIP_LOOPIF_MULTITHREADING
#include "lwip/sys.h"
#include "lwip/mem.h"
/* helper struct for the linked list of pbufs */
struct loopif_private {
struct pbuf *first;
struct pbuf *last;
};
/**
* Call loopif_poll() in the main loop of your application. This is to prevent
* reentering non-reentrant functions like tcp_input(). Packets passed to
* loopif_output() are put on a list that is passed to netif->input() by
* loopif_poll().
*
* @param netif the lwip network interface structure for this loopif
*/
void
loopif_poll(struct netif *netif)
{
SYS_ARCH_DECL_PROTECT(lev);
struct pbuf *in, *in_end;
struct loopif_private *priv = (struct loopif_private*)netif->state;
LWIP_ERROR("priv != NULL", (priv != NULL), return;);
do {
/* Get a packet from the list. With SYS_LIGHTWEIGHT_PROT=1, this is protected */
SYS_ARCH_PROTECT(lev);
in = priv->first;
if(in) {
in_end = in;
while(in_end->len != in_end->tot_len) {
LWIP_ASSERT("bogus pbuf: len != tot_len but next == NULL!", in_end->next != NULL);
in_end = in_end->next;
}
/* 'in_end' now points to the last pbuf from 'in' */
if(in_end == priv->last) {
/* this was the last pbuf in the list */
priv->first = priv->last = NULL;
} else {
/* pop the pbuf off the list */
priv->first = in_end->next;
LWIP_ASSERT("should not be null since first != last!", priv->first != NULL);
}
}
SYS_ARCH_UNPROTECT(lev);
if(in != NULL) {
if(in_end->next != NULL) {
/* De-queue the pbuf from its successors on the 'priv' list. */
in_end->next = NULL;
}
if(netif->input(in, netif) != ERR_OK) {
pbuf_free(in);
}
/* Don't reference the packet any more! */
in = NULL;
in_end = NULL;
}
/* go on while there is a packet on the list */
} while(priv->first != NULL);
}
#endif /* LWIP_LOOPIF_MULTITHREADING */
/**
* Send an IP packet over the loopback interface.
* The pbuf is simply copied and handed back to netif->input.
* In multithreaded mode, this is done directly since netif->input must put
* the packet on a queue.
* In callback mode, the packet is put on an internal queue and is fed to
* netif->input by loopif_poll().
*
* @param netif the lwip network interface structure for this loopif
* @param p the (IP) packet to 'send'
* @param ipaddr the ip address to send the packet to (not used for loopif)
* @return ERR_OK if the packet has been sent
* ERR_MEM if the pbuf used to copy the packet couldn't be allocated
*/
static err_t
loopif_output(struct netif *netif, struct pbuf *p,
struct ip_addr *ipaddr)
{
#if !LWIP_LOOPIF_MULTITHREADING
SYS_ARCH_DECL_PROTECT(lev);
struct loopif_private *priv;
struct pbuf *last;
#endif /* LWIP_LOOPIF_MULTITHREADING */
struct pbuf *r;
err_t err;
LWIP_UNUSED_ARG(ipaddr);
/* Allocate a new pbuf */
r = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
if (r == NULL) {
return ERR_MEM;
}
/* Copy the whole pbuf queue p into the single pbuf r */
if ((err = pbuf_copy(r, p)) != ERR_OK) {
pbuf_free(r);
r = NULL;
return err;
}
#if LWIP_LOOPIF_MULTITHREADING
/* Multithreading environment, netif->input() is supposed to put the packet
into a mailbox, so we can safely call it here without risking to re-enter
functions that are not reentrant (TCP!!!) */
if(netif->input(r, netif) != ERR_OK) {
pbuf_free(r);
r = NULL;
}
#else /* LWIP_LOOPIF_MULTITHREADING */
/* Raw API without threads: put the packet on a linked list which gets emptied
through calling loopif_poll(). */
priv = (struct loopif_private*)netif->state;
/* let last point to the last pbuf in chain r */
for (last = r; last->next != NULL; last = last->next);
SYS_ARCH_PROTECT(lev);
if(priv->first != NULL) {
LWIP_ASSERT("if first != NULL, last must also be != NULL", priv->last != NULL);
priv->last->next = r;
priv->last = last;
} else {
priv->first = r;
priv->last = last;
}
SYS_ARCH_UNPROTECT(lev);
#endif /* LWIP_LOOPIF_MULTITHREADING */
return ERR_OK;
}
/**
* Initialize a lwip network interface structure for a loopback interface
*
* @param netif the lwip network interface structure for this loopif
* @return ERR_OK if the loopif is initialized
* ERR_MEM if private data couldn't be allocated
*/
err_t
loopif_init(struct netif *netif)
{
#if !LWIP_LOOPIF_MULTITHREADING
struct loopif_private *priv;
priv = (struct loopif_private*)mem_malloc(sizeof(struct loopif_private));
if(priv == NULL)
return ERR_MEM;
priv->first = priv->last = NULL;
netif->state = priv;
#endif /* LWIP_LOOPIF_MULTITHREADING */
/* initialize the snmp variables and counters inside the struct netif
* ifSpeed: no assumption can be made!
*/
NETIF_INIT_SNMP(netif, snmp_ifType_softwareLoopback, 0);
netif->name[0] = 'l';
netif->name[1] = 'o';
netif->output = loopif_output;
return ERR_OK;
}
#endif /* LWIP_HAVE_LOOPIF */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/loopif.c | C | oos | 7,043 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
/*
* This file is a skeleton for developing Ethernet network interface
* drivers for lwIP. Add code to the low_level functions and do a
* search-and-replace for the word "ethernetif" to replace it with
* something that better describes your network interface.
*/
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include "lwip/sys.h"
#include <lwip/stats.h>
#include <lwip/snmp.h>
#include "netif/etharp.h"
#include "91x_enet.h"
// Standard library include
#include <stdio.h>
#include <string.h>
#define netifMTU ( 1500 )
#define netifINTERFACE_TASK_STACK_SIZE ( 350 )
#define netifINTERFACE_TASK_PRIORITY ( configMAX_PRIORITIES - 1 )
#define netifBUFFER_WAIT_ATTEMPTS 10
#define netifBUFFER_WAIT_DELAY (10 / portTICK_RATE_MS)
#define IFNAME0 'e'
#define IFNAME1 'n'
/* The time to block waiting for input. */
#define emacBLOCK_TIME_WAITING_FOR_INPUT ( ( portTickType ) 100 )
/* Interrupt status bit definition. */
#define DMI_RX_CURRENT_DONE 0x8000
static u8_t s_rxBuff[1520];
/* The semaphore used by the ISR to wake the lwIP task. */
static xSemaphoreHandle s_xSemaphore = NULL;
struct ethernetif {
struct eth_addr *ethaddr;
/* Add whatever per-interface state that is needed here. */
};
/* Forward declarations. */
static void ethernetif_input( void *pParams );
u8 *pcGetNextBuffer( void );
/**
* In this function, the hardware should be initialized.
* Called from ethernetif_init().
*
* @param netif the already initialized lwip network interface structure
* for this ethernetif
*/
static void low_level_init(struct netif *netif)
{
/* set MAC hardware address length */
netif->hwaddr_len = ETHARP_HWADDR_LEN;
/* set MAC hardware address */
netif->hwaddr[0] = MAC_ADDR0;
netif->hwaddr[1] = MAC_ADDR1;
netif->hwaddr[2] = MAC_ADDR2;
netif->hwaddr[3] = MAC_ADDR3;
netif->hwaddr[4] = MAC_ADDR4;
netif->hwaddr[5] = MAC_ADDR5;
/* maximum transfer unit */
netif->mtu = netifMTU;
// device capabilities.
// don't set NETIF_FLAG_ETHARP if this device is not an ethernet one
netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP;
/* Do whatever else is needed to initialize interface. */
if( s_xSemaphore == NULL )
{
vSemaphoreCreateBinary( s_xSemaphore );
xSemaphoreTake( s_xSemaphore, 0);
}
/* Initialise the MAC. */
ENET_InitClocksGPIO();
ENET_Init(PHY_AUTO_NEGOTIATION);
ENET_Start();
portENTER_CRITICAL();
{
/*set MAC physical*/
ENET_MAC->MAH = (MAC_ADDR5<<8) + MAC_ADDR4;
ENET_MAC->MAL = (MAC_ADDR3<<24) + (MAC_ADDR2<<16) + (MAC_ADDR1<<8) + MAC_ADDR0;
VIC_Config( ENET_ITLine, VIC_IRQ, 1 );
VIC_ITCmd( ENET_ITLine, ENABLE );
ENET_DMA->ISR = DMI_RX_CURRENT_DONE;
ENET_DMA->IER = DMI_RX_CURRENT_DONE;
}
portEXIT_CRITICAL();
netif->flags |= NETIF_FLAG_LINK_UP;
/* Create the task that handles the EMAC. */
xTaskCreate( ethernetif_input, ( signed portCHAR * ) "ETH_INT", netifINTERFACE_TASK_STACK_SIZE, (void *)netif, netifINTERFACE_TASK_PRIORITY, NULL );
}
/**
* This function should do the actual transmission of the packet. The packet is
* contained in the pbuf that is passed to the function. This pbuf
* might be chained.
*
* @param netif the lwip network interface structure for this ethernetif
* @param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
* @return ERR_OK if the packet could be sent
* an err_t value if the packet couldn't be sent
*
* @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
* strange results. You might consider waiting for space in the DMA queue
* to become availale since the stack doesn't retry to send a packet
* dropped because of memory failure (except for the TCP timers).
*/
static err_t low_level_output(struct netif *netif, struct pbuf *p)
{
struct pbuf *q;
u32_t l = 0;
unsigned portCHAR *pcTxData;
#if ETH_PAD_SIZE
pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
#endif
/* Get a DMA buffer into which we can write the data to send. */
for( int i = 0; i < netifBUFFER_WAIT_ATTEMPTS; i++ )
{
pcTxData = pcGetNextBuffer();
if( pcTxData ){
break;
} else {
vTaskDelay( netifBUFFER_WAIT_DELAY );
}
}
if (pcTxData == NULL) {
portNOP();
return ERR_BUF;
}
else {
for(q = p; q != NULL; q = q->next) {
/* Send the data from the pbuf to the interface, one pbuf at a
time. The size of the data in each pbuf is kept in the ->len
variable. */
vTaskSuspendAll();
memcpy(&pcTxData[l], (u8_t*)q->payload, q->len);
xTaskResumeAll();
l += q->len;
}
}
ENET_TxPkt( &pcTxData, l );
#if ETH_PAD_SIZE
pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif
LINK_STATS_INC(link.xmit);
return ERR_OK;
}
/**
* Should allocate a pbuf and transfer the bytes of the incoming
* packet from the interface into the pbuf.
*
* @param netif the lwip network interface structure for this ethernetif
* @return a pbuf filled with the received packet (including MAC header)
* NULL on memory error
*/
static struct pbuf *low_level_input(struct netif *netif)
{
struct pbuf *p, *q;
u16_t len, l;
l = 0;
p = NULL;
/* Obtain the size of the packet and put it into the "len"
variable. */
len = ENET_HandleRxPkt(s_rxBuff);
if(len)
{
#if ETH_PAD_SIZE
len += ETH_PAD_SIZE; /* allow room for Ethernet padding */
#endif
/* We allocate a pbuf chain of pbufs from the pool. */
p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
if (p != NULL) {
#if ETH_PAD_SIZE
pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
#endif
/* We iterate over the pbuf chain until we have read the entire
* packet into the pbuf. */
for(q = p; q != NULL; q = q->next) {
/* Read enough bytes to fill this pbuf in the chain. The
* available data in the pbuf is given by the q->len
* variable. */
vTaskSuspendAll();
memcpy((u8_t*)q->payload, &s_rxBuff[l], q->len);
xTaskResumeAll();
l = l + q->len;
}
#if ETH_PAD_SIZE
pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif
LINK_STATS_INC(link.recv);
} else {
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
} /* End else */
} /* End if */
return p;
}
/**
* This function should be called when a packet is ready to be read
* from the interface. It uses the function low_level_input() that
* should handle the actual reception of bytes from the network
* interface.Then the type of the received packet is determined and
* the appropriate input function is called.
*
* @param netif the lwip network interface structure for this ethernetif
*/
static void ethernetif_input( void *pParams )
{
struct netif *netif;
struct ethernetif *ethernetif;
struct eth_hdr *ethhdr;
struct pbuf *p;
netif = (struct netif*) pParams;
ethernetif = netif->state;
for( ;; )
{
do
{
/* move received packet into a new pbuf */
p = low_level_input( netif );
if( p == NULL )
{
/* No packet could be read. Wait a for an interrupt to tell us
there is more data available. */
xSemaphoreTake( s_xSemaphore, emacBLOCK_TIME_WAITING_FOR_INPUT );
}
} while( p == NULL );
/* points to packet payload, which starts with an Ethernet header */
ethhdr = p->payload;
switch (htons(ethhdr->type)) {
/* IP or ARP packet? */
case ETHTYPE_IP:
/* full packet send to tcpip_thread to process */
if (netif->input(p, netif) != ERR_OK)
{
LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n"));
pbuf_free(p);
p = NULL;
}
break;
case ETHTYPE_ARP:
#if ETHARP_TRUST_IP_MAC
etharp_ip_input(netif, p);
#endif
etharp_arp_input(netif, ethernetif->ethaddr, p);
break;
default:
pbuf_free(p);
p = NULL;
break;
}
}
}
/**
* Should be called at the beginning of the program to set up the
* network interface. It calls the function low_level_init() to do the
* actual setup of the hardware.
*
* This function should be passed as a parameter to netif_add().
*
* @param netif the lwip network interface structure for this ethernetif
* @return ERR_OK if the loopif is initialized
* ERR_MEM if private data couldn't be allocated
* any other err_t on error
*/
err_t
ethernetif_init(struct netif *netif)
{
struct ethernetif *ethernetif;
LWIP_ASSERT("netif != NULL", (netif != NULL));
ethernetif = mem_malloc(sizeof(struct ethernetif));
if (ethernetif == NULL)
{
LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_init: out of memory\n"));
return ERR_MEM;
}
#if LWIP_NETIF_HOSTNAME
/* Initialize interface hostname */
netif->hostname = "lwip";
#endif /* LWIP_NETIF_HOSTNAME */
/*
* Initialize the snmp variables and counters inside the struct netif.
* The last argument should be replaced with your link speed, in units
* of bits per second.
*/
NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 100);
netif->state = ethernetif;
netif->name[0] = IFNAME0;
netif->name[1] = IFNAME1;
/* We directly use etharp_output() here to save a function call.
* You can instead declare your own function an call etharp_output()
* from it if you have to do some checks before sending (e.g. if link
* is available...)
*/
netif->output = etharp_output;
netif->linkoutput = low_level_output;
ethernetif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]);
low_level_init(netif);
return ERR_OK;
}
/*-----------------------------------------------------------*/
void ENET_IRQHandler(void)
{
portBASE_TYPE xSwitchRequired;
/* Give the semaphore in case the lwIP task needs waking. */
xSwitchRequired = xSemaphoreGiveFromISR( s_xSemaphore, &xSwitchRequired );
/* Clear the interrupt. */
ENET_DMA->ISR = DMI_RX_CURRENT_DONE;
/* Switch tasks if necessary. */
portEND_SWITCHING_ISR( xSwitchRequired );
}
/*-----------------------------------------------------------*/
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/netif/stf91x_ethernetif.c | C | oos | 12,032 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_IP_ADDR_H__
#define __LWIP_IP_ADDR_H__
#include "lwip/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
#define IP_ADDR_ANY 0
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct ip_addr {
PACK_STRUCT_FIELD(u32_t addr[4]);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/*
* struct ipaddr2 is used in the definition of the ARP packet format in
* order to support compilers that don't have structure packing.
*/
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct ip_addr2 {
PACK_STRUCT_FIELD(u16_t addrw[2]);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define IP6_ADDR(ipaddr, a,b,c,d,e,f,g,h) do { (ipaddr)->addr[0] = htonl((u32_t)((a & 0xffff) << 16) | (b & 0xffff)); \
(ipaddr)->addr[1] = htonl(((c & 0xffff) << 16) | (d & 0xffff)); \
(ipaddr)->addr[2] = htonl(((e & 0xffff) << 16) | (f & 0xffff)); \
(ipaddr)->addr[3] = htonl(((g & 0xffff) << 16) | (h & 0xffff)); } while(0)
u8_t ip_addr_netcmp(struct ip_addr *addr1, struct ip_addr *addr2,
struct ip_addr *mask);
u8_t ip_addr_cmp(struct ip_addr *addr1, struct ip_addr *addr2);
void ip_addr_set(struct ip_addr *dest, struct ip_addr *src);
u8_t ip_addr_isany(struct ip_addr *addr);
#define ip_addr_debug_print(debug, ipaddr) \
LWIP_DEBUGF(debug, ("%"X32_F":%"X32_F":%"X32_F":%"X32_F":%"X32_F":%"X32_F":%"X32_F":%"X32_F"\n", \
(ntohl(ipaddr->addr[0]) >> 16) & 0xffff, \
ntohl(ipaddr->addr[0]) & 0xffff, \
(ntohl(ipaddr->addr[1]) >> 16) & 0xffff, \
ntohl(ipaddr->addr[1]) & 0xffff, \
(ntohl(ipaddr->addr[2]) >> 16) & 0xffff, \
ntohl(ipaddr->addr[2]) & 0xffff, \
(ntohl(ipaddr->addr[3]) >> 16) & 0xffff, \
ntohl(ipaddr->addr[3]) & 0xffff));
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_IP_ADDR_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv6/lwip/ip_addr.h | C | oos | 3,995 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_ICMP_H__
#define __LWIP_ICMP_H__
#include "lwip/opt.h"
#if LWIP_ICMP /* don't build if not configured for use in lwipopts.h */
#include "lwip/pbuf.h"
#include "lwip/netif.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ICMP6_DUR 1
#define ICMP6_TE 3
#define ICMP6_ECHO 128 /* echo */
#define ICMP6_ER 129 /* echo reply */
enum icmp_dur_type {
ICMP_DUR_NET = 0, /* net unreachable */
ICMP_DUR_HOST = 1, /* host unreachable */
ICMP_DUR_PROTO = 2, /* protocol unreachable */
ICMP_DUR_PORT = 3, /* port unreachable */
ICMP_DUR_FRAG = 4, /* fragmentation needed and DF set */
ICMP_DUR_SR = 5 /* source route failed */
};
enum icmp_te_type {
ICMP_TE_TTL = 0, /* time to live exceeded in transit */
ICMP_TE_FRAG = 1 /* fragment reassembly time exceeded */
};
void icmp_input(struct pbuf *p, struct netif *inp);
void icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t);
void icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t);
struct icmp_echo_hdr {
u8_t type;
u8_t icode;
u16_t chksum;
u16_t id;
u16_t seqno;
};
struct icmp_dur_hdr {
u8_t type;
u8_t icode;
u16_t chksum;
u32_t unused;
};
struct icmp_te_hdr {
u8_t type;
u8_t icode;
u16_t chksum;
u32_t unused;
};
#ifdef __cplusplus
}
#endif
#endif /* LWIP_ICMP */
#endif /* __LWIP_ICMP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv6/lwip/icmp.h | C | oos | 3,065 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_IP_H__
#define __LWIP_IP_H__
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#include "lwip/err.h"
#ifdef __cplusplus
extern "C" {
#endif
#define IP_HLEN 40
#define IP_PROTO_ICMP 58
#define IP_PROTO_UDP 17
#define IP_PROTO_UDPLITE 136
#define IP_PROTO_TCP 6
/* This is passed as the destination address to ip_output_if (not
to ip_output), meaning that an IP header already is constructed
in the pbuf. This is used when TCP retransmits. */
#ifdef IP_HDRINCL
#undef IP_HDRINCL
#endif /* IP_HDRINCL */
#define IP_HDRINCL NULL
#if LWIP_NETIF_HWADDRHINT
#define IP_PCB_ADDRHINT ;u8_t addr_hint
#else
#define IP_PCB_ADDRHINT
#endif /* LWIP_NETIF_HWADDRHINT */
/* This is the common part of all PCB types. It needs to be at the
beginning of a PCB type definition. It is located here so that
changes to this common part are made in one location instead of
having to change all PCB structs. */
#define IP_PCB struct ip_addr local_ip; \
struct ip_addr remote_ip; \
/* Socket options */ \
u16_t so_options; \
/* Type Of Service */ \
u8_t tos; \
/* Time To Live */ \
u8_t ttl; \
/* link layer address resolution hint */ \
IP_PCB_ADDRHINT
/* The IPv6 header. */
struct ip_hdr {
#if BYTE_ORDER == LITTLE_ENDIAN
u8_t tclass1:4, v:4;
u8_t flow1:4, tclass2:4;
#else
u8_t v:4, tclass1:4;
u8_t tclass2:8, flow1:4;
#endif
u16_t flow2;
u16_t len; /* payload length */
u8_t nexthdr; /* next header */
u8_t hoplim; /* hop limit (TTL) */
struct ip_addr src, dest; /* source and destination IP addresses */
};
#define IPH_PROTO(hdr) (iphdr->nexthdr)
void ip_init(void);
#include "lwip/netif.h"
struct netif *ip_route(struct ip_addr *dest);
void ip_input(struct pbuf *p, struct netif *inp);
/* source and destination addresses in network byte order, please */
err_t ip_output(struct pbuf *p, struct ip_addr *src, struct ip_addr *dest,
u8_t ttl, u8_t proto);
err_t ip_output_if(struct pbuf *p, struct ip_addr *src, struct ip_addr *dest,
u8_t ttl, u8_t proto,
struct netif *netif);
#if IP_DEBUG
void ip_debug_print(struct pbuf *p);
#endif /* IP_DEBUG */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_IP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv6/lwip/ip.h | C | oos | 4,071 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_INET_H__
#define __LWIP_INET_H__
#include "lwip/opt.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#ifdef __cplusplus
extern "C" {
#endif
u16_t inet_chksum(void *data, u16_t len);
u16_t inet_chksum_pbuf(struct pbuf *p);
u16_t inet_chksum_pseudo(struct pbuf *p,
struct ip_addr *src, struct ip_addr *dest,
u8_t proto, u32_t proto_len);
u32_t inet_addr(const char *cp);
s8_t inet_aton(const char *cp, struct in_addr *addr);
#ifndef _MACHINE_ENDIAN_H_
#ifndef _NETINET_IN_H
#ifndef _LINUX_BYTEORDER_GENERIC_H
u16_t htons(u16_t n);
u16_t ntohs(u16_t n);
u32_t htonl(u32_t n);
u32_t ntohl(u32_t n);
#endif /* _LINUX_BYTEORDER_GENERIC_H */
#endif /* _NETINET_IN_H */
#endif /* _MACHINE_ENDIAN_H_ */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_INET_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv6/lwip/inet.h | C | oos | 2,467 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_STATS_H__
#define __LWIP_STATS_H__
#include "lwip/opt.h"
#include "lwip/mem.h"
#include "lwip/memp.h"
#ifdef __cplusplus
extern "C" {
#endif
#if LWIP_STATS
#ifndef LWIP_STATS_LARGE
#define LWIP_STATS_LARGE 0
#endif
#if LWIP_STATS_LARGE
#define STAT_COUNTER u32_t
#define STAT_COUNTER_F U32_F
#else
#define STAT_COUNTER u16_t
#define STAT_COUNTER_F U16_F
#endif
struct stats_proto {
STAT_COUNTER xmit; /* Transmitted packets. */
STAT_COUNTER rexmit; /* Retransmitted packets. */
STAT_COUNTER recv; /* Received packets. */
STAT_COUNTER fw; /* Forwarded packets. */
STAT_COUNTER drop; /* Dropped packets. */
STAT_COUNTER chkerr; /* Checksum error. */
STAT_COUNTER lenerr; /* Invalid length error. */
STAT_COUNTER memerr; /* Out of memory error. */
STAT_COUNTER rterr; /* Routing error. */
STAT_COUNTER proterr; /* Protocol error. */
STAT_COUNTER opterr; /* Error in options. */
STAT_COUNTER err; /* Misc error. */
STAT_COUNTER cachehit;
};
struct stats_igmp {
STAT_COUNTER lenerr; /* Invalid length error. */
STAT_COUNTER chkerr; /* Checksum error. */
STAT_COUNTER v1_rxed; /* */
STAT_COUNTER join_sent; /* */
STAT_COUNTER leave_sent; /* */
STAT_COUNTER unicast_query; /* */
STAT_COUNTER report_sent; /* */
STAT_COUNTER report_rxed; /* */
STAT_COUNTER group_query_rxed; /* */
};
struct stats_mem {
mem_size_t avail;
mem_size_t used;
mem_size_t max;
mem_size_t err;
};
struct stats_syselem {
STAT_COUNTER used;
STAT_COUNTER max;
STAT_COUNTER err;
};
struct stats_sys {
struct stats_syselem sem;
struct stats_syselem mbox;
};
struct stats_ {
#if LINK_STATS
struct stats_proto link;
#endif
#if ETHARP_STATS
struct stats_proto etharp;
#endif
#if IPFRAG_STATS
struct stats_proto ip_frag;
#endif
#if IP_STATS
struct stats_proto ip;
#endif
#if ICMP_STATS
struct stats_proto icmp;
#endif
#if IGMP_STATS
struct stats_igmp igmp;
#endif
#if UDP_STATS
struct stats_proto udp;
#endif
#if TCP_STATS
struct stats_proto tcp;
#endif
#if MEM_STATS
struct stats_mem mem;
#endif
#if MEMP_STATS
struct stats_mem memp[MEMP_MAX];
#endif
#if SYS_STATS
struct stats_sys sys;
#endif
};
extern struct stats_ lwip_stats;
#define stats_init() /* Compatibility define, not init needed. */
#define STATS_INC(x) ++lwip_stats.x
#else
#define stats_init()
#define STATS_INC(x)
#endif /* LWIP_STATS */
#if TCP_STATS
#define TCP_STATS_INC(x) STATS_INC(x)
#else
#define TCP_STATS_INC(x)
#endif
#if UDP_STATS
#define UDP_STATS_INC(x) STATS_INC(x)
#else
#define UDP_STATS_INC(x)
#endif
#if ICMP_STATS
#define ICMP_STATS_INC(x) STATS_INC(x)
#else
#define ICMP_STATS_INC(x)
#endif
#if IGMP_STATS
#define IGMP_STATS_INC(x) STATS_INC(x)
#else
#define IGMP_STATS_INC(x)
#endif
#if IP_STATS
#define IP_STATS_INC(x) STATS_INC(x)
#else
#define IP_STATS_INC(x)
#endif
#if IPFRAG_STATS
#define IPFRAG_STATS_INC(x) STATS_INC(x)
#else
#define IPFRAG_STATS_INC(x)
#endif
#if ETHARP_STATS
#define ETHARP_STATS_INC(x) STATS_INC(x)
#else
#define ETHARP_STATS_INC(x)
#endif
#if LINK_STATS
#define LINK_STATS_INC(x) STATS_INC(x)
#else
#define LINK_STATS_INC(x)
#endif
/* Display of statistics */
#if LWIP_STATS_DISPLAY
void stats_display(void);
#else
#define stats_display()
#endif /* LWIP_STATS_DISPLAY */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_STATS_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/stats.h | C | oos | 5,333 |
/*
* Copyright (c) 2001, 2002 Leon Woestenberg <leon.woestenberg@axon.tv>
* Copyright (c) 2001, 2002 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Leon Woestenberg <leon.woestenberg@axon.tv>
*
*/
#ifndef __LWIP_SNMP_H__
#define __LWIP_SNMP_H__
#include "lwip/opt.h"
#include "lwip/netif.h"
#include "lwip/udp.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @see RFC1213, "MIB-II, 6. Definitions"
*/
enum snmp_ifType {
snmp_ifType_other=1, /* none of the following */
snmp_ifType_regular1822,
snmp_ifType_hdh1822,
snmp_ifType_ddn_x25,
snmp_ifType_rfc877_x25,
snmp_ifType_ethernet_csmacd,
snmp_ifType_iso88023_csmacd,
snmp_ifType_iso88024_tokenBus,
snmp_ifType_iso88025_tokenRing,
snmp_ifType_iso88026_man,
snmp_ifType_starLan,
snmp_ifType_proteon_10Mbit,
snmp_ifType_proteon_80Mbit,
snmp_ifType_hyperchannel,
snmp_ifType_fddi,
snmp_ifType_lapb,
snmp_ifType_sdlc,
snmp_ifType_ds1, /* T-1 */
snmp_ifType_e1, /* european equiv. of T-1 */
snmp_ifType_basicISDN,
snmp_ifType_primaryISDN, /* proprietary serial */
snmp_ifType_propPointToPointSerial,
snmp_ifType_ppp,
snmp_ifType_softwareLoopback,
snmp_ifType_eon, /* CLNP over IP [11] */
snmp_ifType_ethernet_3Mbit,
snmp_ifType_nsip, /* XNS over IP */
snmp_ifType_slip, /* generic SLIP */
snmp_ifType_ultra, /* ULTRA technologies */
snmp_ifType_ds3, /* T-3 */
snmp_ifType_sip, /* SMDS */
snmp_ifType_frame_relay
};
#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */
/** SNMP "sysuptime" Interval */
#define SNMP_SYSUPTIME_INTERVAL 10
/** fixed maximum length for object identifier type */
#define LWIP_SNMP_OBJ_ID_LEN 32
/** internal object identifier representation */
struct snmp_obj_id
{
u8_t len;
s32_t id[LWIP_SNMP_OBJ_ID_LEN];
};
/* system */
void snmp_set_sysdesr(u8_t* str, u8_t* len);
void snmp_set_sysobjid(struct snmp_obj_id *oid);
void snmp_get_sysobjid_ptr(struct snmp_obj_id **oid);
void snmp_inc_sysuptime(void);
void snmp_add_sysuptime(u32_t value);
void snmp_get_sysuptime(u32_t *value);
void snmp_set_syscontact(u8_t *ocstr, u8_t *ocstrlen);
void snmp_set_sysname(u8_t *ocstr, u8_t *ocstrlen);
void snmp_set_syslocation(u8_t *ocstr, u8_t *ocstrlen);
/* network interface */
void snmp_add_ifinoctets(struct netif *ni, u32_t value);
void snmp_inc_ifinucastpkts(struct netif *ni);
void snmp_inc_ifinnucastpkts(struct netif *ni);
void snmp_inc_ifindiscards(struct netif *ni);
void snmp_add_ifoutoctets(struct netif *ni, u32_t value);
void snmp_inc_ifoutucastpkts(struct netif *ni);
void snmp_inc_ifoutnucastpkts(struct netif *ni);
void snmp_inc_ifoutdiscards(struct netif *ni);
void snmp_inc_iflist(void);
void snmp_dec_iflist(void);
/* ARP (for atTable and ipNetToMediaTable) */
void snmp_insert_arpidx_tree(struct netif *ni, struct ip_addr *ip);
void snmp_delete_arpidx_tree(struct netif *ni, struct ip_addr *ip);
/* IP */
void snmp_inc_ipinreceives(void);
void snmp_inc_ipinhdrerrors(void);
void snmp_inc_ipinaddrerrors(void);
void snmp_inc_ipforwdatagrams(void);
void snmp_inc_ipinunknownprotos(void);
void snmp_inc_ipindiscards(void);
void snmp_inc_ipindelivers(void);
void snmp_inc_ipoutrequests(void);
void snmp_inc_ipoutdiscards(void);
void snmp_inc_ipoutnoroutes(void);
void snmp_inc_ipreasmreqds(void);
void snmp_inc_ipreasmoks(void);
void snmp_inc_ipreasmfails(void);
void snmp_inc_ipfragoks(void);
void snmp_inc_ipfragfails(void);
void snmp_inc_ipfragcreates(void);
void snmp_inc_iproutingdiscards(void);
void snmp_insert_ipaddridx_tree(struct netif *ni);
void snmp_delete_ipaddridx_tree(struct netif *ni);
void snmp_insert_iprteidx_tree(u8_t dflt, struct netif *ni);
void snmp_delete_iprteidx_tree(u8_t dflt, struct netif *ni);
/* ICMP */
void snmp_inc_icmpinmsgs(void);
void snmp_inc_icmpinerrors(void);
void snmp_inc_icmpindestunreachs(void);
void snmp_inc_icmpintimeexcds(void);
void snmp_inc_icmpinparmprobs(void);
void snmp_inc_icmpinsrcquenchs(void);
void snmp_inc_icmpinredirects(void);
void snmp_inc_icmpinechos(void);
void snmp_inc_icmpinechoreps(void);
void snmp_inc_icmpintimestamps(void);
void snmp_inc_icmpintimestampreps(void);
void snmp_inc_icmpinaddrmasks(void);
void snmp_inc_icmpinaddrmaskreps(void);
void snmp_inc_icmpoutmsgs(void);
void snmp_inc_icmpouterrors(void);
void snmp_inc_icmpoutdestunreachs(void);
void snmp_inc_icmpouttimeexcds(void);
void snmp_inc_icmpoutparmprobs(void);
void snmp_inc_icmpoutsrcquenchs(void);
void snmp_inc_icmpoutredirects(void);
void snmp_inc_icmpoutechos(void);
void snmp_inc_icmpoutechoreps(void);
void snmp_inc_icmpouttimestamps(void);
void snmp_inc_icmpouttimestampreps(void);
void snmp_inc_icmpoutaddrmasks(void);
void snmp_inc_icmpoutaddrmaskreps(void);
/* TCP */
void snmp_inc_tcpactiveopens(void);
void snmp_inc_tcppassiveopens(void);
void snmp_inc_tcpattemptfails(void);
void snmp_inc_tcpestabresets(void);
void snmp_inc_tcpinsegs(void);
void snmp_inc_tcpoutsegs(void);
void snmp_inc_tcpretranssegs(void);
void snmp_inc_tcpinerrs(void);
void snmp_inc_tcpoutrsts(void);
/* UDP */
void snmp_inc_udpindatagrams(void);
void snmp_inc_udpnoports(void);
void snmp_inc_udpinerrors(void);
void snmp_inc_udpoutdatagrams(void);
void snmp_insert_udpidx_tree(struct udp_pcb *pcb);
void snmp_delete_udpidx_tree(struct udp_pcb *pcb);
/* SNMP */
void snmp_inc_snmpinpkts(void);
void snmp_inc_snmpoutpkts(void);
void snmp_inc_snmpinbadversions(void);
void snmp_inc_snmpinbadcommunitynames(void);
void snmp_inc_snmpinbadcommunityuses(void);
void snmp_inc_snmpinasnparseerrs(void);
void snmp_inc_snmpintoobigs(void);
void snmp_inc_snmpinnosuchnames(void);
void snmp_inc_snmpinbadvalues(void);
void snmp_inc_snmpinreadonlys(void);
void snmp_inc_snmpingenerrs(void);
void snmp_add_snmpintotalreqvars(u8_t value);
void snmp_add_snmpintotalsetvars(u8_t value);
void snmp_inc_snmpingetrequests(void);
void snmp_inc_snmpingetnexts(void);
void snmp_inc_snmpinsetrequests(void);
void snmp_inc_snmpingetresponses(void);
void snmp_inc_snmpintraps(void);
void snmp_inc_snmpouttoobigs(void);
void snmp_inc_snmpoutnosuchnames(void);
void snmp_inc_snmpoutbadvalues(void);
void snmp_inc_snmpoutgenerrs(void);
void snmp_inc_snmpoutgetrequests(void);
void snmp_inc_snmpoutgetnexts(void);
void snmp_inc_snmpoutsetrequests(void);
void snmp_inc_snmpoutgetresponses(void);
void snmp_inc_snmpouttraps(void);
void snmp_get_snmpgrpid_ptr(struct snmp_obj_id **oid);
void snmp_set_snmpenableauthentraps(u8_t *value);
void snmp_get_snmpenableauthentraps(u8_t *value);
/* LWIP_SNMP support not available */
/* define everything to be empty */
#else
/* system */
#define snmp_set_sysdesr(str, len)
#define snmp_set_sysobjid(oid);
#define snmp_get_sysobjid_ptr(oid)
#define snmp_inc_sysuptime()
#define snmp_add_sysuptime(value)
#define snmp_get_sysuptime(value)
#define snmp_set_syscontact(ocstr, ocstrlen);
#define snmp_set_sysname(ocstr, ocstrlen);
#define snmp_set_syslocation(ocstr, ocstrlen);
/* network interface */
#define snmp_add_ifinoctets(ni,value)
#define snmp_inc_ifinucastpkts(ni)
#define snmp_inc_ifinnucastpkts(ni)
#define snmp_inc_ifindiscards(ni)
#define snmp_add_ifoutoctets(ni,value)
#define snmp_inc_ifoutucastpkts(ni)
#define snmp_inc_ifoutnucastpkts(ni)
#define snmp_inc_ifoutdiscards(ni)
#define snmp_inc_iflist()
#define snmp_dec_iflist()
/* ARP */
#define snmp_insert_arpidx_tree(ni,ip)
#define snmp_delete_arpidx_tree(ni,ip)
/* IP */
#define snmp_inc_ipinreceives()
#define snmp_inc_ipinhdrerrors()
#define snmp_inc_ipinaddrerrors()
#define snmp_inc_ipforwdatagrams()
#define snmp_inc_ipinunknownprotos()
#define snmp_inc_ipindiscards()
#define snmp_inc_ipindelivers()
#define snmp_inc_ipoutrequests()
#define snmp_inc_ipoutdiscards()
#define snmp_inc_ipoutnoroutes()
#define snmp_inc_ipreasmreqds()
#define snmp_inc_ipreasmoks()
#define snmp_inc_ipreasmfails()
#define snmp_inc_ipfragoks()
#define snmp_inc_ipfragfails()
#define snmp_inc_ipfragcreates()
#define snmp_inc_iproutingdiscards()
#define snmp_insert_ipaddridx_tree(ni)
#define snmp_delete_ipaddridx_tree(ni)
#define snmp_insert_iprteidx_tree(dflt, ni)
#define snmp_delete_iprteidx_tree(dflt, ni)
/* ICMP */
#define snmp_inc_icmpinmsgs()
#define snmp_inc_icmpinerrors()
#define snmp_inc_icmpindestunreachs()
#define snmp_inc_icmpintimeexcds()
#define snmp_inc_icmpinparmprobs()
#define snmp_inc_icmpinsrcquenchs()
#define snmp_inc_icmpinredirects()
#define snmp_inc_icmpinechos()
#define snmp_inc_icmpinechoreps()
#define snmp_inc_icmpintimestamps()
#define snmp_inc_icmpintimestampreps()
#define snmp_inc_icmpinaddrmasks()
#define snmp_inc_icmpinaddrmaskreps()
#define snmp_inc_icmpoutmsgs()
#define snmp_inc_icmpouterrors()
#define snmp_inc_icmpoutdestunreachs()
#define snmp_inc_icmpouttimeexcds()
#define snmp_inc_icmpoutparmprobs()
#define snmp_inc_icmpoutsrcquenchs()
#define snmp_inc_icmpoutredirects()
#define snmp_inc_icmpoutechos()
#define snmp_inc_icmpoutechoreps()
#define snmp_inc_icmpouttimestamps()
#define snmp_inc_icmpouttimestampreps()
#define snmp_inc_icmpoutaddrmasks()
#define snmp_inc_icmpoutaddrmaskreps()
/* TCP */
#define snmp_inc_tcpactiveopens()
#define snmp_inc_tcppassiveopens()
#define snmp_inc_tcpattemptfails()
#define snmp_inc_tcpestabresets()
#define snmp_inc_tcpinsegs()
#define snmp_inc_tcpoutsegs()
#define snmp_inc_tcpretranssegs()
#define snmp_inc_tcpinerrs()
#define snmp_inc_tcpoutrsts()
/* UDP */
#define snmp_inc_udpindatagrams()
#define snmp_inc_udpnoports()
#define snmp_inc_udpinerrors()
#define snmp_inc_udpoutdatagrams()
#define snmp_insert_udpidx_tree(pcb)
#define snmp_delete_udpidx_tree(pcb)
/* SNMP */
#define snmp_inc_snmpinpkts()
#define snmp_inc_snmpoutpkts()
#define snmp_inc_snmpinbadversions()
#define snmp_inc_snmpinbadcommunitynames()
#define snmp_inc_snmpinbadcommunityuses()
#define snmp_inc_snmpinasnparseerrs()
#define snmp_inc_snmpintoobigs()
#define snmp_inc_snmpinnosuchnames()
#define snmp_inc_snmpinbadvalues()
#define snmp_inc_snmpinreadonlys()
#define snmp_inc_snmpingenerrs()
#define snmp_add_snmpintotalreqvars(value)
#define snmp_add_snmpintotalsetvars(value)
#define snmp_inc_snmpingetrequests()
#define snmp_inc_snmpingetnexts()
#define snmp_inc_snmpinsetrequests()
#define snmp_inc_snmpingetresponses()
#define snmp_inc_snmpintraps()
#define snmp_inc_snmpouttoobigs()
#define snmp_inc_snmpoutnosuchnames()
#define snmp_inc_snmpoutbadvalues()
#define snmp_inc_snmpoutgenerrs()
#define snmp_inc_snmpoutgetrequests()
#define snmp_inc_snmpoutgetnexts()
#define snmp_inc_snmpoutsetrequests()
#define snmp_inc_snmpoutgetresponses()
#define snmp_inc_snmpouttraps()
#define snmp_get_snmpgrpid_ptr(oid)
#define snmp_set_snmpenableauthentraps(value)
#define snmp_get_snmpenableauthentraps(value)
#endif /* LWIP_SNMP */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_SNMP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/snmp.h | C | oos | 12,761 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_API_MSG_H__
#define __LWIP_API_MSG_H__
#include "lwip/opt.h"
#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */
#include "lwip/ip_addr.h"
#include "lwip/err.h"
#include "lwip/sys.h"
#include "lwip/igmp.h"
#include "lwip/api.h"
#ifdef __cplusplus
extern "C" {
#endif
/* IP addresses and port numbers are expected to be in
* the same byte order as in the corresponding pcb.
*/
/** This struct includes everything that is necessary to execute a function
for a netconn in another thread context (mainly used to process netconns
in the tcpip_thread context to be thread safe). */
struct api_msg_msg {
/** The netconn which to process - always needed: it includes the semaphore
which is used to block the application thread until the function finished. */
struct netconn *conn;
/** Depending on the executed function, one of these union members is used */
union {
/** used for do_send */
struct netbuf *b;
/** used for do_newconn */
struct {
u8_t proto;
} n;
/** used for do_bind and do_connect */
struct {
struct ip_addr *ipaddr;
u16_t port;
} bc;
/** used for do_getaddr */
struct {
struct ip_addr *ipaddr;
u16_t *port;
u8_t local;
} ad;
/** used for do_write */
struct {
const void *dataptr;
int len;
u8_t apiflags;
} w;
/** used ofr do_recv */
struct {
u16_t len;
} r;
#if LWIP_IGMP
/** used for do_join_leave_group */
struct {
struct ip_addr *multiaddr;
struct ip_addr *interface;
enum netconn_igmp join_or_leave;
} jl;
#endif /* LWIP_IGMP */
#if TCP_LISTEN_BACKLOG
struct {
u8_t backlog;
} lb;
#endif /* TCP_LISTEN_BACKLOG */
} msg;
};
/** This struct contains a function to execute in another thread context and
a struct api_msg_msg that serves as an argument for this function.
This is passed to tcpip_apimsg to execute functions in tcpip_thread context. */
struct api_msg {
/** function to execute in tcpip_thread context */
void (* function)(struct api_msg_msg *msg);
/** arguments for this function */
struct api_msg_msg msg;
};
#if LWIP_DNS
/** As do_gethostbyname requires more arguments but doesn't require a netconn,
it has its own struct (to avoid struct api_msg getting bigger than necessary).
do_gethostbyname must be called using tcpip_callback instead of tcpip_apimsg
(see netconn_gethostbyname). */
struct dns_api_msg {
/** Hostname to query or dotted IP address string */
const char *name;
/** Rhe resolved address is stored here */
struct ip_addr *addr;
/** This semaphore is posted when the name is resolved, the application thread
should wait on it. */
sys_sem_t sem;
/** Errors are given back here */
err_t *err;
};
#endif /* LWIP_DNS */
void do_newconn ( struct api_msg_msg *msg);
void do_delconn ( struct api_msg_msg *msg);
void do_bind ( struct api_msg_msg *msg);
void do_connect ( struct api_msg_msg *msg);
void do_disconnect ( struct api_msg_msg *msg);
void do_listen ( struct api_msg_msg *msg);
void do_send ( struct api_msg_msg *msg);
void do_recv ( struct api_msg_msg *msg);
void do_write ( struct api_msg_msg *msg);
void do_getaddr ( struct api_msg_msg *msg);
void do_close ( struct api_msg_msg *msg);
#if LWIP_IGMP
void do_join_leave_group( struct api_msg_msg *msg);
#endif /* LWIP_IGMP */
#if LWIP_DNS
void do_gethostbyname(void *arg);
#endif /* LWIP_DNS */
struct netconn* netconn_alloc(enum netconn_type t, netconn_callback callback);
void netconn_free(struct netconn *conn);
#ifdef __cplusplus
}
#endif
#endif /* LWIP_NETCONN */
#endif /* __LWIP_API_MSG_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/api_msg.h | C | oos | 5,548 |
/*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
*/
#ifndef __LWIP_NETIFAPI_H__
#define __LWIP_NETIFAPI_H__
#include "lwip/opt.h"
#if LWIP_NETIF_API /* don't build if not configured for use in lwipopts.h */
#include "lwip/sys.h"
#include "lwip/netif.h"
#include "lwip/dhcp.h"
#include "lwip/autoip.h"
#ifdef __cplusplus
extern "C" {
#endif
struct netifapi_msg_msg {
#if !LWIP_TCPIP_CORE_LOCKING
sys_sem_t sem;
#endif /* !LWIP_TCPIP_CORE_LOCKING */
err_t err;
struct netif *netif;
union {
struct {
struct ip_addr *ipaddr;
struct ip_addr *netmask;
struct ip_addr *gw;
void *state;
err_t (* init) (struct netif *netif);
err_t (* input)(struct pbuf *p, struct netif *netif);
} add;
struct {
void (* voidfunc)(struct netif *netif);
err_t (* errtfunc)(struct netif *netif);
} common;
} msg;
};
struct netifapi_msg {
void (* function)(struct netifapi_msg_msg *msg);
struct netifapi_msg_msg msg;
};
/* API for application */
err_t netifapi_netif_add ( struct netif *netif,
struct ip_addr *ipaddr,
struct ip_addr *netmask,
struct ip_addr *gw,
void *state,
err_t (* init)(struct netif *netif),
err_t (* input)(struct pbuf *p, struct netif *netif) );
err_t netifapi_netif_common ( struct netif *netif,
void (* voidfunc)(struct netif *netif),
err_t (* errtfunc)(struct netif *netif) );
#define netifapi_netif_remove(n) netifapi_netif_common(n, netif_remove, NULL)
#define netifapi_netif_set_up(n) netifapi_netif_common(n, netif_set_up, NULL)
#define netifapi_netif_set_down(n) netifapi_netif_common(n, netif_set_down, NULL)
#define netifapi_netif_set_default(n) netifapi_netif_common(n, netif_set_default, NULL)
#define netifapi_dhcp_start(n) netifapi_netif_common(n, NULL, dhcp_start)
#define netifapi_dhcp_stop(n) netifapi_netif_common(n, dhcp_stop, NULL)
#define netifapi_autoip_start(n) netifapi_netif_common(n, NULL, autoip_start)
#define netifapi_autoip_stop(n) netifapi_netif_common(n, NULL, autoip_stop)
#ifdef __cplusplus
}
#endif
#endif /* LWIP_NETIF_API */
#endif /* __LWIP_NETIFAPI_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/netifapi.h | C | oos | 3,902 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_SYS_H__
#define __LWIP_SYS_H__
#include "lwip/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
#if NO_SYS
/* For a totally minimal and standalone system, we provide null
definitions of the sys_ functions. */
typedef u8_t sys_sem_t;
typedef u8_t sys_mbox_t;
typedef u8_t sys_prot_t;
struct sys_timeo {u8_t dummy;};
#define sys_init()
#define sys_timeout(m,h,a)
#define sys_untimeout(m,a)
#define sys_sem_new(c) c
#define sys_sem_signal(s)
#define sys_sem_wait(s)
#define sys_sem_wait_timeout(s,t)
#define sys_arch_sem_wait(s,t)
#define sys_sem_free(s)
#define sys_mbox_new(s) 0
#define sys_mbox_fetch(m,d)
#define sys_mbox_tryfetch(m,d)
#define sys_mbox_post(m,d)
#define sys_mbox_trypost(m,d)
#define sys_mbox_free(m)
#define sys_thread_new(n,t,a,s,p)
#else /* NO_SYS */
/** Return code for timeouts from sys_arch_mbox_fetch and sys_arch_sem_wait */
#define SYS_ARCH_TIMEOUT 0xffffffffUL
/* sys_mbox_tryfetch returns SYS_MBOX_EMPTY if appropriate.
* For now we use the same magic value, but we allow this to change in future.
*/
#define SYS_MBOX_EMPTY SYS_ARCH_TIMEOUT
#include "lwip/err.h"
#include "arch/sys_arch.h"
typedef void (* sys_timeout_handler)(void *arg);
struct sys_timeo {
struct sys_timeo *next;
u32_t time;
sys_timeout_handler h;
void *arg;
};
struct sys_timeouts {
struct sys_timeo *next;
};
/* sys_init() must be called before anthing else. */
void sys_init(void);
/*
* sys_timeout():
*
* Schedule a timeout a specified amount of milliseconds in the
* future. When the timeout occurs, the specified timeout handler will
* be called. The handler will be passed the "arg" argument when
* called.
*
*/
void sys_timeout(u32_t msecs, sys_timeout_handler h, void *arg);
void sys_untimeout(sys_timeout_handler h, void *arg);
struct sys_timeouts *sys_arch_timeouts(void);
/* Semaphore functions. */
sys_sem_t sys_sem_new(u8_t count);
void sys_sem_signal(sys_sem_t sem);
u32_t sys_arch_sem_wait(sys_sem_t sem, u32_t timeout);
void sys_sem_free(sys_sem_t sem);
void sys_sem_wait(sys_sem_t sem);
int sys_sem_wait_timeout(sys_sem_t sem, u32_t timeout);
/* Time functions. */
#ifndef sys_msleep
void sys_msleep(u32_t ms); /* only has a (close to) 1 jiffy resolution. */
#endif
#ifndef sys_jiffies
u32_t sys_jiffies(void); /* since power up. */
#endif
/* Mailbox functions. */
sys_mbox_t sys_mbox_new(int size);
void sys_mbox_post(sys_mbox_t mbox, void *msg);
err_t sys_mbox_trypost(sys_mbox_t mbox, void *msg);
u32_t sys_arch_mbox_fetch(sys_mbox_t mbox, void **msg, u32_t timeout);
#ifndef sys_arch_mbox_tryfetch /* Allow port to override with a macro */
u32_t sys_arch_mbox_tryfetch(sys_mbox_t mbox, void **msg);
#endif
/* For now, we map straight to sys_arch implementation. */
#define sys_mbox_tryfetch(mbox, msg) sys_arch_mbox_tryfetch(mbox, msg)
void sys_mbox_free(sys_mbox_t mbox);
void sys_mbox_fetch(sys_mbox_t mbox, void **msg);
/* Thread functions. */
sys_thread_t sys_thread_new(char *name, void (* thread)(void *arg), void *arg, int stacksize, int prio);
/* The following functions are used only in Unix code, and
can be omitted when porting the stack. */
/* Returns the current time in microseconds. */
unsigned long sys_now(void);
#endif /* NO_SYS */
/* Critical Region Protection */
/* These functions must be implemented in the sys_arch.c file.
In some implementations they can provide a more light-weight protection
mechanism than using semaphores. Otherwise semaphores can be used for
implementation */
#ifndef SYS_ARCH_PROTECT
/** SYS_LIGHTWEIGHT_PROT
* define SYS_LIGHTWEIGHT_PROT in lwipopts.h if you want inter-task protection
* for certain critical regions during buffer allocation, deallocation and memory
* allocation and deallocation.
*/
#if SYS_LIGHTWEIGHT_PROT
/** SYS_ARCH_DECL_PROTECT
* declare a protection variable. This macro will default to defining a variable of
* type sys_prot_t. If a particular port needs a different implementation, then
* this macro may be defined in sys_arch.h.
*/
#define SYS_ARCH_DECL_PROTECT(lev) sys_prot_t lev
/** SYS_ARCH_PROTECT
* Perform a "fast" protect. This could be implemented by
* disabling interrupts for an embedded system or by using a semaphore or
* mutex. The implementation should allow calling SYS_ARCH_PROTECT when
* already protected. The old protection level is returned in the variable
* "lev". This macro will default to calling the sys_arch_protect() function
* which should be implemented in sys_arch.c. If a particular port needs a
* different implementation, then this macro may be defined in sys_arch.h
*/
#define SYS_ARCH_PROTECT(lev) lev = sys_arch_protect()
/** SYS_ARCH_UNPROTECT
* Perform a "fast" set of the protection level to "lev". This could be
* implemented by setting the interrupt level to "lev" within the MACRO or by
* using a semaphore or mutex. This macro will default to calling the
* sys_arch_unprotect() function which should be implemented in
* sys_arch.c. If a particular port needs a different implementation, then
* this macro may be defined in sys_arch.h
*/
#define SYS_ARCH_UNPROTECT(lev) sys_arch_unprotect(lev)
sys_prot_t sys_arch_protect(void);
void sys_arch_unprotect(sys_prot_t pval);
#else
#define SYS_ARCH_DECL_PROTECT(lev)
#define SYS_ARCH_PROTECT(lev)
#define SYS_ARCH_UNPROTECT(lev)
#endif /* SYS_LIGHTWEIGHT_PROT */
#endif /* SYS_ARCH_PROTECT */
/*
* Macros to set/get and increase/decrease variables in a thread-safe way.
* Use these for accessing variable that are used from more than one thread.
*/
#ifndef SYS_ARCH_INC
#define SYS_ARCH_INC(var, val) do { \
SYS_ARCH_DECL_PROTECT(old_level); \
SYS_ARCH_PROTECT(old_level); \
var += val; \
SYS_ARCH_UNPROTECT(old_level); \
} while(0)
#endif /* SYS_ARCH_INC */
#ifndef SYS_ARCH_DEC
#define SYS_ARCH_DEC(var, val) do { \
SYS_ARCH_DECL_PROTECT(old_level); \
SYS_ARCH_PROTECT(old_level); \
var -= val; \
SYS_ARCH_UNPROTECT(old_level); \
} while(0)
#endif /* SYS_ARCH_DEC */
#ifndef SYS_ARCH_GET
#define SYS_ARCH_GET(var, ret) do { \
SYS_ARCH_DECL_PROTECT(old_level); \
SYS_ARCH_PROTECT(old_level); \
ret = var; \
SYS_ARCH_UNPROTECT(old_level); \
} while(0)
#endif /* SYS_ARCH_GET */
#ifndef SYS_ARCH_SET
#define SYS_ARCH_SET(var, val) do { \
SYS_ARCH_DECL_PROTECT(old_level); \
SYS_ARCH_PROTECT(old_level); \
var = val; \
SYS_ARCH_UNPROTECT(old_level); \
} while(0)
#endif /* SYS_ARCH_SET */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_SYS_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/sys.h | C | oos | 8,907 |
/*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Simon Goldschmidt
*
*/
#include "lwip/opt.h"
#if LWIP_DNS && LWIP_SOCKET
#include "lwip/sockets.h"
/* some rarely used options */
#ifndef LWIP_DNS_API_DECLARE_H_ERRNO
#define LWIP_DNS_API_DECLARE_H_ERRNO 1
#endif
#ifndef LWIP_DNS_API_DEFINE_ERRORS
#define LWIP_DNS_API_DEFINE_ERRORS 1
#endif
#ifndef LWIP_DNS_API_DECLARE_STRUCTS
#define LWIP_DNS_API_DECLARE_STRUCTS 1
#endif
#if LWIP_DNS_API_DEFINE_ERRORS
/** Errors used by the DNS API functions, h_errno can be one of them */
#define EAI_NONAME 200
#define EAI_SERVICE 201
#define EAI_FAIL 202
#define EAI_MEMORY 203
#define HOST_NOT_FOUND 210
#define NO_DATA 211
#define NO_RECOVERY 212
#define TRY_AGAIN 213
#endif /* LWIP_DNS_API_DEFINE_ERRORS */
#if LWIP_DNS_API_DECLARE_STRUCTS
struct hostent {
char *h_name; /* Official name of the host. */
char **h_aliases; /* A pointer to an array of pointers to alternative host names,
terminated by a null pointer. */
int h_addrtype; /* Address type. */
int h_length; /* The length, in bytes, of the address. */
char **h_addr_list; /* A pointer to an array of pointers to network addresses (in
network byte order) for the host, terminated by a null pointer. */
#define h_addr h_addr_list[0] /* for backward compatibility */
};
struct addrinfo {
int ai_flags; /* Input flags. */
int ai_family; /* Address family of socket. */
int ai_socktype; /* Socket type. */
int ai_protocol; /* Protocol of socket. */
socklen_t ai_addrlen; /* Length of socket address. */
struct sockaddr *ai_addr; /* Socket address of socket. */
char *ai_canonname; /* Canonical name of service location. */
struct addrinfo *ai_next; /* Pointer to next in list. */
};
#endif /* LWIP_DNS_API_DECLARE_STRUCTS */
#if LWIP_DNS_API_DECLARE_H_ERRNO
/* application accessable error code set by the DNS API functions */
extern int h_errno;
#endif /* LWIP_DNS_API_DECLARE_H_ERRNO*/
struct hostent *lwip_gethostbyname(const char *name);
int lwip_gethostbyname_r(const char *name, struct hostent *ret, char *buf,
size_t buflen, struct hostent **result, int *h_errnop);
void lwip_freeaddrinfo(struct addrinfo *ai);
int lwip_getaddrinfo(const char *nodename,
const char *servname,
const struct addrinfo *hints,
struct addrinfo **res);
#if LWIP_COMPAT_SOCKETS
#define gethostbyname(name) lwip_gethostbyname(name)
#define gethostbyname_r(name, ret, buf, buflen, result, h_errnop) \
lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop)
#define freeaddrinfo(addrinfo) lwip_freeaddrinfo(a)
#define getaddrinfo(nodname, servname, hints, res) \
lwip_getaddrinfo(nodname, servname, hints, res)
#endif /* LWIP_COMPAT_SOCKETS */
#endif /* LWIP_DNS && LWIP_SOCKET */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/netdb.h | C | oos | 4,544 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_RAW_H__
#define __LWIP_RAW_H__
#include "lwip/opt.h"
#if LWIP_RAW /* don't build if not configured for use in lwipopts.h */
#include "lwip/pbuf.h"
#include "lwip/inet.h"
#include "lwip/ip.h"
#include "lwip/ip_addr.h"
#ifdef __cplusplus
extern "C" {
#endif
struct raw_pcb {
/* Common members of all PCB types */
IP_PCB;
struct raw_pcb *next;
u8_t protocol;
/* receive callback function
* @param arg user supplied argument (raw_pcb.recv_arg)
* @param pcb the raw_pcb which received data
* @param p the packet buffer that was received
* @param addr the remote IP address from which the packet was received
* @return 1 if the packet was 'eaten' (aka. deleted),
* 0 if the packet lives on
* If returning 1, the callback is responsible for freeing the pbuf
* if it's not used any more.
*/
u8_t (* recv)(void *arg, struct raw_pcb *pcb, struct pbuf *p,
struct ip_addr *addr);
/* user-supplied argument for the recv callback */
void *recv_arg;
};
/* The following functions is the application layer interface to the
RAW code. */
struct raw_pcb * raw_new (u8_t proto);
void raw_remove (struct raw_pcb *pcb);
err_t raw_bind (struct raw_pcb *pcb, struct ip_addr *ipaddr);
err_t raw_connect (struct raw_pcb *pcb, struct ip_addr *ipaddr);
void raw_recv (struct raw_pcb *pcb,
u8_t (* recv)(void *arg, struct raw_pcb *pcb,
struct pbuf *p,
struct ip_addr *addr),
void *recv_arg);
err_t raw_sendto (struct raw_pcb *pcb, struct pbuf *p, struct ip_addr *ipaddr);
err_t raw_send (struct raw_pcb *pcb, struct pbuf *p);
/* The following functions are the lower layer interface to RAW. */
u8_t raw_input (struct pbuf *p, struct netif *inp);
#define raw_init() /* Compatibility define, not init needed. */
#ifdef __cplusplus
}
#endif
#endif /* LWIP_RAW */
#endif /* __LWIP_RAW_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/raw.h | C | oos | 3,814 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_MEMP_H__
#define __LWIP_MEMP_H__
#include "lwip/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Create the list of all memory pools managed by memp. MEMP_MAX represents a NULL pool at the end */
typedef enum {
#define LWIP_MEMPOOL(name,num,size,desc) MEMP_##name,
#include "lwip/memp_std.h"
MEMP_MAX
} memp_t;
#if MEM_USE_POOLS
/* Use a helper type to get the start and end of the user "memory pools" for mem_malloc */
typedef enum {
/* Get the first (via:
MEMP_POOL_HELPER_START = ((u8_t) 1*MEMP_POOL_A + 0*MEMP_POOL_B + 0*MEMP_POOL_C + 0)*/
MEMP_POOL_HELPER_FIRST = ((u8_t)
#define LWIP_MEMPOOL(name,num,size,desc)
#define LWIP_MALLOC_MEMPOOL_START 1
#define LWIP_MALLOC_MEMPOOL(num, size) * MEMP_POOL_##size + 0
#define LWIP_MALLOC_MEMPOOL_END
#include "lwip/memp_std.h"
) ,
/* Get the last (via:
MEMP_POOL_HELPER_END = ((u8_t) 0 + MEMP_POOL_A*0 + MEMP_POOL_B*0 + MEMP_POOL_C*1) */
MEMP_POOL_HELPER_LAST = ((u8_t)
#define LWIP_MEMPOOL(name,num,size,desc)
#define LWIP_MALLOC_MEMPOOL_START
#define LWIP_MALLOC_MEMPOOL(num, size) 0 + MEMP_POOL_##size *
#define LWIP_MALLOC_MEMPOOL_END 1
#include "lwip/memp_std.h"
)
} memp_pool_helper_t;
/* The actual start and stop values are here (cast them over)
We use this helper type and these defines so we can avoid using const memp_t values */
#define MEMP_POOL_FIRST ((memp_t) MEMP_POOL_HELPER_FIRST)
#define MEMP_POOL_LAST ((memp_t) MEMP_POOL_HELPER_LAST)
extern const u16_t memp_sizes[MEMP_MAX];
#endif /* MEM_USE_POOLS */
void memp_init(void);
#if MEMP_OVERFLOW_CHECK
void *memp_malloc_fn(memp_t type, const char* file, const int line);
#define memp_malloc(t) memp_malloc_fn((t), __FILE__, __LINE__)
#else
void *memp_malloc(memp_t type);
#endif
void memp_free(memp_t type, void *mem);
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_MEMP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/memp.h | C | oos | 3,553 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_DEF_H__
#define __LWIP_DEF_H__
/* this might define NULL already */
#include "lwip/arch.h"
#define LWIP_MAX(x , y) (((x) > (y)) ? (x) : (y))
#define LWIP_MIN(x , y) (((x) < (y)) ? (x) : (y))
#ifndef NULL
#define NULL ((void *)0)
#endif
#endif /* __LWIP_DEF_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/def.h | C | oos | 1,928 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_MEM_H__
#define __LWIP_MEM_H__
#include "lwip/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
#if MEM_LIBC_MALLOC
#include <stddef.h> /* for size_t */
typedef size_t mem_size_t;
/* aliases for C library malloc() */
#define mem_init()
/* in case C library malloc() needs extra protection,
* allow these defines to be overridden.
*/
#ifndef mem_free
#define mem_free(x) free(x)
#endif
#ifndef mem_malloc
#define mem_malloc(x) malloc(x)
#endif
#ifndef mem_calloc
#define mem_calloc(x, y) calloc(x, y)
#endif
#ifndef mem_realloc
#define mem_realloc(x, size) (x)
#endif
#else /* MEM_LIBC_MALLOC */
/* MEM_SIZE would have to be aligned, but using 64000 here instead of
* 65535 leaves some room for alignment...
*/
#if MEM_SIZE > 64000l
typedef u32_t mem_size_t;
#else
typedef u16_t mem_size_t;
#endif /* MEM_SIZE > 64000 */
#if MEM_USE_POOLS
/** mem_init is not used when using pools instead of a heap */
#define mem_init()
/** mem_realloc is not used when using pools instead of a heap:
we can't free part of a pool element and don't want to copy the rest */
#define mem_realloc(mem, size) (mem)
#else /* MEM_USE_POOLS */
/* lwIP alternative malloc */
void mem_init(void);
void *mem_realloc(void *mem, mem_size_t size);
#endif /* MEM_USE_POOLS */
void *mem_malloc(mem_size_t size);
void *mem_calloc(mem_size_t count, mem_size_t size);
void mem_free(void *mem);
#endif /* MEM_LIBC_MALLOC */
#ifndef LWIP_MEM_ALIGN_SIZE
#define LWIP_MEM_ALIGN_SIZE(size) (((size) + MEM_ALIGNMENT - 1) & ~(MEM_ALIGNMENT-1))
#endif
#ifndef LWIP_MEM_ALIGN
#define LWIP_MEM_ALIGN(addr) ((void *)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) & ~(mem_ptr_t)(MEM_ALIGNMENT-1)))
#endif
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_MEM_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/mem.h | C | oos | 3,437 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_TCPIP_H__
#define __LWIP_TCPIP_H__
#include "lwip/opt.h"
#if !NO_SYS /* don't build if not configured for use in lwipopts.h */
#include "lwip/api_msg.h"
#include "lwip/netifapi.h"
#include "lwip/pbuf.h"
#include "lwip/api.h"
#include "lwip/sys.h"
#ifdef __cplusplus
extern "C" {
#endif
#if LWIP_TCPIP_CORE_LOCKING
/** The global semaphore to lock the stack. */
extern sys_sem_t lock_tcpip_core;
#define LOCK_TCPIP_CORE() sys_sem_wait(lock_tcpip_core)
#define UNLOCK_TCPIP_CORE() sys_sem_signal(lock_tcpip_core)
#define TCPIP_APIMSG(m) tcpip_apimsg_lock(m)
#define TCPIP_APIMSG_ACK(m)
#define TCPIP_NETIFAPI(m) tcpip_netifapi_lock(m)
#define TCPIP_NETIFAPI_ACK(m)
#else
#define LOCK_TCPIP_CORE()
#define UNLOCK_TCPIP_CORE()
#define TCPIP_APIMSG(m) tcpip_apimsg(m)
#define TCPIP_APIMSG_ACK(m) sys_sem_signal(m->conn->op_completed)
#define TCPIP_NETIFAPI(m) tcpip_netifapi(m)
#define TCPIP_NETIFAPI_ACK(m) sys_sem_signal(m->sem)
#endif /* LWIP_TCPIP_CORE_LOCKING */
void tcpip_init(void (* tcpip_init_done)(void *), void *arg);
#if LWIP_NETCONN
err_t tcpip_apimsg(struct api_msg *apimsg);
#if LWIP_TCPIP_CORE_LOCKING
err_t tcpip_apimsg_lock(struct api_msg *apimsg);
#endif /* LWIP_TCPIP_CORE_LOCKING */
#endif /* LWIP_NETCONN */
err_t tcpip_input(struct pbuf *p, struct netif *inp);
#if LWIP_NETIF_API
err_t tcpip_netifapi(struct netifapi_msg *netifapimsg);
#if LWIP_TCPIP_CORE_LOCKING
err_t tcpip_netifapi_lock(struct netifapi_msg *netifapimsg);
#endif /* LWIP_TCPIP_CORE_LOCKING */
#endif /* LWIP_NETIF_API */
err_t tcpip_callback_with_block(void (*f)(void *ctx), void *ctx, u8_t block);
#define tcpip_callback(f,ctx) tcpip_callback_with_block(f,ctx,1)
err_t tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg);
#define tcpip_untimeout(h, arg) tcpip_timeout(0xffffffff, h, arg)
enum tcpip_msg_type {
#if LWIP_NETCONN
TCPIP_MSG_API,
#endif /* LWIP_NETCONN */
TCPIP_MSG_INPKT,
#if LWIP_NETIF_API
TCPIP_MSG_NETIFAPI,
#endif /* LWIP_NETIF_API */
TCPIP_MSG_CALLBACK,
TCPIP_MSG_TIMEOUT
};
struct tcpip_msg {
enum tcpip_msg_type type;
sys_sem_t *sem;
union {
#if LWIP_NETCONN
struct api_msg *apimsg;
#endif /* LWIP_NETCONN */
#if LWIP_NETIF_API
struct netifapi_msg *netifapimsg;
#endif /* LWIP_NETIF_API */
struct {
struct pbuf *p;
struct netif *netif;
} inp;
struct {
void (*f)(void *ctx);
void *ctx;
} cb;
struct {
u32_t msecs;
sys_timeout_handler h;
void *arg;
} tmo;
} msg;
};
#ifdef __cplusplus
}
#endif
#endif /* !NO_SYS */
#endif /* __LWIP_TCPIP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/tcpip.h | C | oos | 4,341 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_DEBUG_H__
#define __LWIP_DEBUG_H__
#include "lwip/arch.h"
/** lower two bits indicate debug level
* - 0 off
* - 1 warning
* - 2 serious
* - 3 severe
*/
#define LWIP_DBG_LEVEL_OFF 0x00
#define LWIP_DBG_LEVEL_WARNING 0x01 /* bad checksums, dropped packets, ... */
#define LWIP_DBG_LEVEL_SERIOUS 0x02 /* memory allocation failures, ... */
#define LWIP_DBG_LEVEL_SEVERE 0x03
#define LWIP_DBG_MASK_LEVEL 0x03
/** flag for LWIP_DEBUGF to enable that debug message */
#define LWIP_DBG_ON 0x80U
/** flag for LWIP_DEBUGF to disable that debug message */
#define LWIP_DBG_OFF 0x00U
/** flag for LWIP_DEBUGF indicating a tracing message (to follow program flow) */
#define LWIP_DBG_TRACE 0x40U
/** flag for LWIP_DEBUGF indicating a state debug message (to follow module states) */
#define LWIP_DBG_STATE 0x20U
/** flag for LWIP_DEBUGF indicating newly added code, not thoroughly tested yet */
#define LWIP_DBG_FRESH 0x10U
/** flag for LWIP_DEBUGF to halt after printing this debug message */
#define LWIP_DBG_HALT 0x08U
#ifndef LWIP_NOASSERT
#define LWIP_ASSERT(x,y) do { if(!(y)) LWIP_PLATFORM_ASSERT(x); } while(0)
#else /* LWIP_NOASSERT */
#define LWIP_ASSERT(x,y)
#endif /* LWIP_NOASSERT */
/** print "m" message only if "e" is true, and execute "h" expression */
#ifndef LWIP_ERROR
#define LWIP_ERROR(m,e,h) do { if (!(e)) { LWIP_PLATFORM_ASSERT(m); h;}} while(0)
#endif /* LWIP_ERROR */
#ifdef LWIP_DEBUG
/** print debug message only if debug message type is enabled...
* AND is of correct type AND is at least LWIP_DBG_LEVEL
*/
#define LWIP_DEBUGF(debug,x) do { \
if ( \
((debug) & LWIP_DBG_ON) && \
((debug) & LWIP_DBG_TYPES_ON) && \
((s16_t)((debug) & LWIP_DBG_MASK_LEVEL) >= LWIP_DBG_MIN_LEVEL)) { \
LWIP_PLATFORM_DIAG(x); \
if ((debug) & LWIP_DBG_HALT) { \
while(1); \
} \
} \
} while(0)
#else /* LWIP_DEBUG */
#define LWIP_DEBUGF(debug,x)
#endif /* LWIP_DEBUG */
#endif /* __LWIP_DEBUG_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/debug.h | C | oos | 4,010 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_INIT_H__
#define __LWIP_INIT_H__
#include "lwip/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Modules initialization */
void lwip_init(void);
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_INIT_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/init.h | C | oos | 1,864 |
/** @file
*/
#ifndef __LWIP_DHCP_H__
#define __LWIP_DHCP_H__
#include "lwip/opt.h"
#if LWIP_DHCP /* don't build if not configured for use in lwipopts.h */
#include "lwip/netif.h"
#include "lwip/udp.h"
#ifdef __cplusplus
extern "C" {
#endif
/** period (in seconds) of the application calling dhcp_coarse_tmr() */
#define DHCP_COARSE_TIMER_SECS 60
/** period (in milliseconds) of the application calling dhcp_coarse_tmr() */
#define DHCP_COARSE_TIMER_MSECS (DHCP_COARSE_TIMER_SECS*1000)
/** period (in milliseconds) of the application calling dhcp_fine_tmr() */
#define DHCP_FINE_TIMER_MSECS 500
struct dhcp
{
/** current DHCP state machine state */
u8_t state;
/** retries of current request */
u8_t tries;
/** transaction identifier of last sent request */
u32_t xid;
/** our connection to the DHCP server */
struct udp_pcb *pcb;
/** (first) pbuf of incoming msg */
struct pbuf *p;
/** incoming msg */
struct dhcp_msg *msg_in;
/** incoming msg options */
struct dhcp_msg *options_in;
/** ingoing msg options length */
u16_t options_in_len;
struct pbuf *p_out; /* pbuf of outcoming msg */
struct dhcp_msg *msg_out; /* outgoing msg */
u16_t options_out_len; /* outgoing msg options length */
u16_t request_timeout; /* #ticks with period DHCP_FINE_TIMER_SECS for request timeout */
u16_t t1_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for renewal time */
u16_t t2_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for rebind time */
struct ip_addr server_ip_addr; /* dhcp server address that offered this lease */
struct ip_addr offered_ip_addr;
struct ip_addr offered_sn_mask;
struct ip_addr offered_gw_addr;
struct ip_addr offered_bc_addr;
#define DHCP_MAX_DNS 2
u32_t dns_count; /* actual number of DNS servers obtained */
struct ip_addr offered_dns_addr[DHCP_MAX_DNS]; /* DNS server addresses */
u32_t offered_t0_lease; /* lease period (in seconds) */
u32_t offered_t1_renew; /* recommended renew time (usually 50% of lease period) */
u32_t offered_t2_rebind; /* recommended rebind time (usually 66% of lease period) */
#if LWIP_DHCP_AUTOIP_COOP
u8_t autoip_coop_state;
#endif
/** Patch #1308
* TODO: See dhcp.c "TODO"s
*/
#if 0
struct ip_addr offered_si_addr;
u8_t *boot_file_name;
#endif
};
/* MUST be compiled with "pack structs" or equivalent! */
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
/** minimum set of fields of any DHCP message */
struct dhcp_msg
{
PACK_STRUCT_FIELD(u8_t op);
PACK_STRUCT_FIELD(u8_t htype);
PACK_STRUCT_FIELD(u8_t hlen);
PACK_STRUCT_FIELD(u8_t hops);
PACK_STRUCT_FIELD(u32_t xid);
PACK_STRUCT_FIELD(u16_t secs);
PACK_STRUCT_FIELD(u16_t flags);
PACK_STRUCT_FIELD(struct ip_addr ciaddr);
PACK_STRUCT_FIELD(struct ip_addr yiaddr);
PACK_STRUCT_FIELD(struct ip_addr siaddr);
PACK_STRUCT_FIELD(struct ip_addr giaddr);
#define DHCP_CHADDR_LEN 16U
PACK_STRUCT_FIELD(u8_t chaddr[DHCP_CHADDR_LEN]);
#define DHCP_SNAME_LEN 64U
PACK_STRUCT_FIELD(u8_t sname[DHCP_SNAME_LEN]);
#define DHCP_FILE_LEN 128U
PACK_STRUCT_FIELD(u8_t file[DHCP_FILE_LEN]);
PACK_STRUCT_FIELD(u32_t cookie);
#define DHCP_MIN_OPTIONS_LEN 68U
/** make sure user does not configure this too small */
#if ((defined(DHCP_OPTIONS_LEN)) && (DHCP_OPTIONS_LEN < DHCP_MIN_OPTIONS_LEN))
# undef DHCP_OPTIONS_LEN
#endif
/** allow this to be configured in lwipopts.h, but not too small */
#if (!defined(DHCP_OPTIONS_LEN))
/** set this to be sufficient for your options in outgoing DHCP msgs */
# define DHCP_OPTIONS_LEN DHCP_MIN_OPTIONS_LEN
#endif
PACK_STRUCT_FIELD(u8_t options[DHCP_OPTIONS_LEN]);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/** start DHCP configuration */
err_t dhcp_start(struct netif *netif);
/** enforce early lease renewal (not needed normally)*/
err_t dhcp_renew(struct netif *netif);
/** release the DHCP lease, usually called before dhcp_stop()*/
err_t dhcp_release(struct netif *netif);
/** stop DHCP configuration */
void dhcp_stop(struct netif *netif);
/** inform server of our manual IP address */
void dhcp_inform(struct netif *netif);
/** if enabled, check whether the offered IP address is not in use, using ARP */
#if DHCP_DOES_ARP_CHECK
void dhcp_arp_reply(struct netif *netif, struct ip_addr *addr);
#endif
/** to be called every minute */
void dhcp_coarse_tmr(void);
/** to be called every half second */
void dhcp_fine_tmr(void);
/** DHCP message item offsets and length */
#define DHCP_MSG_OFS (UDP_DATA_OFS)
#define DHCP_OP_OFS (DHCP_MSG_OFS + 0)
#define DHCP_HTYPE_OFS (DHCP_MSG_OFS + 1)
#define DHCP_HLEN_OFS (DHCP_MSG_OFS + 2)
#define DHCP_HOPS_OFS (DHCP_MSG_OFS + 3)
#define DHCP_XID_OFS (DHCP_MSG_OFS + 4)
#define DHCP_SECS_OFS (DHCP_MSG_OFS + 8)
#define DHCP_FLAGS_OFS (DHCP_MSG_OFS + 10)
#define DHCP_CIADDR_OFS (DHCP_MSG_OFS + 12)
#define DHCP_YIADDR_OFS (DHCP_MSG_OFS + 16)
#define DHCP_SIADDR_OFS (DHCP_MSG_OFS + 20)
#define DHCP_GIADDR_OFS (DHCP_MSG_OFS + 24)
#define DHCP_CHADDR_OFS (DHCP_MSG_OFS + 28)
#define DHCP_SNAME_OFS (DHCP_MSG_OFS + 44)
#define DHCP_FILE_OFS (DHCP_MSG_OFS + 108)
#define DHCP_MSG_LEN 236
#define DHCP_COOKIE_OFS (DHCP_MSG_OFS + DHCP_MSG_LEN)
#define DHCP_OPTIONS_OFS (DHCP_MSG_OFS + DHCP_MSG_LEN + 4)
#define DHCP_CLIENT_PORT 68
#define DHCP_SERVER_PORT 67
/** DHCP client states */
#define DHCP_REQUESTING 1
#define DHCP_INIT 2
#define DHCP_REBOOTING 3
#define DHCP_REBINDING 4
#define DHCP_RENEWING 5
#define DHCP_SELECTING 6
#define DHCP_INFORMING 7
#define DHCP_CHECKING 8
#define DHCP_PERMANENT 9
#define DHCP_BOUND 10
/** not yet implemented #define DHCP_RELEASING 11 */
#define DHCP_BACKING_OFF 12
#define DHCP_OFF 13
/** AUTOIP cooperatation flags */
#define DHCP_AUTOIP_COOP_STATE_OFF 0
#define DHCP_AUTOIP_COOP_STATE_ON 1
#define DHCP_BOOTREQUEST 1
#define DHCP_BOOTREPLY 2
#define DHCP_DISCOVER 1
#define DHCP_OFFER 2
#define DHCP_REQUEST 3
#define DHCP_DECLINE 4
#define DHCP_ACK 5
#define DHCP_NAK 6
#define DHCP_RELEASE 7
#define DHCP_INFORM 8
#define DHCP_HTYPE_ETH 1
#define DHCP_HLEN_ETH 6
#define DHCP_BROADCAST_FLAG 15
#define DHCP_BROADCAST_MASK (1 << DHCP_FLAG_BROADCAST)
/** BootP options */
#define DHCP_OPTION_PAD 0
#define DHCP_OPTION_SUBNET_MASK 1 /* RFC 2132 3.3 */
#define DHCP_OPTION_ROUTER 3
#define DHCP_OPTION_DNS_SERVER 6
#define DHCP_OPTION_HOSTNAME 12
#define DHCP_OPTION_IP_TTL 23
#define DHCP_OPTION_MTU 26
#define DHCP_OPTION_BROADCAST 28
#define DHCP_OPTION_TCP_TTL 37
#define DHCP_OPTION_END 255
/** DHCP options */
#define DHCP_OPTION_REQUESTED_IP 50 /* RFC 2132 9.1, requested IP address */
#define DHCP_OPTION_LEASE_TIME 51 /* RFC 2132 9.2, time in seconds, in 4 bytes */
#define DHCP_OPTION_OVERLOAD 52 /* RFC2132 9.3, use file and/or sname field for options */
#define DHCP_OPTION_MESSAGE_TYPE 53 /* RFC 2132 9.6, important for DHCP */
#define DHCP_OPTION_MESSAGE_TYPE_LEN 1
#define DHCP_OPTION_SERVER_ID 54 /* RFC 2132 9.7, server IP address */
#define DHCP_OPTION_PARAMETER_REQUEST_LIST 55 /* RFC 2132 9.8, requested option types */
#define DHCP_OPTION_MAX_MSG_SIZE 57 /* RFC 2132 9.10, message size accepted >= 576 */
#define DHCP_OPTION_MAX_MSG_SIZE_LEN 2
#define DHCP_OPTION_T1 58 /* T1 renewal time */
#define DHCP_OPTION_T2 59 /* T2 rebinding time */
#define DHCP_OPTION_US 60
#define DHCP_OPTION_CLIENT_ID 61
#define DHCP_OPTION_TFTP_SERVERNAME 66
#define DHCP_OPTION_BOOTFILE 67
/** possible combinations of overloading the file and sname fields with options */
#define DHCP_OVERLOAD_NONE 0
#define DHCP_OVERLOAD_FILE 1
#define DHCP_OVERLOAD_SNAME 2
#define DHCP_OVERLOAD_SNAME_FILE 3
#ifdef __cplusplus
}
#endif
#endif /* LWIP_DHCP */
#endif /*__LWIP_DHCP_H__*/
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/dhcp.h | C | oos | 8,100 |
/**
* @file
* Generic MIB tree structures.
*
* @todo namespace prefixes
*/
/*
* Copyright (c) 2006 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* Author: Christiaan Simons <christiaan.simons@axon.tv>
*/
#ifndef __LWIP_SNMP_STRUCTS_H__
#define __LWIP_SNMP_STRUCTS_H__
#include "lwip/opt.h"
#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */
#include "lwip/snmp.h"
#if SNMP_PRIVATE_MIB
#include "private_mib.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* MIB object instance */
#define MIB_OBJECT_NONE 0
#define MIB_OBJECT_SCALAR 1
#define MIB_OBJECT_TAB 2
/* MIB object access */
#define MIB_OBJECT_READ_ONLY 0
#define MIB_OBJECT_READ_WRITE 1
#define MIB_OBJECT_WRITE_ONLY 2
#define MIB_OBJECT_NOT_ACCESSIBLE 3
/** object definition returned by (get_object_def)() */
struct obj_def
{
/* MIB_OBJECT_NONE (0), MIB_OBJECT_SCALAR (1), MIB_OBJECT_TAB (2) */
u8_t instance;
/* 0 read-only, 1 read-write, 2 write-only, 3 not-accessible */
u8_t access;
/* ASN type for this object */
u8_t asn_type;
/* value length (host length) */
u16_t v_len;
/* length of instance part of supplied object identifier */
u8_t id_inst_len;
/* instance part of supplied object identifier */
s32_t *id_inst_ptr;
};
struct snmp_name_ptr
{
u8_t ident_len;
s32_t *ident;
};
/** MIB const scalar (.0) node */
#define MIB_NODE_SC 0x01
/** MIB const array node */
#define MIB_NODE_AR 0x02
/** MIB array node (mem_malloced from RAM) */
#define MIB_NODE_RA 0x03
/** MIB list root node (mem_malloced from RAM) */
#define MIB_NODE_LR 0x04
/** MIB node for external objects */
#define MIB_NODE_EX 0x05
/** node "base class" layout, the mandatory fields for a node */
struct mib_node
{
/** returns struct obj_def for the given object identifier */
void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od);
/** returns object value for the given object identifier,
@note the caller must allocate at least len bytes for the value */
void (*get_value)(struct obj_def *od, u16_t len, void *value);
/** tests length and/or range BEFORE setting */
u8_t (*set_test)(struct obj_def *od, u16_t len, void *value);
/** sets object value, only to be called when set_test() */
void (*set_value)(struct obj_def *od, u16_t len, void *value);
/** One out of MIB_NODE_AR, MIB_NODE_LR or MIB_NODE_EX */
const u8_t node_type;
/* array or max list length */
const u16_t maxlength;
};
/** derived node for scalars .0 index */
typedef struct mib_node mib_scalar_node;
/** derived node, points to a fixed size const array
of sub-identifiers plus a 'child' pointer */
struct mib_array_node
{
/* inherited "base class" members */
void (* const get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od);
void (* const get_value)(struct obj_def *od, u16_t len, void *value);
u8_t (*set_test)(struct obj_def *od, u16_t len, void *value);
void (*set_value)(struct obj_def *od, u16_t len, void *value);
const u8_t node_type;
const u16_t maxlength;
/* aditional struct members */
const s32_t *objid;
struct mib_node* const *nptr;
};
/** derived node, points to a fixed size mem_malloced array
of sub-identifiers plus a 'child' pointer */
struct mib_ram_array_node
{
/* inherited "base class" members */
void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od);
void (*get_value)(struct obj_def *od, u16_t len, void *value);
u8_t (*set_test)(struct obj_def *od, u16_t len, void *value);
void (*set_value)(struct obj_def *od, u16_t len, void *value);
u8_t node_type;
u16_t maxlength;
/* aditional struct members */
s32_t *objid;
struct mib_node **nptr;
};
struct mib_list_node
{
struct mib_list_node *prev;
struct mib_list_node *next;
s32_t objid;
struct mib_node *nptr;
};
/** derived node, points to a doubly linked list
of sub-identifiers plus a 'child' pointer */
struct mib_list_rootnode
{
/* inherited "base class" members */
void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od);
void (*get_value)(struct obj_def *od, u16_t len, void *value);
u8_t (*set_test)(struct obj_def *od, u16_t len, void *value);
void (*set_value)(struct obj_def *od, u16_t len, void *value);
u8_t node_type;
u16_t maxlength;
/* aditional struct members */
struct mib_list_node *head;
struct mib_list_node *tail;
/* counts list nodes in list */
u16_t count;
};
/** derived node, has access functions for mib object in external memory or device
using 'tree_level' and 'idx', with a range 0 .. (level_length() - 1) */
struct mib_external_node
{
/* inherited "base class" members */
void (*get_object_def)(u8_t ident_len, s32_t *ident, struct obj_def *od);
void (*get_value)(struct obj_def *od, u16_t len, void *value);
u8_t (*set_test)(struct obj_def *od, u16_t len, void *value);
void (*set_value)(struct obj_def *od, u16_t len, void *value);
u8_t node_type;
u16_t maxlength;
/* aditional struct members */
/** points to an extenal (in memory) record of some sort of addressing
information, passed to and interpreted by the funtions below */
void* addr_inf;
/** tree levels under this node */
u8_t tree_levels;
/** number of objects at this level */
u16_t (*level_length)(void* addr_inf, u8_t level);
/** compares object sub identifier with external id
return zero when equal, nonzero when unequal */
s32_t (*ident_cmp)(void* addr_inf, u8_t level, u16_t idx, s32_t sub_id);
void (*get_objid)(void* addr_inf, u8_t level, u16_t idx, s32_t *sub_id);
/** async Questions */
void (*get_object_def_q)(void* addr_inf, u8_t rid, u8_t ident_len, s32_t *ident);
void (*get_value_q)(u8_t rid, struct obj_def *od);
void (*set_test_q)(u8_t rid, struct obj_def *od);
void (*set_value_q)(u8_t rid, struct obj_def *od, u16_t len, void *value);
/** async Answers */
void (*get_object_def_a)(u8_t rid, u8_t ident_len, s32_t *ident, struct obj_def *od);
void (*get_value_a)(u8_t rid, struct obj_def *od, u16_t len, void *value);
u8_t (*set_test_a)(u8_t rid, struct obj_def *od, u16_t len, void *value);
void (*set_value_a)(u8_t rid, struct obj_def *od, u16_t len, void *value);
/** async Panic Close (agent returns error reply,
e.g. used for external transaction cleanup) */
void (*get_object_def_pc)(u8_t rid, u8_t ident_len, s32_t *ident);
void (*get_value_pc)(u8_t rid, struct obj_def *od);
void (*set_test_pc)(u8_t rid, struct obj_def *od);
void (*set_value_pc)(u8_t rid, struct obj_def *od);
};
/** export MIB tree from mib2.c */
extern const struct mib_array_node internet;
/** dummy function pointers for non-leaf MIB nodes from mib2.c */
void noleafs_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od);
void noleafs_get_value(struct obj_def *od, u16_t len, void *value);
u8_t noleafs_set_test(struct obj_def *od, u16_t len, void *value);
void noleafs_set_value(struct obj_def *od, u16_t len, void *value);
void snmp_oidtoip(s32_t *ident, struct ip_addr *ip);
void snmp_iptooid(struct ip_addr *ip, s32_t *ident);
void snmp_ifindextonetif(s32_t ifindex, struct netif **netif);
void snmp_netiftoifindex(struct netif *netif, s32_t *ifidx);
struct mib_list_node* snmp_mib_ln_alloc(s32_t id);
void snmp_mib_ln_free(struct mib_list_node *ln);
struct mib_list_rootnode* snmp_mib_lrn_alloc(void);
void snmp_mib_lrn_free(struct mib_list_rootnode *lrn);
s8_t snmp_mib_node_insert(struct mib_list_rootnode *rn, s32_t objid, struct mib_list_node **insn);
s8_t snmp_mib_node_find(struct mib_list_rootnode *rn, s32_t objid, struct mib_list_node **fn);
struct mib_list_rootnode *snmp_mib_node_delete(struct mib_list_rootnode *rn, struct mib_list_node *n);
struct mib_node* snmp_search_tree(struct mib_node *node, u8_t ident_len, s32_t *ident, struct snmp_name_ptr *np);
struct mib_node* snmp_expand_tree(struct mib_node *node, u8_t ident_len, s32_t *ident, struct snmp_obj_id *oidret);
u8_t snmp_iso_prefix_tst(u8_t ident_len, s32_t *ident);
u8_t snmp_iso_prefix_expand(u8_t ident_len, s32_t *ident, struct snmp_obj_id *oidret);
#ifdef __cplusplus
}
#endif
#endif /* LWIP_SNMP */
#endif /* __LWIP_SNMP_STRUCTS_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/snmp_structs.h | C | oos | 9,868 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_SOCKETS_H__
#define __LWIP_SOCKETS_H__
#include "lwip/opt.h"
#if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */
#include "lwip/ip_addr.h"
#include "lwip/inet.h"
#ifdef __cplusplus
extern "C" {
#endif
/* members are in network byte order */
struct sockaddr_in {
u8_t sin_len;
u8_t sin_family;
u16_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
struct sockaddr {
u8_t sa_len;
u8_t sa_family;
char sa_data[14];
};
#ifndef socklen_t
# define socklen_t u32_t
#endif
/* Socket protocol types (TCP/UDP/RAW) */
#define SOCK_STREAM 1
#define SOCK_DGRAM 2
#define SOCK_RAW 3
/*
* Option flags per-socket. These must match the SOF_ flags in ip.h!
*/
#define SO_DEBUG 0x0001 /* Unimplemented: turn on debugging info recording */
#define SO_ACCEPTCONN 0x0002 /* socket has had listen() */
#define SO_REUSEADDR 0x0004 /* Unimplemented: allow local address reuse */
#define SO_KEEPALIVE 0x0008 /* keep connections alive */
#define SO_DONTROUTE 0x0010 /* Unimplemented: just use interface addresses */
#define SO_BROADCAST 0x0020 /* Unimplemented: permit sending of broadcast msgs */
#define SO_USELOOPBACK 0x0040 /* Unimplemented: bypass hardware when possible */
#define SO_LINGER 0x0080 /* linger on close if data present */
#define SO_OOBINLINE 0x0100 /* Unimplemented: leave received OOB data in line */
#define SO_REUSEPORT 0x0200 /* Unimplemented: allow local address & port reuse */
#define SO_DONTLINGER ((int)(~SO_LINGER))
/*
* Additional options, not kept in so_options.
*/
#define SO_SNDBUF 0x1001 /* Unimplemented: send buffer size */
#define SO_RCVBUF 0x1002 /* receive buffer size */
#define SO_SNDLOWAT 0x1003 /* Unimplemented: send low-water mark */
#define SO_RCVLOWAT 0x1004 /* Unimplemented: receive low-water mark */
#define SO_SNDTIMEO 0x1005 /* Unimplemented: send timeout */
#define SO_RCVTIMEO 0x1006 /* receive timeout */
#define SO_ERROR 0x1007 /* get error status and clear */
#define SO_TYPE 0x1008 /* get socket type */
#define SO_CONTIMEO 0x1009 /* Unimplemented: connect timeout */
#define SO_NO_CHECK 0x100a /* don't create UDP checksum */
/*
* Structure used for manipulating linger option.
*/
struct linger {
int l_onoff; /* option on/off */
int l_linger; /* linger time */
};
/*
* Level number for (get/set)sockopt() to apply to socket itself.
*/
#define SOL_SOCKET 0xfff /* options for socket level */
#define AF_UNSPEC 0
#define AF_INET 2
#define PF_INET AF_INET
#define PF_UNSPEC AF_UNSPEC
#define IPPROTO_IP 0
#define IPPROTO_TCP 6
#define IPPROTO_UDP 17
#define IPPROTO_UDPLITE 136
#define INADDR_ANY 0
#define INADDR_BROADCAST 0xffffffff
/* Flags we can use with send and recv. */
#define MSG_PEEK 0x01 /* Peeks at an incoming message */
#define MSG_WAITALL 0x02 /* Unimplemented: Requests that the function block until the full amount of data requested can be returned */
#define MSG_OOB 0x04 /* Unimplemented: Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific */
#define MSG_DONTWAIT 0x08 /* Nonblocking i/o for this operation only */
#define MSG_MORE 0x10 /* Sender will send more */
/*
* Options for level IPPROTO_IP
*/
#define IP_TOS 1
#define IP_TTL 2
#if LWIP_TCP
/*
* Options for level IPPROTO_TCP
*/
#define TCP_NODELAY 0x01 /* don't delay send to coalesce packets */
#define TCP_KEEPALIVE 0x02 /* send KEEPALIVE probes when idle for pcb->keep_idle milliseconds */
#define TCP_KEEPIDLE 0x03 /* set pcb->keep_idle - Same as TCP_KEEPALIVE, but use seconds for get/setsockopt */
#define TCP_KEEPINTVL 0x04 /* set pcb->keep_intvl - Use seconds for get/setsockopt */
#define TCP_KEEPCNT 0x05 /* set pcb->keep_cnt - Use number of probes sent for get/setsockopt */
#endif /* LWIP_TCP */
#if LWIP_UDP && LWIP_UDPLITE
/*
* Options for level IPPROTO_UDPLITE
*/
#define UDPLITE_SEND_CSCOV 0x01 /* sender checksum coverage */
#define UDPLITE_RECV_CSCOV 0x02 /* minimal receiver checksum coverage */
#endif /* LWIP_UDP && LWIP_UDPLITE*/
#if LWIP_IGMP
/*
* Options and types for UDP multicast traffic handling
*/
#define IP_ADD_MEMBERSHIP 3
#define IP_DROP_MEMBERSHIP 4
#define IP_MULTICAST_TTL 5
#define IP_MULTICAST_IF 6
#define IP_MULTICAST_LOOP 7
typedef struct ip_mreq {
struct in_addr imr_multiaddr; /* IP multicast address of group */
struct in_addr imr_interface; /* local IP address of interface */
} ip_mreq;
#endif /* LWIP_IGMP */
/* Unimplemented for now... */
#define IPTOS_TOS_MASK 0x1E
#define IPTOS_TOS(tos) ((tos) & IPTOS_TOS_MASK)
#define IPTOS_LOWDELAY 0x10
#define IPTOS_THROUGHPUT 0x08
#define IPTOS_RELIABILITY 0x04
#define IPTOS_LOWCOST 0x02
#define IPTOS_MINCOST IPTOS_LOWCOST
/*
* Definitions for IP precedence (also in ip_tos) (Unimplemented)
*/
#define IPTOS_PREC_MASK 0xe0
#define IPTOS_PREC(tos) ((tos) & IPTOS_PREC_MASK)
#define IPTOS_PREC_NETCONTROL 0xe0
#define IPTOS_PREC_INTERNETCONTROL 0xc0
#define IPTOS_PREC_CRITIC_ECP 0xa0
#define IPTOS_PREC_FLASHOVERRIDE 0x80
#define IPTOS_PREC_FLASH 0x60
#define IPTOS_PREC_IMMEDIATE 0x40
#define IPTOS_PREC_PRIORITY 0x20
#define IPTOS_PREC_ROUTINE 0x00
/*
* Commands for ioctlsocket(), taken from the BSD file fcntl.h.
* lwip_ioctl only supports FIONREAD and FIONBIO, for now
*
* Ioctl's have the command encoded in the lower word,
* and the size of any in or out parameters in the upper
* word. The high 2 bits of the upper word are used
* to encode the in/out status of the parameter; for now
* we restrict parameters to at most 128 bytes.
*/
#if !defined(FIONREAD) || !defined(FIONBIO)
#define IOCPARM_MASK 0x7fU /* parameters must be < 128 bytes */
#define IOC_VOID 0x20000000UL /* no parameters */
#define IOC_OUT 0x40000000UL /* copy out parameters */
#define IOC_IN 0x80000000UL /* copy in parameters */
#define IOC_INOUT (IOC_IN|IOC_OUT)
/* 0x20000000 distinguishes new &
old ioctl's */
#define _IO(x,y) (IOC_VOID|((x)<<8)|(y))
#define _IOR(x,y,t) (IOC_OUT|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y))
#define _IOW(x,y,t) (IOC_IN|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y))
#endif /* !defined(FIONREAD) || !defined(FIONBIO) */
#ifndef FIONREAD
#define FIONREAD _IOR('f', 127, unsigned long) /* get # bytes to read */
#endif
#ifndef FIONBIO
#define FIONBIO _IOW('f', 126, unsigned long) /* set/clear non-blocking i/o */
#endif
/* Socket I/O Controls: unimplemented */
#ifndef SIOCSHIWAT
#define SIOCSHIWAT _IOW('s', 0, unsigned long) /* set high watermark */
#define SIOCGHIWAT _IOR('s', 1, unsigned long) /* get high watermark */
#define SIOCSLOWAT _IOW('s', 2, unsigned long) /* set low watermark */
#define SIOCGLOWAT _IOR('s', 3, unsigned long) /* get low watermark */
#define SIOCATMARK _IOR('s', 7, unsigned long) /* at oob mark? */
#endif
/* Socket flags: */
#ifndef O_NONBLOCK
#define O_NONBLOCK 04000U
#endif
/* FD_SET used for lwip_select */
#ifndef FD_SET
#undef FD_SETSIZE
/* Make FD_SETSIZE match NUM_SOCKETS in socket.c */
#define FD_SETSIZE MEMP_NUM_NETCONN
#define FD_SET(n, p) ((p)->fd_bits[(n)/8] |= (1 << ((n) & 7)))
#define FD_CLR(n, p) ((p)->fd_bits[(n)/8] &= ~(1 << ((n) & 7)))
#define FD_ISSET(n,p) ((p)->fd_bits[(n)/8] & (1 << ((n) & 7)))
#define FD_ZERO(p) memset((void*)(p),0,sizeof(*(p)))
typedef struct fd_set {
unsigned char fd_bits [(FD_SETSIZE+7)/8];
} fd_set;
#endif /* FD_SET */
/** LWIP_TIMEVAL_PRIVATE: if you want to use the struct timeval provided
* by your system, set this to 0 and include <sys/time.h> in cc.h */
#ifndef LWIP_TIMEVAL_PRIVATE
#define LWIP_TIMEVAL_PRIVATE 1
#endif
#if LWIP_TIMEVAL_PRIVATE
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* and microseconds */
};
#endif /* LWIP_TIMEVAL_PRIVATE */
void lwip_socket_init(void);
int lwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen);
int lwip_bind(int s, struct sockaddr *name, socklen_t namelen);
int lwip_shutdown(int s, int how);
int lwip_getpeername (int s, struct sockaddr *name, socklen_t *namelen);
int lwip_getsockname (int s, struct sockaddr *name, socklen_t *namelen);
int lwip_getsockopt (int s, int level, int optname, void *optval, socklen_t *optlen);
int lwip_setsockopt (int s, int level, int optname, const void *optval, socklen_t optlen);
int lwip_close(int s);
int lwip_connect(int s, const struct sockaddr *name, socklen_t namelen);
int lwip_listen(int s, int backlog);
int lwip_recv(int s, void *mem, int len, unsigned int flags);
int lwip_read(int s, void *mem, int len);
int lwip_recvfrom(int s, void *mem, int len, unsigned int flags,
struct sockaddr *from, socklen_t *fromlen);
int lwip_send(int s, const void *dataptr, int size, unsigned int flags);
int lwip_sendto(int s, const void *dataptr, int size, unsigned int flags,
struct sockaddr *to, socklen_t tolen);
int lwip_socket(int domain, int type, int protocol);
int lwip_write(int s, const void *dataptr, int size);
int lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset,
struct timeval *timeout);
int lwip_ioctl(int s, long cmd, void *argp);
#if LWIP_COMPAT_SOCKETS
#define accept(a,b,c) lwip_accept(a,b,c)
#define bind(a,b,c) lwip_bind(a,b,c)
#define shutdown(a,b) lwip_shutdown(a,b)
#define closesocket(s) lwip_close(s)
#define connect(a,b,c) lwip_connect(a,b,c)
#define getsockname(a,b,c) lwip_getsockname(a,b,c)
#define getpeername(a,b,c) lwip_getpeername(a,b,c)
#define setsockopt(a,b,c,d,e) lwip_setsockopt(a,b,c,d,e)
#define getsockopt(a,b,c,d,e) lwip_getsockopt(a,b,c,d,e)
#define listen(a,b) lwip_listen(a,b)
#define recv(a,b,c,d) lwip_recv(a,b,c,d)
#define recvfrom(a,b,c,d,e,f) lwip_recvfrom(a,b,c,d,e,f)
#define send(a,b,c,d) lwip_send(a,b,c,d)
#define sendto(a,b,c,d,e,f) lwip_sendto(a,b,c,d,e,f)
#define socket(a,b,c) lwip_socket(a,b,c)
#define select(a,b,c,d,e) lwip_select(a,b,c,d,e)
#define ioctlsocket(a,b,c) lwip_ioctl(a,b,c)
#if LWIP_POSIX_SOCKETS_IO_NAMES
#define read(a,b,c) lwip_read(a,b,c)
#define write(a,b,c) lwip_write(a,b,c)
#define close(s) lwip_close(s)
#endif /* LWIP_POSIX_SOCKETS_IO_NAMES */
#endif /* LWIP_COMPAT_SOCKETS */
#ifdef __cplusplus
}
#endif
#endif /* LWIP_SOCKET */
#endif /* __LWIP_SOCKETS_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/sockets.h | C | oos | 12,889 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_API_H__
#define __LWIP_API_H__
#include "lwip/opt.h"
#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */
#include "lwip/netbuf.h"
#include "lwip/sys.h"
#include "lwip/ip_addr.h"
#include "lwip/err.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Throughout this file, IP addresses and port numbers are expected to be in
* the same byte order as in the corresponding pcb.
*/
/* Flags for netconn_write */
#define NETCONN_NOFLAG 0x00
#define NETCONN_NOCOPY 0x00 /* Only for source code compatibility */
#define NETCONN_COPY 0x01
#define NETCONN_MORE 0x02
/* Helpers to process several netconn_types by the same code */
#define NETCONNTYPE_GROUP(t) (t&0xF0)
#define NETCONNTYPE_DATAGRAM(t) (t&0xE0)
enum netconn_type {
NETCONN_INVALID = 0,
/* NETCONN_TCP Group */
NETCONN_TCP = 0x10,
/* NETCONN_UDP Group */
NETCONN_UDP = 0x20,
NETCONN_UDPLITE = 0x21,
NETCONN_UDPNOCHKSUM= 0x22,
/* NETCONN_RAW Group */
NETCONN_RAW = 0x40
};
enum netconn_state {
NETCONN_NONE,
NETCONN_WRITE,
NETCONN_LISTEN,
NETCONN_CONNECT,
NETCONN_CLOSE
};
enum netconn_evt {
NETCONN_EVT_RCVPLUS,
NETCONN_EVT_RCVMINUS,
NETCONN_EVT_SENDPLUS,
NETCONN_EVT_SENDMINUS
};
#if LWIP_IGMP
enum netconn_igmp {
NETCONN_JOIN,
NETCONN_LEAVE
};
#endif /* LWIP_IGMP */
/* forward-declare some structs to avoid to include their headers */
struct ip_pcb;
struct tcp_pcb;
struct udp_pcb;
struct raw_pcb;
struct netconn;
/** A callback prototype to inform about events for a netconn */
typedef void (* netconn_callback)(struct netconn *, enum netconn_evt, u16_t len);
/** A netconn descriptor */
struct netconn {
/** type of the netconn (TCP, UDP or RAW) */
enum netconn_type type;
/** current state of the netconn */
enum netconn_state state;
/** the lwIP internal protocol control block */
union {
struct ip_pcb *ip;
struct tcp_pcb *tcp;
struct udp_pcb *udp;
struct raw_pcb *raw;
} pcb;
/** the last error this netconn had */
err_t err;
/** sem that is used to synchroneously execute functions in the core context */
sys_sem_t op_completed;
/** mbox where received packets are stored until they are fetched
by the netconn application thread (can grow quite big) */
sys_mbox_t recvmbox;
/** mbox where new connections are stored until processed
by the application thread */
sys_mbox_t acceptmbox;
/** only used for socket layer */
int socket;
#if LWIP_SO_RCVTIMEO
/** timeout to wait for new data to be received
(or connections to arrive for listening netconns) */
int recv_timeout;
#endif /* LWIP_SO_RCVTIMEO */
#if LWIP_SO_RCVBUF
/** maximum amount of bytes queued in recvmbox */
int recv_bufsize;
#endif /* LWIP_SO_RCVBUF */
u16_t recv_avail;
/** TCP: when data passed to netconn_write doesn't fit into the send buffer,
this temporarily stores the message. */
struct api_msg_msg *write_msg;
/** TCP: when data passed to netconn_write doesn't fit into the send buffer,
this temporarily stores how much is already sent. */
int write_offset;
#if LWIP_TCPIP_CORE_LOCKING
/** TCP: when data passed to netconn_write doesn't fit into the send buffer,
this temporarily stores whether to wake up the original application task
if data couldn't be sent in the first try. */
u8_t write_delayed;
#endif /* LWIP_TCPIP_CORE_LOCKING */
/** A callback function that is informed about events for this netconn */
netconn_callback callback;
};
/* Register an Network connection event */
#define API_EVENT(c,e,l) if (c->callback) { \
(*c->callback)(c, e, l); \
}
/* Network connection functions: */
#define netconn_new(t) netconn_new_with_proto_and_callback(t, 0, NULL)
#define netconn_new_with_callback(t, c) netconn_new_with_proto_and_callback(t, 0, c)
struct
netconn *netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto,
netconn_callback callback);
err_t netconn_delete (struct netconn *conn);
enum netconn_type netconn_type (struct netconn *conn);
err_t netconn_getaddr (struct netconn *conn,
struct ip_addr *addr,
u16_t *port,
u8_t local);
#define netconn_peer(c,i,p) netconn_getaddr(c,i,p,0)
#define netconn_addr(c,i,p) netconn_getaddr(c,i,p,1)
err_t netconn_bind (struct netconn *conn,
struct ip_addr *addr,
u16_t port);
err_t netconn_connect (struct netconn *conn,
struct ip_addr *addr,
u16_t port);
err_t netconn_disconnect (struct netconn *conn);
err_t netconn_listen_with_backlog(struct netconn *conn, u8_t backlog);
#define netconn_listen(conn) netconn_listen_with_backlog(conn, TCP_DEFAULT_LISTEN_BACKLOG)
struct netconn * netconn_accept (struct netconn *conn);
struct netbuf * netconn_recv (struct netconn *conn);
err_t netconn_sendto (struct netconn *conn,
struct netbuf *buf, struct ip_addr *addr, u16_t port);
err_t netconn_send (struct netconn *conn,
struct netbuf *buf);
err_t netconn_write (struct netconn *conn,
const void *dataptr, int size,
u8_t apiflags);
err_t netconn_close (struct netconn *conn);
#if LWIP_IGMP
err_t netconn_join_leave_group (struct netconn *conn,
struct ip_addr *multiaddr,
struct ip_addr *interface,
enum netconn_igmp join_or_leave);
#endif /* LWIP_IGMP */
#if LWIP_DNS
err_t netconn_gethostbyname(const char *name, struct ip_addr *addr);
#endif /* LWIP_DNS */
#define netconn_err(conn) ((conn)->err)
#define netconn_recv_bufsize(conn) ((conn)->recv_bufsize)
#ifdef __cplusplus
}
#endif
#endif /* LWIP_NETCONN */
#endif /* __LWIP_API_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/api.h | C | oos | 8,099 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_NETBUF_H__
#define __LWIP_NETBUF_H__
#include "lwip/opt.h"
#include "lwip/pbuf.h"
#ifdef __cplusplus
extern "C" {
#endif
struct netbuf {
struct pbuf *p, *ptr;
struct ip_addr *addr;
u16_t port;
};
/* Network buffer functions: */
struct netbuf * netbuf_new (void);
void netbuf_delete (struct netbuf *buf);
void * netbuf_alloc (struct netbuf *buf, u16_t size);
void netbuf_free (struct netbuf *buf);
err_t netbuf_ref (struct netbuf *buf,
const void *dataptr, u16_t size);
void netbuf_chain (struct netbuf *head,
struct netbuf *tail);
u16_t netbuf_len (struct netbuf *buf);
err_t netbuf_data (struct netbuf *buf,
void **dataptr, u16_t *len);
s8_t netbuf_next (struct netbuf *buf);
void netbuf_first (struct netbuf *buf);
#define netbuf_copy_partial(buf, dataptr, len, offset) \
pbuf_copy_partial((buf)->p, (dataptr), (len), (offset))
#define netbuf_copy(buf,dataptr,len) netbuf_copy_partial(buf, dataptr, len, 0)
#define netbuf_len(buf) ((buf)->p->tot_len)
#define netbuf_fromaddr(buf) ((buf)->addr)
#define netbuf_fromport(buf) ((buf)->port)
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_NETBUF_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/netbuf.h | C | oos | 3,014 |
/**
* lwip DNS resolver header file.
* Author: Jim Pettinato
* April 2007
* ported from uIP resolv.c Copyright (c) 2002-2003, Adam Dunkels.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __LWIP_DNS_H__
#define __LWIP_DNS_H__
#include "lwip/opt.h"
#if LWIP_DNS /* don't build if not configured for use in lwipopts.h */
/** DNS timer period */
#define DNS_TMR_INTERVAL 1000
/** DNS field TYPE used for "Resource Records" */
#define DNS_RRTYPE_A 1 /* a host address */
#define DNS_RRTYPE_NS 2 /* an authoritative name server */
#define DNS_RRTYPE_MD 3 /* a mail destination (Obsolete - use MX) */
#define DNS_RRTYPE_MF 4 /* a mail forwarder (Obsolete - use MX) */
#define DNS_RRTYPE_CNAME 5 /* the canonical name for an alias */
#define DNS_RRTYPE_SOA 6 /* marks the start of a zone of authority */
#define DNS_RRTYPE_MB 7 /* a mailbox domain name (EXPERIMENTAL) */
#define DNS_RRTYPE_MG 8 /* a mail group member (EXPERIMENTAL) */
#define DNS_RRTYPE_MR 9 /* a mail rename domain name (EXPERIMENTAL) */
#define DNS_RRTYPE_NULL 10 /* a null RR (EXPERIMENTAL) */
#define DNS_RRTYPE_WKS 11 /* a well known service description */
#define DNS_RRTYPE_PTR 12 /* a domain name pointer */
#define DNS_RRTYPE_HINFO 13 /* host information */
#define DNS_RRTYPE_MINFO 14 /* mailbox or mail list information */
#define DNS_RRTYPE_MX 15 /* mail exchange */
#define DNS_RRTYPE_TXT 16 /* text strings */
/** DNS field CLASS used for "Resource Records" */
#define DNS_RRCLASS_IN 1 /* the Internet */
#define DNS_RRCLASS_CS 2 /* the CSNET class (Obsolete - used only for examples in some obsolete RFCs) */
#define DNS_RRCLASS_CH 3 /* the CHAOS class */
#define DNS_RRCLASS_HS 4 /* Hesiod [Dyer 87] */
#define DNS_RRCLASS_FLUSH 0x800 /* Flush bit */
/** Callback which is invoked when a hostname is found.
* A function of this type must be implemented by the application using the DNS resolver.
* @param name pointer to the name that was looked up.
* @param ipaddr pointer to a struct ip_addr containing the IP address of the hostname,
* or NULL if the name could not be found (or on any other error).
* @param callback_arg a user-specified callback argument passed to dns_gethostbyname
*/
typedef void (*dns_found_callback)(const char *name, struct ip_addr *ipaddr, void *callback_arg);
void dns_init(void);
void dns_tmr(void);
void dns_setserver(u8_t numdns, struct ip_addr *dnsserver);
struct ip_addr dns_getserver(u8_t numdns);
err_t dns_gethostbyname(const char *hostname, struct ip_addr *addr,
dns_found_callback found, void *callback_arg);
#endif /* LWIP_DNS */
#endif /* __LWIP_DNS_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/dns.h | C | oos | 4,462 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_TCP_H__
#define __LWIP_TCP_H__
#include "lwip/opt.h"
#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */
#include "lwip/sys.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include "lwip/ip.h"
#include "lwip/icmp.h"
#include "lwip/err.h"
#ifdef __cplusplus
extern "C" {
#endif
struct tcp_pcb;
/* Functions for interfacing with TCP: */
/* Lower layer interface to TCP: */
#define tcp_init() /* Compatibility define, not init needed. */
void tcp_tmr (void); /* Must be called every
TCP_TMR_INTERVAL
ms. (Typically 250 ms). */
/* Application program's interface: */
struct tcp_pcb * tcp_new (void);
struct tcp_pcb * tcp_alloc (u8_t prio);
void tcp_arg (struct tcp_pcb *pcb, void *arg);
void tcp_accept (struct tcp_pcb *pcb,
err_t (* accept)(void *arg, struct tcp_pcb *newpcb,
err_t err));
void tcp_recv (struct tcp_pcb *pcb,
err_t (* recv)(void *arg, struct tcp_pcb *tpcb,
struct pbuf *p, err_t err));
void tcp_sent (struct tcp_pcb *pcb,
err_t (* sent)(void *arg, struct tcp_pcb *tpcb,
u16_t len));
void tcp_poll (struct tcp_pcb *pcb,
err_t (* poll)(void *arg, struct tcp_pcb *tpcb),
u8_t interval);
void tcp_err (struct tcp_pcb *pcb,
void (* err)(void *arg, err_t err));
#define tcp_mss(pcb) ((pcb)->mss)
#define tcp_sndbuf(pcb) ((pcb)->snd_buf)
#if TCP_LISTEN_BACKLOG
#define tcp_accepted(pcb) (((struct tcp_pcb_listen *)(pcb))->accepts_pending--)
#else /* TCP_LISTEN_BACKLOG */
#define tcp_accepted(pcb)
#endif /* TCP_LISTEN_BACKLOG */
void tcp_recved (struct tcp_pcb *pcb, u16_t len);
err_t tcp_bind (struct tcp_pcb *pcb, struct ip_addr *ipaddr,
u16_t port);
err_t tcp_connect (struct tcp_pcb *pcb, struct ip_addr *ipaddr,
u16_t port, err_t (* connected)(void *arg,
struct tcp_pcb *tpcb,
err_t err));
struct tcp_pcb * tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog);
#define tcp_listen(pcb) tcp_listen_with_backlog(pcb, TCP_DEFAULT_LISTEN_BACKLOG)
void tcp_abort (struct tcp_pcb *pcb);
err_t tcp_close (struct tcp_pcb *pcb);
/* Flags for "apiflags" parameter in tcp_write and tcp_enqueue */
#define TCP_WRITE_FLAG_COPY 0x01
#define TCP_WRITE_FLAG_MORE 0x02
err_t tcp_write (struct tcp_pcb *pcb, const void *dataptr, u16_t len,
u8_t apiflags);
void tcp_setprio (struct tcp_pcb *pcb, u8_t prio);
#define TCP_PRIO_MIN 1
#define TCP_PRIO_NORMAL 64
#define TCP_PRIO_MAX 127
/* It is also possible to call these two functions at the right
intervals (instead of calling tcp_tmr()). */
void tcp_slowtmr (void);
void tcp_fasttmr (void);
/* Only used by IP to pass a TCP segment to TCP: */
void tcp_input (struct pbuf *p, struct netif *inp);
/* Used within the TCP code only: */
err_t tcp_output (struct tcp_pcb *pcb);
void tcp_rexmit (struct tcp_pcb *pcb);
void tcp_rexmit_rto (struct tcp_pcb *pcb);
/**
* This is the Nagle algorithm: inhibit the sending of new TCP
* segments when new outgoing data arrives from the user if any
* previously transmitted data on the connection remains
* unacknowledged.
*/
#define tcp_do_output_nagle(tpcb) ((((tpcb)->unacked == NULL) || \
((tpcb)->flags & TF_NODELAY) || \
(((tpcb)->unsent != NULL) && ((tpcb)->unsent->next != NULL))) ? \
1 : 0)
#define tcp_output_nagle(tpcb) (tcp_do_output_nagle(tpcb) ? tcp_output(tpcb) : ERR_OK)
/** This returns a TCP header option for MSS in an u32_t */
#define TCP_BUILD_MSS_OPTION() htonl(((u32_t)2 << 24) | \
((u32_t)4 << 16) | \
(((u32_t)TCP_MSS / 256) << 8) | \
(TCP_MSS & 255))
#define TCP_SEQ_LT(a,b) ((s32_t)((a)-(b)) < 0)
#define TCP_SEQ_LEQ(a,b) ((s32_t)((a)-(b)) <= 0)
#define TCP_SEQ_GT(a,b) ((s32_t)((a)-(b)) > 0)
#define TCP_SEQ_GEQ(a,b) ((s32_t)((a)-(b)) >= 0)
/* is b<=a<=c? */
#if 0 /* see bug #10548 */
#define TCP_SEQ_BETWEEN(a,b,c) ((c)-(b) >= (a)-(b))
#endif
#define TCP_SEQ_BETWEEN(a,b,c) (TCP_SEQ_GEQ(a,b) && TCP_SEQ_LEQ(a,c))
#define TCP_FIN 0x01U
#define TCP_SYN 0x02U
#define TCP_RST 0x04U
#define TCP_PSH 0x08U
#define TCP_ACK 0x10U
#define TCP_URG 0x20U
#define TCP_ECE 0x40U
#define TCP_CWR 0x80U
#define TCP_FLAGS 0x3fU
/* Length of the TCP header, excluding options. */
#define TCP_HLEN 20
#ifndef TCP_TMR_INTERVAL
#define TCP_TMR_INTERVAL 250 /* The TCP timer interval in milliseconds. */
#endif /* TCP_TMR_INTERVAL */
#ifndef TCP_FAST_INTERVAL
#define TCP_FAST_INTERVAL TCP_TMR_INTERVAL /* the fine grained timeout in milliseconds */
#endif /* TCP_FAST_INTERVAL */
#ifndef TCP_SLOW_INTERVAL
#define TCP_SLOW_INTERVAL (2*TCP_TMR_INTERVAL) /* the coarse grained timeout in milliseconds */
#endif /* TCP_SLOW_INTERVAL */
#define TCP_FIN_WAIT_TIMEOUT 20000 /* milliseconds */
#define TCP_SYN_RCVD_TIMEOUT 20000 /* milliseconds */
#define TCP_OOSEQ_TIMEOUT 6U /* x RTO */
#ifndef TCP_MSL
#define TCP_MSL 60000U /* The maximum segment lifetime in milliseconds */
#endif
/* Keepalive values, compliant with RFC 1122. Don't change this unless you know what you're doing */
#ifndef TCP_KEEPIDLE_DEFAULT
#define TCP_KEEPIDLE_DEFAULT 7200000UL /* Default KEEPALIVE timer in milliseconds */
#endif
#ifndef TCP_KEEPINTVL_DEFAULT
#define TCP_KEEPINTVL_DEFAULT 75000UL /* Default Time between KEEPALIVE probes in milliseconds */
#endif
#ifndef TCP_KEEPCNT_DEFAULT
#define TCP_KEEPCNT_DEFAULT 9U /* Default Counter for KEEPALIVE probes */
#endif
#define TCP_MAXIDLE TCP_KEEPCNT_DEFAULT * TCP_KEEPINTVL_DEFAULT /* Maximum KEEPALIVE probe time */
/* Fields are (of course) in network byte order.
* Some fields are converted to host byte order in tcp_input().
*/
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct tcp_hdr {
PACK_STRUCT_FIELD(u16_t src);
PACK_STRUCT_FIELD(u16_t dest);
PACK_STRUCT_FIELD(u32_t seqno);
PACK_STRUCT_FIELD(u32_t ackno);
PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags);
PACK_STRUCT_FIELD(u16_t wnd);
PACK_STRUCT_FIELD(u16_t chksum);
PACK_STRUCT_FIELD(u16_t urgp);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define TCPH_OFFSET(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 8)
#define TCPH_HDRLEN(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 12)
#define TCPH_FLAGS(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS)
#define TCPH_OFFSET_SET(phdr, offset) (phdr)->_hdrlen_rsvd_flags = htons(((offset) << 8) | TCPH_FLAGS(phdr))
#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | TCPH_FLAGS(phdr))
#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = htons((ntohs((phdr)->_hdrlen_rsvd_flags) & ~TCP_FLAGS) | (flags))
#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = htons(ntohs((phdr)->_hdrlen_rsvd_flags) | (flags))
#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = htons(ntohs((phdr)->_hdrlen_rsvd_flags) | (TCPH_FLAGS(phdr) & ~(flags)) )
#define TCP_TCPLEN(seg) ((seg)->len + ((TCPH_FLAGS((seg)->tcphdr) & TCP_FIN || \
TCPH_FLAGS((seg)->tcphdr) & TCP_SYN)? 1: 0))
enum tcp_state {
CLOSED = 0,
LISTEN = 1,
SYN_SENT = 2,
SYN_RCVD = 3,
ESTABLISHED = 4,
FIN_WAIT_1 = 5,
FIN_WAIT_2 = 6,
CLOSE_WAIT = 7,
CLOSING = 8,
LAST_ACK = 9,
TIME_WAIT = 10
};
/** Flags used on input processing, not on pcb->flags
*/
#define TF_RESET (u8_t)0x08U /* Connection was reset. */
#define TF_CLOSED (u8_t)0x10U /* Connection was sucessfully closed. */
#define TF_GOT_FIN (u8_t)0x20U /* Connection was closed by the remote end. */
/**
* members common to struct tcp_pcb and struct tcp_listen_pcb
*/
#define TCP_PCB_COMMON(type) \
type *next; /* for the linked list */ \
enum tcp_state state; /* TCP state */ \
u8_t prio; \
void *callback_arg; \
/* ports are in host byte order */ \
u16_t local_port
/* the TCP protocol control block */
struct tcp_pcb {
/** common PCB members */
IP_PCB;
/** protocol specific PCB members */
TCP_PCB_COMMON(struct tcp_pcb);
/* ports are in host byte order */
u16_t remote_port;
u8_t flags;
#define TF_ACK_DELAY (u8_t)0x01U /* Delayed ACK. */
#define TF_ACK_NOW (u8_t)0x02U /* Immediate ACK. */
#define TF_INFR (u8_t)0x04U /* In fast recovery. */
#define TF_FIN (u8_t)0x20U /* Connection was closed locally (FIN segment enqueued). */
#define TF_NODELAY (u8_t)0x40U /* Disable Nagle algorithm */
#define TF_NAGLEMEMERR (u8_t)0x80U /* nagle enabled, memerr, try to output to prevent delayed ACK to happen */
/* the rest of the fields are in host byte order
as we have to do some math with them */
/* receiver variables */
u32_t rcv_nxt; /* next seqno expected */
u16_t rcv_wnd; /* receiver window */
u16_t rcv_ann_wnd; /* announced receive window */
/* Timers */
u32_t tmr;
u8_t polltmr, pollinterval;
/* Retransmission timer. */
s16_t rtime;
u16_t mss; /* maximum segment size */
/* RTT (round trip time) estimation variables */
u32_t rttest; /* RTT estimate in 500ms ticks */
u32_t rtseq; /* sequence number being timed */
s16_t sa, sv; /* @todo document this */
s16_t rto; /* retransmission time-out */
u8_t nrtx; /* number of retransmissions */
/* fast retransmit/recovery */
u32_t lastack; /* Highest acknowledged seqno. */
u8_t dupacks;
/* congestion avoidance/control variables */
u16_t cwnd;
u16_t ssthresh;
/* sender variables */
u32_t snd_nxt, /* next seqno to be sent */
snd_max; /* Highest seqno sent. */
u16_t snd_wnd; /* sender window */
u32_t snd_wl1, snd_wl2, /* Sequence and acknowledgement numbers of last
window update. */
snd_lbb; /* Sequence number of next byte to be buffered. */
u16_t acked;
u16_t snd_buf; /* Available buffer space for sending (in bytes). */
#define TCP_SNDQUEUELEN_OVERFLOW (0xffff-3)
u16_t snd_queuelen; /* Available buffer space for sending (in tcp_segs). */
/* These are ordered by sequence number: */
struct tcp_seg *unsent; /* Unsent (queued) segments. */
struct tcp_seg *unacked; /* Sent but unacknowledged segments. */
#if TCP_QUEUE_OOSEQ
struct tcp_seg *ooseq; /* Received out of sequence segments. */
#endif /* TCP_QUEUE_OOSEQ */
struct pbuf *refused_data; /* Data previously received but not yet taken by upper layer */
#if LWIP_CALLBACK_API
/* Function to be called when more send buffer space is available.
* @param arg user-supplied argument (tcp_pcb.callback_arg)
* @param pcb the tcp_pcb which has send buffer space available
* @param space the amount of bytes available
* @return ERR_OK: try to send some data by calling tcp_output
*/
err_t (* sent)(void *arg, struct tcp_pcb *pcb, u16_t space);
/* Function to be called when (in-sequence) data has arrived.
* @param arg user-supplied argument (tcp_pcb.callback_arg)
* @param pcb the tcp_pcb for which data has arrived
* @param p the packet buffer which arrived
* @param err an error argument (TODO: that is current always ERR_OK?)
* @return ERR_OK: try to send some data by calling tcp_output
*/
err_t (* recv)(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err);
/* Function to be called when a connection has been set up.
* @param arg user-supplied argument (tcp_pcb.callback_arg)
* @param pcb the tcp_pcb that now is connected
* @param err an error argument (TODO: that is current always ERR_OK?)
* @return value is currently ignored
*/
err_t (* connected)(void *arg, struct tcp_pcb *pcb, err_t err);
/* Function to call when a listener has been connected.
* @param arg user-supplied argument (tcp_pcb.callback_arg)
* @param pcb a new tcp_pcb that now is connected
* @param err an error argument (TODO: that is current always ERR_OK?)
* @return ERR_OK: accept the new connection,
* any other err_t abortsthe new connection
*/
err_t (* accept)(void *arg, struct tcp_pcb *newpcb, err_t err);
/* Function which is called periodically.
* The period can be adjusted in multiples of the TCP slow timer interval
* by changing tcp_pcb.polltmr.
* @param arg user-supplied argument (tcp_pcb.callback_arg)
* @param pcb the tcp_pcb to poll for
* @return ERR_OK: try to send some data by calling tcp_output
*/
err_t (* poll)(void *arg, struct tcp_pcb *pcb);
/* Function to be called whenever a fatal error occurs.
* There is no pcb parameter since most of the times, the pcb is
* already deallocated (or there is no pcb) when this function is called.
* @param arg user-supplied argument (tcp_pcb.callback_arg)
* @param err an indication why the error callback is called:
* ERR_ABRT: aborted through tcp_abort or by a TCP timer
* ERR_RST: the connection was reset by the remote host
*/
void (* errf)(void *arg, err_t err);
#endif /* LWIP_CALLBACK_API */
/* idle time before KEEPALIVE is sent */
u32_t keep_idle;
#if LWIP_TCP_KEEPALIVE
u32_t keep_intvl;
u32_t keep_cnt;
#endif /* LWIP_TCP_KEEPALIVE */
/* Persist timer counter */
u32_t persist_cnt;
/* Persist timer back-off */
u8_t persist_backoff;
/* KEEPALIVE counter */
u8_t keep_cnt_sent;
};
struct tcp_pcb_listen {
/* Common members of all PCB types */
IP_PCB;
/* Protocol specific PCB members */
TCP_PCB_COMMON(struct tcp_pcb_listen);
#if LWIP_CALLBACK_API
/* Function to call when a listener has been connected.
* @param arg user-supplied argument (tcp_pcb.callback_arg)
* @param pcb a new tcp_pcb that now is connected
* @param err an error argument (TODO: that is current always ERR_OK?)
* @return ERR_OK: accept the new connection,
* any other err_t abortsthe new connection
*/
err_t (* accept)(void *arg, struct tcp_pcb *newpcb, err_t err);
#endif /* LWIP_CALLBACK_API */
#if TCP_LISTEN_BACKLOG
u8_t backlog;
u8_t accepts_pending;
#endif /* TCP_LISTEN_BACKLOG */
};
#if LWIP_EVENT_API
enum lwip_event {
LWIP_EVENT_ACCEPT,
LWIP_EVENT_SENT,
LWIP_EVENT_RECV,
LWIP_EVENT_CONNECTED,
LWIP_EVENT_POLL,
LWIP_EVENT_ERR
};
err_t lwip_tcp_event(void *arg, struct tcp_pcb *pcb,
enum lwip_event,
struct pbuf *p,
u16_t size,
err_t err);
#define TCP_EVENT_ACCEPT(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
LWIP_EVENT_ACCEPT, NULL, 0, err)
#define TCP_EVENT_SENT(pcb,space,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
LWIP_EVENT_SENT, NULL, space, ERR_OK)
#define TCP_EVENT_RECV(pcb,p,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
LWIP_EVENT_RECV, (p), 0, (err))
#define TCP_EVENT_CONNECTED(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
LWIP_EVENT_CONNECTED, NULL, 0, (err))
#define TCP_EVENT_POLL(pcb,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\
LWIP_EVENT_POLL, NULL, 0, ERR_OK)
#define TCP_EVENT_ERR(errf,arg,err) lwip_tcp_event((arg), NULL, \
LWIP_EVENT_ERR, NULL, 0, (err))
#else /* LWIP_EVENT_API */
#define TCP_EVENT_ACCEPT(pcb,err,ret) \
if((pcb)->accept != NULL) \
(ret = (pcb)->accept((pcb)->callback_arg,(pcb),(err)))
#define TCP_EVENT_SENT(pcb,space,ret) \
if((pcb)->sent != NULL) \
(ret = (pcb)->sent((pcb)->callback_arg,(pcb),(space)))
#define TCP_EVENT_RECV(pcb,p,err,ret) \
if((pcb)->recv != NULL) \
{ ret = (pcb)->recv((pcb)->callback_arg,(pcb),(p),(err)); } else { \
ret = ERR_OK; \
if (p) pbuf_free(p); }
#define TCP_EVENT_CONNECTED(pcb,err,ret) \
if((pcb)->connected != NULL) \
(ret = (pcb)->connected((pcb)->callback_arg,(pcb),(err)))
#define TCP_EVENT_POLL(pcb,ret) \
if((pcb)->poll != NULL) \
(ret = (pcb)->poll((pcb)->callback_arg,(pcb)))
#define TCP_EVENT_ERR(errf,arg,err) \
if((errf) != NULL) \
(errf)((arg),(err))
#endif /* LWIP_EVENT_API */
/* This structure represents a TCP segment on the unsent and unacked queues */
struct tcp_seg {
struct tcp_seg *next; /* used when putting segements on a queue */
struct pbuf *p; /* buffer containing data + TCP header */
void *dataptr; /* pointer to the TCP data in the pbuf */
u16_t len; /* the TCP length of this segment */
struct tcp_hdr *tcphdr; /* the TCP header */
};
/* Internal functions and global variables: */
struct tcp_pcb *tcp_pcb_copy(struct tcp_pcb *pcb);
void tcp_pcb_purge(struct tcp_pcb *pcb);
void tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb);
u8_t tcp_segs_free(struct tcp_seg *seg);
u8_t tcp_seg_free(struct tcp_seg *seg);
struct tcp_seg *tcp_seg_copy(struct tcp_seg *seg);
#define tcp_ack(pcb) if((pcb)->flags & TF_ACK_DELAY) { \
(pcb)->flags &= ~TF_ACK_DELAY; \
(pcb)->flags |= TF_ACK_NOW; \
tcp_output(pcb); \
} else { \
(pcb)->flags |= TF_ACK_DELAY; \
}
#define tcp_ack_now(pcb) (pcb)->flags |= TF_ACK_NOW; \
tcp_output(pcb)
err_t tcp_send_ctrl(struct tcp_pcb *pcb, u8_t flags);
err_t tcp_enqueue(struct tcp_pcb *pcb, void *dataptr, u16_t len,
u8_t flags, u8_t apiflags,
u8_t *optdata, u8_t optlen);
void tcp_rexmit_seg(struct tcp_pcb *pcb, struct tcp_seg *seg);
void tcp_rst(u32_t seqno, u32_t ackno,
struct ip_addr *local_ip, struct ip_addr *remote_ip,
u16_t local_port, u16_t remote_port);
u32_t tcp_next_iss(void);
void tcp_keepalive(struct tcp_pcb *pcb);
void tcp_zero_window_probe(struct tcp_pcb *pcb);
#if TCP_CALCULATE_EFF_SEND_MSS
u16_t tcp_eff_send_mss(u16_t sendmss, struct ip_addr *addr);
#endif /* TCP_CALCULATE_EFF_SEND_MSS */
extern struct tcp_pcb *tcp_input_pcb;
extern u32_t tcp_ticks;
#if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG
void tcp_debug_print(struct tcp_hdr *tcphdr);
void tcp_debug_print_flags(u8_t flags);
void tcp_debug_print_state(enum tcp_state s);
void tcp_debug_print_pcbs(void);
s16_t tcp_pcbs_sane(void);
#else
# define tcp_debug_print(tcphdr)
# define tcp_debug_print_flags(flags)
# define tcp_debug_print_state(s)
# define tcp_debug_print_pcbs()
# define tcp_pcbs_sane() 1
#endif /* TCP_DEBUG */
#if NO_SYS
#define tcp_timer_needed()
#else
void tcp_timer_needed(void);
#endif
/* The TCP PCB lists. */
union tcp_listen_pcbs_t { /* List of all TCP PCBs in LISTEN state. */
struct tcp_pcb_listen *listen_pcbs;
struct tcp_pcb *pcbs;
};
extern union tcp_listen_pcbs_t tcp_listen_pcbs;
extern struct tcp_pcb *tcp_active_pcbs; /* List of all TCP PCBs that are in a
state in which they accept or send
data. */
extern struct tcp_pcb *tcp_tw_pcbs; /* List of all TCP PCBs in TIME-WAIT. */
extern struct tcp_pcb *tcp_tmp_pcb; /* Only used for temporary storage. */
/* Axioms about the above lists:
1) Every TCP PCB that is not CLOSED is in one of the lists.
2) A PCB is only in one of the lists.
3) All PCBs in the tcp_listen_pcbs list is in LISTEN state.
4) All PCBs in the tcp_tw_pcbs list is in TIME-WAIT state.
*/
/* Define two macros, TCP_REG and TCP_RMV that registers a TCP PCB
with a PCB list or removes a PCB from a list, respectively. */
#if 0
#define TCP_REG(pcbs, npcb) do {\
LWIP_DEBUGF(TCP_DEBUG, ("TCP_REG %p local port %d\n", npcb, npcb->local_port)); \
for(tcp_tmp_pcb = *pcbs; \
tcp_tmp_pcb != NULL; \
tcp_tmp_pcb = tcp_tmp_pcb->next) { \
LWIP_ASSERT("TCP_REG: already registered\n", tcp_tmp_pcb != npcb); \
} \
LWIP_ASSERT("TCP_REG: pcb->state != CLOSED", npcb->state != CLOSED); \
npcb->next = *pcbs; \
LWIP_ASSERT("TCP_REG: npcb->next != npcb", npcb->next != npcb); \
*(pcbs) = npcb; \
LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \
tcp_timer_needed(); \
} while(0)
#define TCP_RMV(pcbs, npcb) do { \
LWIP_ASSERT("TCP_RMV: pcbs != NULL", *pcbs != NULL); \
LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removing %p from %p\n", npcb, *pcbs)); \
if(*pcbs == npcb) { \
*pcbs = (*pcbs)->next; \
} else for(tcp_tmp_pcb = *pcbs; tcp_tmp_pcb != NULL; tcp_tmp_pcb = tcp_tmp_pcb->next) { \
if(tcp_tmp_pcb->next != NULL && tcp_tmp_pcb->next == npcb) { \
tcp_tmp_pcb->next = npcb->next; \
break; \
} \
} \
npcb->next = NULL; \
LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \
LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removed %p from %p\n", npcb, *pcbs)); \
} while(0)
#else /* LWIP_DEBUG */
#define TCP_REG(pcbs, npcb) do { \
npcb->next = *pcbs; \
*(pcbs) = npcb; \
tcp_timer_needed(); \
} while(0)
#define TCP_RMV(pcbs, npcb) do { \
if(*(pcbs) == npcb) { \
(*(pcbs)) = (*pcbs)->next; \
} else for(tcp_tmp_pcb = *pcbs; tcp_tmp_pcb != NULL; tcp_tmp_pcb = tcp_tmp_pcb->next) { \
if(tcp_tmp_pcb->next != NULL && tcp_tmp_pcb->next == npcb) { \
tcp_tmp_pcb->next = npcb->next; \
break; \
} \
} \
npcb->next = NULL; \
} while(0)
#endif /* LWIP_DEBUG */
#ifdef __cplusplus
}
#endif
#endif /* LWIP_TCP */
#endif /* __LWIP_TCP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/tcp.h | C | oos | 25,657 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_ARCH_H__
#define __LWIP_ARCH_H__
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN 1234
#endif
#ifndef BIG_ENDIAN
#define BIG_ENDIAN 4321
#endif
#include "arch/cc.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef PACK_STRUCT_BEGIN
#define PACK_STRUCT_BEGIN
#endif /* PACK_STRUCT_BEGIN */
#ifndef PACK_STRUCT_END
#define PACK_STRUCT_END
#endif /* PACK_STRUCT_END */
#ifndef PACK_STRUCT_FIELD
#define PACK_STRUCT_FIELD(x) x
#endif /* PACK_STRUCT_FIELD */
#ifndef LWIP_UNUSED_ARG
#define LWIP_UNUSED_ARG(x) (void)x
#endif /* LWIP_UNUSED_ARG */
#ifdef LWIP_PROVIDE_ERRNO
#define EPERM 1 /* Operation not permitted */
#define ENOENT 2 /* No such file or directory */
#define ESRCH 3 /* No such process */
#define EINTR 4 /* Interrupted system call */
#define EIO 5 /* I/O error */
#define ENXIO 6 /* No such device or address */
#define E2BIG 7 /* Arg list too long */
#define ENOEXEC 8 /* Exec format error */
#define EBADF 9 /* Bad file number */
#define ECHILD 10 /* No child processes */
#define EAGAIN 11 /* Try again */
#define ENOMEM 12 /* Out of memory */
#define EACCES 13 /* Permission denied */
#define EFAULT 14 /* Bad address */
#define ENOTBLK 15 /* Block device required */
#define EBUSY 16 /* Device or resource busy */
#define EEXIST 17 /* File exists */
#define EXDEV 18 /* Cross-device link */
#define ENODEV 19 /* No such device */
#define ENOTDIR 20 /* Not a directory */
#define EISDIR 21 /* Is a directory */
#define EINVAL 22 /* Invalid argument */
#define ENFILE 23 /* File table overflow */
#define EMFILE 24 /* Too many open files */
#define ENOTTY 25 /* Not a typewriter */
#define ETXTBSY 26 /* Text file busy */
#define EFBIG 27 /* File too large */
#define ENOSPC 28 /* No space left on device */
#define ESPIPE 29 /* Illegal seek */
#define EROFS 30 /* Read-only file system */
#define EMLINK 31 /* Too many links */
#define EPIPE 32 /* Broken pipe */
#define EDOM 33 /* Math argument out of domain of func */
#define ERANGE 34 /* Math result not representable */
#define EDEADLK 35 /* Resource deadlock would occur */
#define ENAMETOOLONG 36 /* File name too long */
#define ENOLCK 37 /* No record locks available */
#define ENOSYS 38 /* Function not implemented */
#define ENOTEMPTY 39 /* Directory not empty */
#define ELOOP 40 /* Too many symbolic links encountered */
#define EWOULDBLOCK EAGAIN /* Operation would block */
#define ENOMSG 42 /* No message of desired type */
#define EIDRM 43 /* Identifier removed */
#define ECHRNG 44 /* Channel number out of range */
#define EL2NSYNC 45 /* Level 2 not synchronized */
#define EL3HLT 46 /* Level 3 halted */
#define EL3RST 47 /* Level 3 reset */
#define ELNRNG 48 /* Link number out of range */
#define EUNATCH 49 /* Protocol driver not attached */
#define ENOCSI 50 /* No CSI structure available */
#define EL2HLT 51 /* Level 2 halted */
#define EBADE 52 /* Invalid exchange */
#define EBADR 53 /* Invalid request descriptor */
#define EXFULL 54 /* Exchange full */
#define ENOANO 55 /* No anode */
#define EBADRQC 56 /* Invalid request code */
#define EBADSLT 57 /* Invalid slot */
#define EDEADLOCK EDEADLK
#define EBFONT 59 /* Bad font file format */
#define ENOSTR 60 /* Device not a stream */
#define ENODATA 61 /* No data available */
#define ETIME 62 /* Timer expired */
#define ENOSR 63 /* Out of streams resources */
#define ENONET 64 /* Machine is not on the network */
#define ENOPKG 65 /* Package not installed */
#define EREMOTE 66 /* Object is remote */
#define ENOLINK 67 /* Link has been severed */
#define EADV 68 /* Advertise error */
#define ESRMNT 69 /* Srmount error */
#define ECOMM 70 /* Communication error on send */
#define EPROTO 71 /* Protocol error */
#define EMULTIHOP 72 /* Multihop attempted */
#define EDOTDOT 73 /* RFS specific error */
#define EBADMSG 74 /* Not a data message */
#define EOVERFLOW 75 /* Value too large for defined data type */
#define ENOTUNIQ 76 /* Name not unique on network */
#define EBADFD 77 /* File descriptor in bad state */
#define EREMCHG 78 /* Remote address changed */
#define ELIBACC 79 /* Can not access a needed shared library */
#define ELIBBAD 80 /* Accessing a corrupted shared library */
#define ELIBSCN 81 /* .lib section in a.out corrupted */
#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
#define ELIBEXEC 83 /* Cannot exec a shared library directly */
#define EILSEQ 84 /* Illegal byte sequence */
#define ERESTART 85 /* Interrupted system call should be restarted */
#define ESTRPIPE 86 /* Streams pipe error */
#define EUSERS 87 /* Too many users */
#define ENOTSOCK 88 /* Socket operation on non-socket */
#define EDESTADDRREQ 89 /* Destination address required */
#define EMSGSIZE 90 /* Message too long */
#define EPROTOTYPE 91 /* Protocol wrong type for socket */
#define ENOPROTOOPT 92 /* Protocol not available */
#define EPROTONOSUPPORT 93 /* Protocol not supported */
#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
#define EPFNOSUPPORT 96 /* Protocol family not supported */
#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
#define EADDRINUSE 98 /* Address already in use */
#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
#define ENETDOWN 100 /* Network is down */
#define ENETUNREACH 101 /* Network is unreachable */
#define ENETRESET 102 /* Network dropped connection because of reset */
#define ECONNABORTED 103 /* Software caused connection abort */
#define ECONNRESET 104 /* Connection reset by peer */
#define ENOBUFS 105 /* No buffer space available */
#define EISCONN 106 /* Transport endpoint is already connected */
#define ENOTCONN 107 /* Transport endpoint is not connected */
#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
#define ETOOMANYREFS 109 /* Too many references: cannot splice */
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */
#define EHOSTUNREACH 113 /* No route to host */
#define EALREADY 114 /* Operation already in progress */
#define EINPROGRESS 115 /* Operation now in progress */
#define ESTALE 116 /* Stale NFS file handle */
#define EUCLEAN 117 /* Structure needs cleaning */
#define ENOTNAM 118 /* Not a XENIX named type file */
#define ENAVAIL 119 /* No XENIX semaphores available */
#define EISNAM 120 /* Is a named type file */
#define EREMOTEIO 121 /* Remote I/O error */
#define EDQUOT 122 /* Quota exceeded */
#define ENOMEDIUM 123 /* No medium found */
#define EMEDIUMTYPE 124 /* Wrong medium type */
#define ENSROK 0 /* DNS server returned answer with no data */
#define ENSRNODATA 160 /* DNS server returned answer with no data */
#define ENSRFORMERR 161 /* DNS server claims query was misformatted */
#define ENSRSERVFAIL 162 /* DNS server returned general failure */
#define ENSRNOTFOUND 163 /* Domain name not found */
#define ENSRNOTIMP 164 /* DNS server does not implement requested operation */
#define ENSRREFUSED 165 /* DNS server refused query */
#define ENSRBADQUERY 166 /* Misformatted DNS query */
#define ENSRBADNAME 167 /* Misformatted domain name */
#define ENSRBADFAMILY 168 /* Unsupported address family */
#define ENSRBADRESP 169 /* Misformatted DNS reply */
#define ENSRCONNREFUSED 170 /* Could not contact DNS servers */
#define ENSRTIMEOUT 171 /* Timeout while contacting DNS servers */
#define ENSROF 172 /* End of file */
#define ENSRFILE 173 /* Error reading file */
#define ENSRNOMEM 174 /* Out of memory */
#define ENSRDESTRUCTION 175 /* Application terminated lookup */
#define ENSRQUERYDOMAINTOOLONG 176 /* Domain name is too long */
#define ENSRCNAMELOOP 177 /* Domain name is too long */
#ifndef errno
extern int errno;
#endif
#endif /* LWIP_PROVIDE_ERRNO */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_ARCH_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/arch.h | C | oos | 10,240 |
/*
* SETUP: Make sure we define everything we will need.
*
* We have create three types of pools:
* 1) MEMPOOL - standard pools
* 2) MALLOC_MEMPOOL - to be used by mem_malloc in mem.c
* 3) PBUF_MEMPOOL - a mempool of pbuf's, so include space for the pbuf struct
*
* If the include'r doesn't require any special treatment of each of the types
* above, then will declare #2 & #3 to be just standard mempools.
*/
#ifndef LWIP_MALLOC_MEMPOOL
/* This treats "malloc pools" just like any other pool */
#define LWIP_MALLOC_MEMPOOL(num, size) LWIP_MEMPOOL(POOL_##size, num, size, "MALLOC_"#size)
#define LWIP_MALLOC_MEMPOOL_START
#define LWIP_MALLOC_MEMPOOL_END
#endif /* LWIP_MALLOC_MEMPOOL */
#ifndef LWIP_PBUF_MEMPOOL
/* This treats "pbuf pools" just like any other pool.
* Allocates buffers for a pbuf struct AND a payload size */
#define LWIP_PBUF_MEMPOOL(name, num, payload, desc) LWIP_MEMPOOL(name, num, (MEMP_ALIGN_SIZE(sizeof(struct pbuf)) + MEMP_ALIGN_SIZE(payload)), desc)
#endif /* LWIP_PBUF_MEMPOOL */
/*
* A list of internal pools used by LWIP.
*
* LWIP_MEMPOOL(pool_name, number_elements, element_size, pool_description)
* creates a pool name MEMP_pool_name. description is used in stats.c
*/
#if LWIP_RAW
LWIP_MEMPOOL(RAW_PCB, MEMP_NUM_RAW_PCB, sizeof(struct raw_pcb), "RAW_PCB")
#endif /* LWIP_RAW */
#if LWIP_UDP
LWIP_MEMPOOL(UDP_PCB, MEMP_NUM_UDP_PCB, sizeof(struct udp_pcb), "UDP_PCB")
#endif /* LWIP_UDP */
#if LWIP_TCP
LWIP_MEMPOOL(TCP_PCB, MEMP_NUM_TCP_PCB, sizeof(struct tcp_pcb), "TCP_PCB")
LWIP_MEMPOOL(TCP_PCB_LISTEN, MEMP_NUM_TCP_PCB_LISTEN, sizeof(struct tcp_pcb_listen), "TCP_PCB_LISTEN")
LWIP_MEMPOOL(TCP_SEG, MEMP_NUM_TCP_SEG, sizeof(struct tcp_seg), "TCP_SEG")
#endif /* LWIP_TCP */
#if IP_REASSEMBLY
LWIP_MEMPOOL(REASSDATA, MEMP_NUM_REASSDATA, sizeof(struct ip_reassdata), "REASSDATA")
#endif /* IP_REASSEMBLY */
#if LWIP_NETCONN
LWIP_MEMPOOL(NETBUF, MEMP_NUM_NETBUF, sizeof(struct netbuf), "NETBUF")
LWIP_MEMPOOL(NETCONN, MEMP_NUM_NETCONN, sizeof(struct netconn), "NETCONN")
#endif /* LWIP_NETCONN */
#if NO_SYS==0
LWIP_MEMPOOL(TCPIP_MSG_API, MEMP_NUM_TCPIP_MSG_API, sizeof(struct tcpip_msg), "TCPIP_MSG_API")
LWIP_MEMPOOL(TCPIP_MSG_INPKT,MEMP_NUM_TCPIP_MSG_INPKT, sizeof(struct tcpip_msg), "TCPIP_MSG_INPKT")
#endif /* NO_SYS==0 */
#if ARP_QUEUEING
LWIP_MEMPOOL(ARP_QUEUE, MEMP_NUM_ARP_QUEUE, sizeof(struct etharp_q_entry), "ARP_QUEUE")
#endif /* ARP_QUEUEING */
#if LWIP_IGMP
LWIP_MEMPOOL(IGMP_GROUP, MEMP_NUM_IGMP_GROUP, sizeof(struct igmp_group), "IGMP_GROUP")
#endif /* LWIP_IGMP */
#if NO_SYS==0
LWIP_MEMPOOL(SYS_TIMEOUT, MEMP_NUM_SYS_TIMEOUT, sizeof(struct sys_timeo), "SYS_TIMEOUT")
#endif /* NO_SYS==0 */
/*
* A list of pools of pbuf's used by LWIP.
*
* LWIP_PBUF_MEMPOOL(pool_name, number_elements, pbuf_payload_size, pool_description)
* creates a pool name MEMP_pool_name. description is used in stats.c
* This allocates enough space for the pbuf struct and a payload.
* (Example: pbuf_payload_size=0 allocates only size for the struct)
*/
LWIP_PBUF_MEMPOOL(PBUF, MEMP_NUM_PBUF, 0, "PBUF_REF/ROM")
LWIP_PBUF_MEMPOOL(PBUF_POOL, PBUF_POOL_SIZE, PBUF_POOL_BUFSIZE, "PBUF_POOL")
/*
* Allow for user-defined pools; this must be explicitly set in lwipopts.h
* since the default is to NOT look for lwippools.h
*/
#if MEMP_USE_CUSTOM_POOLS
#include "lwippools.h"
#endif /* MEMP_USE_CUSTOM_POOLS */
/*
* REQUIRED CLEANUP: Clear up so we don't get "multiply defined" error later
* (#undef is ignored for something that is not defined)
*/
#undef LWIP_MEMPOOL
#undef LWIP_MALLOC_MEMPOOL
#undef LWIP_MALLOC_MEMPOOL_START
#undef LWIP_MALLOC_MEMPOOL_END
#undef LWIP_PBUF_MEMPOOL
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/memp_std.h | C | oos | 4,034 |
/**
* @file
* Abstract Syntax Notation One (ISO 8824, 8825) codec.
*/
/*
* Copyright (c) 2006 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* Author: Christiaan Simons <christiaan.simons@axon.tv>
*/
#ifndef __LWIP_SNMP_ASN1_H__
#define __LWIP_SNMP_ASN1_H__
#include "lwip/opt.h"
#include "lwip/err.h"
#include "lwip/pbuf.h"
#include "lwip/snmp.h"
#ifdef __cplusplus
extern "C" {
#endif
#define SNMP_ASN1_UNIV (!0x80 | !0x40)
#define SNMP_ASN1_APPLIC (!0x80 | 0x40)
#define SNMP_ASN1_CONTXT ( 0x80 | !0x40)
#define SNMP_ASN1_CONSTR (0x20)
#define SNMP_ASN1_PRIMIT (!0x20)
/* universal tags */
#define SNMP_ASN1_INTEG 2
#define SNMP_ASN1_OC_STR 4
#define SNMP_ASN1_NUL 5
#define SNMP_ASN1_OBJ_ID 6
#define SNMP_ASN1_SEQ 16
/* application specific (SNMP) tags */
#define SNMP_ASN1_IPADDR 0 /* octet string size(4) */
#define SNMP_ASN1_COUNTER 1 /* u32_t */
#define SNMP_ASN1_GAUGE 2 /* u32_t */
#define SNMP_ASN1_TIMETICKS 3 /* u32_t */
#define SNMP_ASN1_OPAQUE 4 /* octet string */
/* context specific (SNMP) tags */
#define SNMP_ASN1_PDU_GET_REQ 0
#define SNMP_ASN1_PDU_GET_NEXT_REQ 1
#define SNMP_ASN1_PDU_GET_RESP 2
#define SNMP_ASN1_PDU_SET_REQ 3
#define SNMP_ASN1_PDU_TRAP 4
err_t snmp_asn1_dec_type(struct pbuf *p, u16_t ofs, u8_t *type);
err_t snmp_asn1_dec_length(struct pbuf *p, u16_t ofs, u8_t *octets_used, u16_t *length);
err_t snmp_asn1_dec_u32t(struct pbuf *p, u16_t ofs, u16_t len, u32_t *value);
err_t snmp_asn1_dec_s32t(struct pbuf *p, u16_t ofs, u16_t len, s32_t *value);
err_t snmp_asn1_dec_oid(struct pbuf *p, u16_t ofs, u16_t len, struct snmp_obj_id *oid);
err_t snmp_asn1_dec_raw(struct pbuf *p, u16_t ofs, u16_t len, u16_t raw_len, u8_t *raw);
void snmp_asn1_enc_length_cnt(u16_t length, u8_t *octets_needed);
void snmp_asn1_enc_u32t_cnt(u32_t value, u16_t *octets_needed);
void snmp_asn1_enc_s32t_cnt(s32_t value, u16_t *octets_needed);
void snmp_asn1_enc_oid_cnt(u8_t ident_len, s32_t *ident, u16_t *octets_needed);
err_t snmp_asn1_enc_type(struct pbuf *p, u16_t ofs, u8_t type);
err_t snmp_asn1_enc_length(struct pbuf *p, u16_t ofs, u16_t length);
err_t snmp_asn1_enc_u32t(struct pbuf *p, u16_t ofs, u8_t octets_needed, u32_t value);
err_t snmp_asn1_enc_s32t(struct pbuf *p, u16_t ofs, u8_t octets_needed, s32_t value);
err_t snmp_asn1_enc_oid(struct pbuf *p, u16_t ofs, u8_t ident_len, s32_t *ident);
err_t snmp_asn1_enc_raw(struct pbuf *p, u16_t ofs, u8_t raw_len, u8_t *raw);
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_SNMP_ASN1_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/snmp_asn1.h | C | oos | 4,030 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_ERR_H__
#define __LWIP_ERR_H__
#include "lwip/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef s8_t err_t;
/* Definitions for error constants. */
#define ERR_OK 0 /* No error, everything OK. */
#define ERR_MEM -1 /* Out of memory error. */
#define ERR_BUF -2 /* Buffer error. */
#define ERR_RTE -3 /* Routing problem. */
#define ERR_IS_FATAL(e) ((e) < ERR_RTE)
#define ERR_ABRT -4 /* Connection aborted. */
#define ERR_RST -5 /* Connection reset. */
#define ERR_CLSD -6 /* Connection closed. */
#define ERR_CONN -7 /* Not connected. */
#define ERR_VAL -8 /* Illegal value. */
#define ERR_ARG -9 /* Illegal argument. */
#define ERR_USE -10 /* Address in use. */
#define ERR_IF -11 /* Low-level netif error */
#define ERR_ISCONN -12 /* Already connected. */
#define ERR_TIMEOUT -13 /* Timeout. */
#define ERR_INPROGRESS -14 /* Operation in progress */
#ifdef LWIP_DEBUG
extern const char *lwip_strerr(err_t err);
#else
#define lwip_strerr(x) ""
#endif /* LWIP_DEBUG */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_ERR_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/err.h | C | oos | 2,971 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_PBUF_H__
#define __LWIP_PBUF_H__
#include "lwip/opt.h"
#include "lwip/err.h"
#ifdef __cplusplus
extern "C" {
#endif
#define PBUF_TRANSPORT_HLEN 20
#define PBUF_IP_HLEN 20
typedef enum {
PBUF_TRANSPORT,
PBUF_IP,
PBUF_LINK,
PBUF_RAW
} pbuf_layer;
typedef enum {
PBUF_RAM, /* pbuf data is stored in RAM */
PBUF_ROM, /* pbuf data is stored in ROM */
PBUF_REF, /* pbuf comes from the pbuf pool */
PBUF_POOL /* pbuf payload refers to RAM */
} pbuf_type;
/** indicates this packet's data should be immediately passed to the application */
#define PBUF_FLAG_PUSH 0x01U
struct pbuf {
/** next pbuf in singly linked pbuf chain */
struct pbuf *next;
/** pointer to the actual data in the buffer */
void *payload;
/**
* total length of this buffer and all next buffers in chain
* belonging to the same packet.
*
* For non-queue packet chains this is the invariant:
* p->tot_len == p->len + (p->next? p->next->tot_len: 0)
*/
u16_t tot_len;
/** length of this buffer */
u16_t len;
/** pbuf_type as u8_t instead of enum to save space */
u8_t /*pbuf_type*/ type;
/** misc flags */
u8_t flags;
/**
* the reference count always equals the number of pointers
* that refer to this pbuf. This can be pointers from an application,
* the stack itself, or pbuf->next pointers from a chain.
*/
u16_t ref;
};
/* Initializes the pbuf module. This call is empty for now, but may not be in future. */
#define pbuf_init()
struct pbuf *pbuf_alloc(pbuf_layer l, u16_t size, pbuf_type type);
void pbuf_realloc(struct pbuf *p, u16_t size);
u8_t pbuf_header(struct pbuf *p, s16_t header_size);
void pbuf_ref(struct pbuf *p);
void pbuf_ref_chain(struct pbuf *p);
u8_t pbuf_free(struct pbuf *p);
u8_t pbuf_clen(struct pbuf *p);
void pbuf_cat(struct pbuf *head, struct pbuf *tail);
void pbuf_chain(struct pbuf *head, struct pbuf *tail);
struct pbuf *pbuf_dechain(struct pbuf *p);
err_t pbuf_copy(struct pbuf *p_to, struct pbuf *p_from);
u16_t pbuf_copy_partial(struct pbuf *p, void *dataptr, u16_t len, u16_t offset);
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_PBUF_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/pbuf.h | C | oos | 3,865 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_UDP_H__
#define __LWIP_UDP_H__
#include "lwip/opt.h"
#if LWIP_UDP /* don't build if not configured for use in lwipopts.h */
#include "lwip/pbuf.h"
#include "lwip/netif.h"
#include "lwip/ip_addr.h"
#include "lwip/ip.h"
#ifdef __cplusplus
extern "C" {
#endif
#define UDP_HLEN 8
/* Fields are (of course) in network byte order. */
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct udp_hdr {
PACK_STRUCT_FIELD(u16_t src);
PACK_STRUCT_FIELD(u16_t dest); /* src/dest UDP ports */
PACK_STRUCT_FIELD(u16_t len);
PACK_STRUCT_FIELD(u16_t chksum);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define UDP_FLAGS_NOCHKSUM 0x01U
#define UDP_FLAGS_UDPLITE 0x02U
#define UDP_FLAGS_CONNECTED 0x04U
struct udp_pcb {
/* Common members of all PCB types */
IP_PCB;
/* Protocol specific PCB members */
struct udp_pcb *next;
u8_t flags;
/* ports are in host byte order */
u16_t local_port, remote_port;
#if LWIP_IGMP
/* outgoing network interface for multicast packets */
struct ip_addr multicast_ip;
#endif /* LWIP_IGMP */
#if LWIP_UDPLITE
/* used for UDP_LITE only */
u16_t chksum_len_rx, chksum_len_tx;
#endif /* LWIP_UDPLITE */
/* receive callback function
* addr and port are in same byte order as in the pcb
* The callback is responsible for freeing the pbuf
* if it's not used any more.
*
* @param arg user supplied argument (udp_pcb.recv_arg)
* @param pcb the udp_pcb which received data
* @param p the packet buffer that was received
* @param addr the remote IP address from which the packet was received
* @param port the remote port from which the packet was received
*/
void (* recv)(void *arg, struct udp_pcb *pcb, struct pbuf *p,
struct ip_addr *addr, u16_t port);
/* user-supplied argument for the recv callback */
void *recv_arg;
};
/* udp_pcbs export for exernal reference (e.g. SNMP agent) */
extern struct udp_pcb *udp_pcbs;
/* The following functions is the application layer interface to the
UDP code. */
struct udp_pcb * udp_new (void);
void udp_remove (struct udp_pcb *pcb);
err_t udp_bind (struct udp_pcb *pcb, struct ip_addr *ipaddr,
u16_t port);
err_t udp_connect (struct udp_pcb *pcb, struct ip_addr *ipaddr,
u16_t port);
void udp_disconnect (struct udp_pcb *pcb);
void udp_recv (struct udp_pcb *pcb,
void (* recv)(void *arg, struct udp_pcb *upcb,
struct pbuf *p,
struct ip_addr *addr,
u16_t port),
void *recv_arg);
err_t udp_sendto_if (struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *dst_ip, u16_t dst_port, struct netif *netif);
err_t udp_sendto (struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *dst_ip, u16_t dst_port);
err_t udp_send (struct udp_pcb *pcb, struct pbuf *p);
#define udp_flags(pcb) ((pcb)->flags)
#define udp_setflags(pcb, f) ((pcb)->flags = (f))
/* The following functions are the lower layer interface to UDP. */
void udp_input (struct pbuf *p, struct netif *inp);
#define udp_init() /* Compatibility define, not init needed. */
#if UDP_DEBUG
void udp_debug_print(struct udp_hdr *udphdr);
#else
#define udp_debug_print(udphdr)
#endif
#ifdef __cplusplus
}
#endif
#endif /* LWIP_UDP */
#endif /* __LWIP_UDP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/udp.h | C | oos | 5,364 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_NETIF_H__
#define __LWIP_NETIF_H__
#include "lwip/opt.h"
#include "lwip/err.h"
#include "lwip/ip_addr.h"
#include "lwip/inet.h"
#include "lwip/pbuf.h"
#if LWIP_DHCP
struct dhcp;
#endif
#if LWIP_AUTOIP
struct autoip;
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Throughout this file, IP addresses are expected to be in
* the same byte order as in IP_PCB. */
/** must be the maximum of all used hardware address lengths
across all types of interfaces in use */
#define NETIF_MAX_HWADDR_LEN 6U
/** TODO: define the use (where, when, whom) of netif flags */
/** whether the network interface is 'up'. this is
* a software flag used to control whether this network
* interface is enabled and processes traffic.
*/
#define NETIF_FLAG_UP 0x01U
/** if set, the netif has broadcast capability */
#define NETIF_FLAG_BROADCAST 0x02U
/** if set, the netif is one end of a point-to-point connection */
#define NETIF_FLAG_POINTTOPOINT 0x04U
/** if set, the interface is configured using DHCP */
#define NETIF_FLAG_DHCP 0x08U
/** if set, the interface has an active link
* (set by the network interface driver) */
#define NETIF_FLAG_LINK_UP 0x10U
/** if set, the netif is an device using ARP */
#define NETIF_FLAG_ETHARP 0x20U
/** if set, the netif has IGMP capability */
#define NETIF_FLAG_IGMP 0x40U
/** Generic data structure used for all lwIP network interfaces.
* The following fields should be filled in by the initialization
* function for the device driver: hwaddr_len, hwaddr[], mtu, flags */
struct netif {
/** pointer to next in linked list */
struct netif *next;
/** IP address configuration in network byte order */
struct ip_addr ip_addr;
struct ip_addr netmask;
struct ip_addr gw;
/** This function is called by the network device driver
* to pass a packet up the TCP/IP stack. */
err_t (* input)(struct pbuf *p, struct netif *inp);
/** This function is called by the IP module when it wants
* to send a packet on the interface. This function typically
* first resolves the hardware address, then sends the packet. */
err_t (* output)(struct netif *netif, struct pbuf *p,
struct ip_addr *ipaddr);
/** This function is called by the ARP module when it wants
* to send a packet on the interface. This function outputs
* the pbuf as-is on the link medium. */
err_t (* linkoutput)(struct netif *netif, struct pbuf *p);
#if LWIP_NETIF_STATUS_CALLBACK
/** This function is called when the netif state is set to up or down
*/
void (* status_callback)(struct netif *netif);
#endif /* LWIP_NETIF_STATUS_CALLBACK */
#if LWIP_NETIF_LINK_CALLBACK
/** This function is called when the netif link is set to up or down
*/
void (* link_callback)(struct netif *netif);
#endif /* LWIP_NETIF_LINK_CALLBACK */
/** This field can be set by the device driver and could point
* to state information for the device. */
void *state;
#if LWIP_DHCP
/** the DHCP client state information for this netif */
struct dhcp *dhcp;
#endif /* LWIP_DHCP */
#if LWIP_AUTOIP
/** the AutoIP client state information for this netif */
struct autoip *autoip;
#endif
#if LWIP_NETIF_HOSTNAME
/* the hostname for this netif, NULL is a valid value */
char* hostname;
#endif /* LWIP_NETIF_HOSTNAME */
/** number of bytes used in hwaddr */
u8_t hwaddr_len;
/** link level hardware address of this interface */
u8_t hwaddr[NETIF_MAX_HWADDR_LEN];
/** maximum transfer unit (in bytes) */
u16_t mtu;
/** flags (see NETIF_FLAG_ above) */
u8_t flags;
/** descriptive abbreviation */
char name[2];
/** number of this interface */
u8_t num;
#if LWIP_SNMP
/** link type (from "snmp_ifType" enum from snmp.h) */
u8_t link_type;
/** (estimate) link speed */
u32_t link_speed;
/** timestamp at last change made (up/down) */
u32_t ts;
/** counters */
u32_t ifinoctets;
u32_t ifinucastpkts;
u32_t ifinnucastpkts;
u32_t ifindiscards;
u32_t ifoutoctets;
u32_t ifoutucastpkts;
u32_t ifoutnucastpkts;
u32_t ifoutdiscards;
#endif /* LWIP_SNMP */
#if LWIP_IGMP
/* This function could be called to add or delete a entry in the multicast filter table of the ethernet MAC.*/
err_t (*igmp_mac_filter)( struct netif *netif, struct ip_addr *group, u8_t action);
#endif /* LWIP_IGMP */
#if LWIP_NETIF_HWADDRHINT
u8_t *addr_hint;
#endif /* LWIP_NETIF_HWADDRHINT */
};
#if LWIP_SNMP
#define NETIF_INIT_SNMP(netif, type, speed) \
/* use "snmp_ifType" enum from snmp.h for "type", snmp_ifType_ethernet_csmacd by example */ \
netif->link_type = type; \
/* your link speed here (units: bits per second) */ \
netif->link_speed = speed; \
netif->ts = 0; \
netif->ifinoctets = 0; \
netif->ifinucastpkts = 0; \
netif->ifinnucastpkts = 0; \
netif->ifindiscards = 0; \
netif->ifoutoctets = 0; \
netif->ifoutucastpkts = 0; \
netif->ifoutnucastpkts = 0; \
netif->ifoutdiscards = 0
#else /* LWIP_SNMP */
#define NETIF_INIT_SNMP(netif, type, speed)
#endif /* LWIP_SNMP */
/** The list of network interfaces. */
extern struct netif *netif_list;
/** The default network interface. */
extern struct netif *netif_default;
#define netif_init() /* Compatibility define, not init needed. */
struct netif *netif_add(struct netif *netif, struct ip_addr *ipaddr, struct ip_addr *netmask,
struct ip_addr *gw,
void *state,
err_t (* init)(struct netif *netif),
err_t (* input)(struct pbuf *p, struct netif *netif));
void
netif_set_addr(struct netif *netif,struct ip_addr *ipaddr, struct ip_addr *netmask,
struct ip_addr *gw);
void netif_remove(struct netif * netif);
/* Returns a network interface given its name. The name is of the form
"et0", where the first two letters are the "name" field in the
netif structure, and the digit is in the num field in the same
structure. */
struct netif *netif_find(char *name);
void netif_set_default(struct netif *netif);
void netif_set_ipaddr(struct netif *netif, struct ip_addr *ipaddr);
void netif_set_netmask(struct netif *netif, struct ip_addr *netmask);
void netif_set_gw(struct netif *netif, struct ip_addr *gw);
void netif_set_up(struct netif *netif);
void netif_set_down(struct netif *netif);
u8_t netif_is_up(struct netif *netif);
#if LWIP_NETIF_STATUS_CALLBACK
/*
* Set callback to be called when interface is brought up/down
*/
void netif_set_status_callback(struct netif *netif, void (* status_callback)(struct netif *netif));
#endif /* LWIP_NETIF_STATUS_CALLBACK */
#if LWIP_NETIF_LINK_CALLBACK
void netif_set_link_up(struct netif *netif);
void netif_set_link_down(struct netif *netif);
u8_t netif_is_link_up(struct netif *netif);
/*
* Set callback to be called when link is brought up/down
*/
void netif_set_link_callback(struct netif *netif, void (* link_callback)(struct netif *netif));
#endif /* LWIP_NETIF_LINK_CALLBACK */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_NETIF_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/netif.h | C | oos | 8,821 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*/
/*
* This is the interface to the platform specific serial IO module
* It needs to be implemented by those platforms which need SLIP or PPP
*/
#include "lwip/arch.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __sio_fd_t_defined
typedef void * sio_fd_t;
#endif
#ifndef sio_open
sio_fd_t sio_open(u8_t);
#endif
#ifndef sio_send
void sio_send(u8_t, sio_fd_t);
#endif
#ifndef sio_recv
u8_t sio_recv(sio_fd_t);
#endif
#ifndef sio_read
u32_t sio_read(sio_fd_t, u8_t *, u32_t);
#endif
#ifndef sio_write
u32_t sio_write(sio_fd_t, u8_t *, u32_t);
#endif
#ifndef sio_read_abort
void sio_read_abort(sio_fd_t);
#endif
#ifdef __cplusplus
}
#endif
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/sio.h | C | oos | 2,285 |
/**
* @file
*
* lwIP Options Configuration
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_OPT_H__
#define __LWIP_OPT_H__
/*
* Include user defined options first. Anything not defined in these files
* will be set to standard values. Override anything you dont like!
*/
#include "lwipopts.h"
#include "lwip/debug.h"
/*
-----------------------------------------------
---------- Platform specific locking ----------
-----------------------------------------------
*/
/**
* SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain
* critical regions during buffer allocation, deallocation and memory
* allocation and deallocation.
*/
#ifndef SYS_LIGHTWEIGHT_PROT
#define SYS_LIGHTWEIGHT_PROT 0
#endif
/**
* NO_SYS==1: Provides VERY minimal functionality. Otherwise,
* use lwIP facilities.
*/
#ifndef NO_SYS
#define NO_SYS 0
#endif
/**
* MEMCPY: override this if you have a faster implementation at hand than the
* one included in your C library
*/
#ifndef MEMCPY
#define MEMCPY(dst,src,len) memcpy(dst,src,len)
#endif
/**
* SMEMCPY: override this with care! Some compilers (e.g. gcc) can inline a
* call to memcpy() if the length is known at compile time and is small.
*/
#ifndef SMEMCPY
#define SMEMCPY(dst,src,len) memcpy(dst,src,len)
#endif
/*
------------------------------------
---------- Memory options ----------
------------------------------------
*/
/**
* MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library
* instead of the lwip internal allocator. Can save code size if you
* already use it.
*/
#ifndef MEM_LIBC_MALLOC
#define MEM_LIBC_MALLOC 0
#endif
/**
* MEM_ALIGNMENT: should be set to the alignment of the CPU
* 4 byte alignment -> #define MEM_ALIGNMENT 4
* 2 byte alignment -> #define MEM_ALIGNMENT 2
*/
#ifndef MEM_ALIGNMENT
#define MEM_ALIGNMENT 1
#endif
/**
* MEM_SIZE: the size of the heap memory. If the application will send
* a lot of data that needs to be copied, this should be set high.
*/
#ifndef MEM_SIZE
#define MEM_SIZE 1600
#endif
/**
* MEMP_OVERFLOW_CHECK: memp overflow protection reserves a configurable
* amount of bytes before and after each memp element in every pool and fills
* it with a prominent default value.
* MEMP_OVERFLOW_CHECK == 0 no checking
* MEMP_OVERFLOW_CHECK == 1 checks each element when it is freed
* MEMP_OVERFLOW_CHECK >= 2 checks each element in every pool every time
* memp_malloc() or memp_free() is called (useful but slow!)
*/
#ifndef MEMP_OVERFLOW_CHECK
#define MEMP_OVERFLOW_CHECK 0
#endif
/**
* MEMP_SANITY_CHECK==1: run a sanity check after each memp_free() to make
* sure that there are no cycles in the linked lists.
*/
#ifndef MEMP_SANITY_CHECK
#define MEMP_SANITY_CHECK 0
#endif
/**
* MEM_USE_POOLS==1: Use an alternative to malloc() by allocating from a set
* of memory pools of various sizes. When mem_malloc is called, an element of
* the smallest pool that can provide the lenght needed is returned.
*/
#ifndef MEM_USE_POOLS
#define MEM_USE_POOLS 0
#endif
/**
* MEMP_USE_CUSTOM_POOLS==1: whether to include a user file lwippools.h
* that defines additional pools beyond the "standard" ones required
* by lwIP. If you set this to 1, you must have lwippools.h in your
* inlude path somewhere.
*/
#ifndef MEMP_USE_CUSTOM_POOLS
#define MEMP_USE_CUSTOM_POOLS 0
#endif
/*
------------------------------------------------
---------- Internal Memory Pool Sizes ----------
------------------------------------------------
*/
/**
* MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF).
* If the application sends a lot of data out of ROM (or other static memory),
* this should be set high.
*/
#ifndef MEMP_NUM_PBUF
#define MEMP_NUM_PBUF 16
#endif
/**
* MEMP_NUM_RAW_PCB: Number of raw connection PCBs
* (requires the LWIP_RAW option)
*/
#ifndef MEMP_NUM_RAW_PCB
#define MEMP_NUM_RAW_PCB 4
#endif
/**
* MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One
* per active UDP "connection".
* (requires the LWIP_UDP option)
*/
#ifndef MEMP_NUM_UDP_PCB
#define MEMP_NUM_UDP_PCB 4
#endif
/**
* MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections.
* (requires the LWIP_TCP option)
*/
#ifndef MEMP_NUM_TCP_PCB
#define MEMP_NUM_TCP_PCB 5
#endif
/**
* MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections.
* (requires the LWIP_TCP option)
*/
#ifndef MEMP_NUM_TCP_PCB_LISTEN
#define MEMP_NUM_TCP_PCB_LISTEN 8
#endif
/**
* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments.
* (requires the LWIP_TCP option)
*/
#ifndef MEMP_NUM_TCP_SEG
#define MEMP_NUM_TCP_SEG 16
#endif
/**
* MEMP_NUM_REASSDATA: the number of simultaneously IP packets queued for
* reassembly (whole packets, not fragments!)
*/
#ifndef MEMP_NUM_REASSDATA
#define MEMP_NUM_REASSDATA 5
#endif
/**
* MEMP_NUM_ARP_QUEUE: the number of simulateously queued outgoing
* packets (pbufs) that are waiting for an ARP request (to resolve
* their destination address) to finish.
* (requires the ARP_QUEUEING option)
*/
#ifndef MEMP_NUM_ARP_QUEUE
#define MEMP_NUM_ARP_QUEUE 30
#endif
/**
* MEMP_NUM_IGMP_GROUP: The number of multicast groups whose network interfaces
* can be members et the same time (one per netif - allsystems group -, plus one
* per netif membership).
* (requires the LWIP_IGMP option)
*/
#ifndef MEMP_NUM_IGMP_GROUP
#define MEMP_NUM_IGMP_GROUP 8
#endif
/**
* MEMP_NUM_SYS_TIMEOUT: the number of simulateously active timeouts.
* (requires NO_SYS==0)
*/
#ifndef MEMP_NUM_SYS_TIMEOUT
#define MEMP_NUM_SYS_TIMEOUT 3
#endif
/**
* MEMP_NUM_NETBUF: the number of struct netbufs.
* (only needed if you use the sequential API, like api_lib.c)
*/
#ifndef MEMP_NUM_NETBUF
#define MEMP_NUM_NETBUF 2
#endif
/**
* MEMP_NUM_NETCONN: the number of struct netconns.
* (only needed if you use the sequential API, like api_lib.c)
*/
#ifndef MEMP_NUM_NETCONN
#define MEMP_NUM_NETCONN 4
#endif
/**
* MEMP_NUM_TCPIP_MSG_API: the number of struct tcpip_msg, which are used
* for callback/timeout API communication.
* (only needed if you use tcpip.c)
*/
#ifndef MEMP_NUM_TCPIP_MSG_API
#define MEMP_NUM_TCPIP_MSG_API 8
#endif
/**
* MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used
* for incoming packets.
* (only needed if you use tcpip.c)
*/
#ifndef MEMP_NUM_TCPIP_MSG_INPKT
#define MEMP_NUM_TCPIP_MSG_INPKT 8
#endif
/**
* PBUF_POOL_SIZE: the number of buffers in the pbuf pool.
*/
#ifndef PBUF_POOL_SIZE
#define PBUF_POOL_SIZE 16
#endif
/*
---------------------------------
---------- ARP options ----------
---------------------------------
*/
/**
* LWIP_ARP==1: Enable ARP functionality.
*/
#ifndef LWIP_ARP
#define LWIP_ARP 1
#endif
/**
* ARP_TABLE_SIZE: Number of active MAC-IP address pairs cached.
*/
#ifndef ARP_TABLE_SIZE
#define ARP_TABLE_SIZE 10
#endif
/**
* ARP_QUEUEING==1: Outgoing packets are queued during hardware address
* resolution.
*/
#ifndef ARP_QUEUEING
#define ARP_QUEUEING 1
#endif
/**
* ETHARP_TRUST_IP_MAC==1: Incoming IP packets cause the ARP table to be
* updated with the source MAC and IP addresses supplied in the packet.
* You may want to disable this if you do not trust LAN peers to have the
* correct addresses, or as a limited approach to attempt to handle
* spoofing. If disabled, lwIP will need to make a new ARP request if
* the peer is not already in the ARP table, adding a little latency.
*/
#ifndef ETHARP_TRUST_IP_MAC
#define ETHARP_TRUST_IP_MAC 1
#endif
/*
--------------------------------
---------- IP options ----------
--------------------------------
*/
/**
* IP_FORWARD==1: Enables the ability to forward IP packets across network
* interfaces. If you are going to run lwIP on a device with only one network
* interface, define this to 0.
*/
#ifndef IP_FORWARD
#define IP_FORWARD 0
#endif
/**
* IP_OPTIONS_ALLOWED: Defines the behavior for IP options.
* IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped.
* IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed).
*/
#ifndef IP_OPTIONS_ALLOWED
#define IP_OPTIONS_ALLOWED 1
#endif
/**
* IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that
* this option does not affect outgoing packet sizes, which can be controlled
* via IP_FRAG.
*/
#ifndef IP_REASSEMBLY
#define IP_REASSEMBLY 1
#endif
/**
* IP_FRAG==1: Fragment outgoing IP packets if their size exceeds MTU. Note
* that this option does not affect incoming packet sizes, which can be
* controlled via IP_REASSEMBLY.
*/
#ifndef IP_FRAG
#define IP_FRAG 1
#endif
/**
* IP_REASS_MAXAGE: Maximum time (in multiples of IP_TMR_INTERVAL - so seconds, normally)
* a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived
* in this time, the whole packet is discarded.
*/
#ifndef IP_REASS_MAXAGE
#define IP_REASS_MAXAGE 3
#endif
/**
* IP_REASS_MAX_PBUFS: Total maximum amount of pbufs waiting to be reassembled.
* Since the received pbufs are enqueued, be sure to configure
* PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive
* packets even if the maximum amount of fragments is enqueued for reassembly!
*/
#ifndef IP_REASS_MAX_PBUFS
#define IP_REASS_MAX_PBUFS 10
#endif
/**
* IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP
* fragmentation. Otherwise pbufs are allocated and reference the original
* packet data to be fragmented.
*/
#ifndef IP_FRAG_USES_STATIC_BUF
#define IP_FRAG_USES_STATIC_BUF 1
#endif
/**
* IP_FRAG_MAX_MTU: Assumed max MTU on any interface for IP frag buffer
* (requires IP_FRAG_USES_STATIC_BUF==1)
*/
#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MAX_MTU)
#define IP_FRAG_MAX_MTU 1500
#endif
/**
* IP_DEFAULT_TTL: Default value for Time-To-Live used by transport layers.
*/
#ifndef IP_DEFAULT_TTL
#define IP_DEFAULT_TTL 255
#endif
/*
----------------------------------
---------- ICMP options ----------
----------------------------------
*/
/**
* LWIP_ICMP==1: Enable ICMP module inside the IP stack.
* Be careful, disable that make your product non-compliant to RFC1122
*/
#ifndef LWIP_ICMP
#define LWIP_ICMP 1
#endif
/**
* ICMP_TTL: Default value for Time-To-Live used by ICMP packets.
*/
#ifndef ICMP_TTL
#define ICMP_TTL (IP_DEFAULT_TTL)
#endif
/*
---------------------------------
---------- RAW options ----------
---------------------------------
*/
/**
* LWIP_RAW==1: Enable application layer to hook into the IP layer itself.
*/
#ifndef LWIP_RAW
#define LWIP_RAW 1
#endif
/**
* LWIP_RAW==1: Enable application layer to hook into the IP layer itself.
*/
#ifndef RAW_TTL
#define RAW_TTL (IP_DEFAULT_TTL)
#endif
/*
----------------------------------
---------- DHCP options ----------
----------------------------------
*/
/**
* LWIP_DHCP==1: Enable DHCP module.
*/
#ifndef LWIP_DHCP
#define LWIP_DHCP 0
#endif
/**
* DHCP_DOES_ARP_CHECK==1: Do an ARP check on the offered address.
*/
#ifndef DHCP_DOES_ARP_CHECK
#define DHCP_DOES_ARP_CHECK ((LWIP_DHCP) && (LWIP_ARP))
#endif
/*
------------------------------------
---------- AUTOIP options ----------
------------------------------------
*/
/**
* LWIP_AUTOIP==1: Enable AUTOIP module.
*/
#ifndef LWIP_AUTOIP
#define LWIP_AUTOIP 0
#endif
/**
* LWIP_DHCP_AUTOIP_COOP==1: Allow DHCP and AUTOIP to be both enabled on
* the same interface at the same time.
*/
#ifndef LWIP_DHCP_AUTOIP_COOP
#define LWIP_DHCP_AUTOIP_COOP 0
#endif
/*
----------------------------------
---------- SNMP options ----------
----------------------------------
*/
/**
* LWIP_SNMP==1: Turn on SNMP module. UDP must be available for SNMP
* transport.
*/
#ifndef LWIP_SNMP
#define LWIP_SNMP 0
#endif
/**
* SNMP_CONCURRENT_REQUESTS: Number of concurrent requests the module will
* allow. At least one request buffer is required.
*/
#ifndef SNMP_CONCURRENT_REQUESTS
#define SNMP_CONCURRENT_REQUESTS 1
#endif
/**
* SNMP_TRAP_DESTINATIONS: Number of trap destinations. At least one trap
* destination is required
*/
#ifndef SNMP_TRAP_DESTINATIONS
#define SNMP_TRAP_DESTINATIONS 1
#endif
/**
* SNMP_PRIVATE_MIB:
*/
#ifndef SNMP_PRIVATE_MIB
#define SNMP_PRIVATE_MIB 0
#endif
/**
* Only allow SNMP write actions that are 'safe' (e.g. disabeling netifs is not
* a safe action and disabled when SNMP_SAFE_REQUESTS = 1).
* Unsafe requests are disabled by default!
*/
#ifndef SNMP_SAFE_REQUESTS
#define SNMP_SAFE_REQUESTS 1
#endif
/*
----------------------------------
---------- IGMP options ----------
----------------------------------
*/
/**
* LWIP_IGMP==1: Turn on IGMP module.
*/
#ifndef LWIP_IGMP
#define LWIP_IGMP 0
#endif
/*
----------------------------------
---------- DNS options -----------
----------------------------------
*/
/**
* LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS
* transport.
*/
#ifndef LWIP_DNS
#define LWIP_DNS 0
#endif
/** DNS maximum number of entries to maintain locally. */
#ifndef DNS_TABLE_SIZE
#define DNS_TABLE_SIZE 4
#endif
/** DNS maximum host name length supported in the name table. */
#ifndef DNS_MAX_NAME_LENGTH
#define DNS_MAX_NAME_LENGTH 256
#endif
/** The maximum of DNS servers */
#ifndef DNS_MAX_SERVERS
#define DNS_MAX_SERVERS 2
#endif
/** DNS do a name checking between the query and the response. */
#ifndef DNS_DOES_NAME_CHECK
#define DNS_DOES_NAME_CHECK 1
#endif
/** DNS use a local buffer if DNS_USES_STATIC_BUF=0, a static one if
DNS_USES_STATIC_BUF=1, or a dynamic one if DNS_USES_STATIC_BUF=2.
The buffer will be of size DNS_MSG_SIZE */
#ifndef DNS_USES_STATIC_BUF
#define DNS_USES_STATIC_BUF 1
#endif
/** DNS message max. size. Default value is RFC compliant. */
#ifndef DNS_MSG_SIZE
#define DNS_MSG_SIZE 512
#endif
/*
---------------------------------
---------- UDP options ----------
---------------------------------
*/
/**
* LWIP_UDP==1: Turn on UDP.
*/
#ifndef LWIP_UDP
#define LWIP_UDP 1
#endif
/**
* LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP)
*/
#ifndef LWIP_UDPLITE
#define LWIP_UDPLITE 0
#endif
/**
* UDP_TTL: Default Time-To-Live value.
*/
#ifndef UDP_TTL
#define UDP_TTL (IP_DEFAULT_TTL)
#endif
/*
---------------------------------
---------- TCP options ----------
---------------------------------
*/
/**
* LWIP_TCP==1: Turn on TCP.
*/
#ifndef LWIP_TCP
#define LWIP_TCP 1
#endif
/**
* TCP_TTL: Default Time-To-Live value.
*/
#ifndef TCP_TTL
#define TCP_TTL (IP_DEFAULT_TTL)
#endif
/**
* TCP_WND: The size of a TCP window.
*/
#ifndef TCP_WND
#define TCP_WND 2048
#endif
/**
* TCP_MAXRTX: Maximum number of retransmissions of data segments.
*/
#ifndef TCP_MAXRTX
#define TCP_MAXRTX 12
#endif
/**
* TCP_SYNMAXRTX: Maximum number of retransmissions of SYN segments.
*/
#ifndef TCP_SYNMAXRTX
#define TCP_SYNMAXRTX 6
#endif
/**
* TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order.
* Define to 0 if your device is low on memory.
*/
#ifndef TCP_QUEUE_OOSEQ
#define TCP_QUEUE_OOSEQ 1
#endif
/**
* TCP_MSS: TCP Maximum segment size. (default is 128, a *very*
* conservative default.)
* For the receive side, this MSS is advertised to the remote side
* when opening a connection. For the transmit size, this MSS sets
* an upper limit on the MSS advertised by the remote host.
*/
#ifndef TCP_MSS
#define TCP_MSS 128
#endif
/**
* TCP_CALCULATE_EFF_SEND_MSS: "The maximum size of a segment that TCP really
* sends, the 'effective send MSS,' MUST be the smaller of the send MSS (which
* reflects the available reassembly buffer size at the remote host) and the
* largest size permitted by the IP layer" (RFC 1122)
* Setting this to 1 enables code that checks TCP_MSS against the MTU of the
* netif used for a connection and limits the MSS if it would be too big otherwise.
*/
#ifndef TCP_CALCULATE_EFF_SEND_MSS
#define TCP_CALCULATE_EFF_SEND_MSS 1
#endif
/**
* TCP_SND_BUF: TCP sender buffer space (bytes).
*/
#ifndef TCP_SND_BUF
#define TCP_SND_BUF 256
#endif
/**
* TCP_SND_QUEUELEN: TCP sender buffer space (pbufs). This must be at least
* as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work.
*/
#ifndef TCP_SND_QUEUELEN
#define TCP_SND_QUEUELEN (4 * (TCP_SND_BUF/TCP_MSS))
#endif
/**
* TCP_SNDLOWAT: TCP writable space (bytes). This must be less than or equal
* to TCP_SND_BUF. It is the amount of space which must be available in the
* TCP snd_buf for select to return writable.
*/
#ifndef TCP_SNDLOWAT
#define TCP_SNDLOWAT (TCP_SND_BUF/2)
#endif
/**
* TCP_LISTEN_BACKLOG: Enable the backlog option for tcp listen pcb.
*/
#ifndef TCP_LISTEN_BACKLOG
#define TCP_LISTEN_BACKLOG 0
#endif
/**
* The maximum allowed backlog for TCP listen netconns.
* This backlog is used unless another is explicitly specified.
* 0xff is the maximum (u8_t).
*/
#ifndef TCP_DEFAULT_LISTEN_BACKLOG
#define TCP_DEFAULT_LISTEN_BACKLOG 0xff
#endif
/**
* LWIP_EVENT_API and LWIP_CALLBACK_API: Only one of these should be set to 1.
* LWIP_EVENT_API==1: The user defines lwip_tcp_event() to receive all
* events (accept, sent, etc) that happen in the system.
* LWIP_CALLBACK_API==1: The PCB callback function is called directly
* for the event.
*/
#ifndef LWIP_EVENT_API
#define LWIP_EVENT_API 0
#define LWIP_CALLBACK_API 1
#else
#define LWIP_EVENT_API 1
#define LWIP_CALLBACK_API 0
#endif
/*
----------------------------------
---------- Pbuf options ----------
----------------------------------
*/
/**
* PBUF_LINK_HLEN: the number of bytes that should be allocated for a
* link level header. The default is 14, the standard value for
* Ethernet.
*/
#ifndef PBUF_LINK_HLEN
#define PBUF_LINK_HLEN 14
#endif
/**
* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. The default is
* designed to accomodate single full size TCP frame in one pbuf, including
* TCP_MSS, IP header, and link header.
*/
#ifndef PBUF_POOL_BUFSIZE
#define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_HLEN)
#endif
/*
------------------------------------------------
---------- Network Interfaces options ----------
------------------------------------------------
*/
/**
* LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname
* field.
*/
#ifndef LWIP_NETIF_HOSTNAME
#define LWIP_NETIF_HOSTNAME 0
#endif
/**
* LWIP_NETIF_API==1: Support netif api (in netifapi.c)
*/
#ifndef LWIP_NETIF_API
#define LWIP_NETIF_API 0
#endif
/**
* LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface
* changes its up/down status (i.e., due to DHCP IP acquistion)
*/
#ifndef LWIP_NETIF_STATUS_CALLBACK
#define LWIP_NETIF_STATUS_CALLBACK 0
#endif
/**
* LWIP_NETIF_LINK_CALLBACK==1: Support a callback function from an interface
* whenever the link changes (i.e., link down)
*/
#ifndef LWIP_NETIF_LINK_CALLBACK
#define LWIP_NETIF_LINK_CALLBACK 0
#endif
/**
* LWIP_NETIF_HWADDRHINT==1: Cache link-layer-address hints (e.g. table
* indices) in struct netif. TCP and UDP can make use of this to prevent
* scanning the ARP table for every sent packet. While this is faster for big
* ARP tables or many concurrent connections, it might be counterproductive
* if you have a tiny ARP table or if there never are concurrent connections.
*/
#ifndef LWIP_NETIF_HWADDRHINT
#define LWIP_NETIF_HWADDRHINT 0
#endif
/*
------------------------------------
---------- LOOPIF options ----------
------------------------------------
*/
/**
* LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1) and loopif.c
*/
#ifndef LWIP_HAVE_LOOPIF
#define LWIP_HAVE_LOOPIF 0
#endif
/**
* LWIP_LOOPIF_MULTITHREADING: Indicates whether threading is enabled in
* the system, as LOOPIF must change how it behaves depending on this setting.
* Setting this is needed to avoid reentering non-reentrant functions like
* tcp_input().
* LWIP_LOOPIF_MULTITHREADING==1: Indicates that the user is using a
* multithreaded environment like tcpip.c. In this case, netif->input()
* is called directly.
* LWIP_LOOPIF_MULTITHREADING==0: Indicates a polling (or NO_SYS) setup.
* The packets are put on a list and loopif_poll() must be called in
* the main application loop.
*/
#ifndef LWIP_LOOPIF_MULTITHREADING
#define LWIP_LOOPIF_MULTITHREADING 1
#endif
/*
------------------------------------
---------- Thread options ----------
------------------------------------
*/
/**
* TCPIP_THREAD_NAME: The name assigned to the main tcpip thread.
*/
#ifndef TCPIP_THREAD_NAME
#define TCPIP_THREAD_NAME "tcpip_thread"
#endif
/**
* TCPIP_THREAD_STACKSIZE: The stack size used by the main tcpip thread.
* The stack size value itself is platform-dependent, but is passed to
* sys_thread_new() when the thread is created.
*/
#ifndef TCPIP_THREAD_STACKSIZE
#define TCPIP_THREAD_STACKSIZE 0
#endif
/**
* TCPIP_THREAD_PRIO: The priority assigned to the main tcpip thread.
* The priority value itself is platform-dependent, but is passed to
* sys_thread_new() when the thread is created.
*/
#ifndef TCPIP_THREAD_PRIO
#define TCPIP_THREAD_PRIO 1
#endif
/**
* TCPIP_MBOX_SIZE: The mailbox size for the tcpip thread messages
* The queue size value itself is platform-dependent, but is passed to
* sys_mbox_new() when tcpip_init is called.
*/
#ifndef TCPIP_MBOX_SIZE
#define TCPIP_MBOX_SIZE 0
#endif
/**
* SLIPIF_THREAD_NAME: The name assigned to the slipif_loop thread.
*/
#ifndef SLIPIF_THREAD_NAME
#define SLIPIF_THREAD_NAME "slipif_loop"
#endif
/**
* SLIP_THREAD_STACKSIZE: The stack size used by the slipif_loop thread.
* The stack size value itself is platform-dependent, but is passed to
* sys_thread_new() when the thread is created.
*/
#ifndef SLIPIF_THREAD_STACKSIZE
#define SLIPIF_THREAD_STACKSIZE 0
#endif
/**
* SLIPIF_THREAD_PRIO: The priority assigned to the slipif_loop thread.
* The priority value itself is platform-dependent, but is passed to
* sys_thread_new() when the thread is created.
*/
#ifndef SLIPIF_THREAD_PRIO
#define SLIPIF_THREAD_PRIO 1
#endif
/**
* PPP_THREAD_NAME: The name assigned to the pppMain thread.
*/
#ifndef PPP_THREAD_NAME
#define PPP_THREAD_NAME "pppMain"
#endif
/**
* PPP_THREAD_STACKSIZE: The stack size used by the pppMain thread.
* The stack size value itself is platform-dependent, but is passed to
* sys_thread_new() when the thread is created.
*/
#ifndef PPP_THREAD_STACKSIZE
#define PPP_THREAD_STACKSIZE 0
#endif
/**
* PPP_THREAD_PRIO: The priority assigned to the pppMain thread.
* The priority value itself is platform-dependent, but is passed to
* sys_thread_new() when the thread is created.
*/
#ifndef PPP_THREAD_PRIO
#define PPP_THREAD_PRIO 1
#endif
/**
* DEFAULT_THREAD_NAME: The name assigned to any other lwIP thread.
*/
#ifndef DEFAULT_THREAD_NAME
#define DEFAULT_THREAD_NAME "lwIP"
#endif
/**
* DEFAULT_THREAD_STACKSIZE: The stack size used by any other lwIP thread.
* The stack size value itself is platform-dependent, but is passed to
* sys_thread_new() when the thread is created.
*/
#ifndef DEFAULT_THREAD_STACKSIZE
#define DEFAULT_THREAD_STACKSIZE 0
#endif
/**
* DEFAULT_THREAD_PRIO: The priority assigned to any other lwIP thread.
* The priority value itself is platform-dependent, but is passed to
* sys_thread_new() when the thread is created.
*/
#ifndef DEFAULT_THREAD_PRIO
#define DEFAULT_THREAD_PRIO 1
#endif
/**
* DEFAULT_RAW_RECVMBOX_SIZE: The mailbox size for the incoming packets on a
* NETCONN_RAW. The queue size value itself is platform-dependent, but is passed
* to sys_mbox_new() when the recvmbox is created.
*/
#ifndef DEFAULT_RAW_RECVMBOX_SIZE
#define DEFAULT_RAW_RECVMBOX_SIZE 0
#endif
/**
* DEFAULT_UDP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a
* NETCONN_UDP. The queue size value itself is platform-dependent, but is passed
* to sys_mbox_new() when the recvmbox is created.
*/
#ifndef DEFAULT_UDP_RECVMBOX_SIZE
#define DEFAULT_UDP_RECVMBOX_SIZE 0
#endif
/**
* DEFAULT_TCP_RECVMBOX_SIZE: The mailbox size for the incoming packets on a
* NETCONN_TCP. The queue size value itself is platform-dependent, but is passed
* to sys_mbox_new() when the recvmbox is created.
*/
#ifndef DEFAULT_TCP_RECVMBOX_SIZE
#define DEFAULT_TCP_RECVMBOX_SIZE 0
#endif
/**
* DEFAULT_ACCEPTMBOX_SIZE: The mailbox size for the incoming connections.
* The queue size value itself is platform-dependent, but is passed to
* sys_mbox_new() when the acceptmbox is created.
*/
#ifndef DEFAULT_ACCEPTMBOX_SIZE
#define DEFAULT_ACCEPTMBOX_SIZE 0
#endif
/*
----------------------------------------------
---------- Sequential layer options ----------
----------------------------------------------
*/
/**
* LWIP_TCPIP_CORE_LOCKING: (EXPERIMENTAL!)
* Don't use it if you're not an active lwIP project member
*/
#ifndef LWIP_TCPIP_CORE_LOCKING
#define LWIP_TCPIP_CORE_LOCKING 0
#endif
/**
* LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c)
*/
#ifndef LWIP_NETCONN
#define LWIP_NETCONN 1
#endif
/*
------------------------------------
---------- Socket options ----------
------------------------------------
*/
/**
* LWIP_SOCKET==1: Enable Socket API (require to use sockets.c)
*/
#ifndef LWIP_SOCKET
#define LWIP_SOCKET 1
#endif
/**
* LWIP_COMPAT_SOCKETS==1: Enable BSD-style sockets functions names.
* (only used if you use sockets.c)
*/
#ifndef LWIP_COMPAT_SOCKETS
#define LWIP_COMPAT_SOCKETS 1
#endif
/**
* LWIP_POSIX_SOCKETS_IO_NAMES==1: Enable POSIX-style sockets functions names.
* Disable this option if you use a POSIX operating system that uses the same
* names (read, write & close). (only used if you use sockets.c)
*/
#ifndef LWIP_POSIX_SOCKETS_IO_NAMES
#define LWIP_POSIX_SOCKETS_IO_NAMES 1
#endif
/**
* LWIP_TCP_KEEPALIVE==1: Enable TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT
* options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set
* in seconds. (does not require sockets.c, and will affect tcp.c)
*/
#ifndef LWIP_TCP_KEEPALIVE
#define LWIP_TCP_KEEPALIVE 0
#endif
/**
* LWIP_SO_RCVTIMEO==1: Enable SO_RCVTIMEO processing.
*/
#ifndef LWIP_SO_RCVTIMEO
#define LWIP_SO_RCVTIMEO 0
#endif
/**
* LWIP_SO_RCVBUF==1: Enable SO_RCVBUF processing.
*/
#ifndef LWIP_SO_RCVBUF
#define LWIP_SO_RCVBUF 0
#endif
/**
* SO_REUSE==1: Enable SO_REUSEADDR and SO_REUSEPORT options. DO NOT USE!
*/
#ifndef SO_REUSE
#define SO_REUSE 0
#endif
/*
----------------------------------------
---------- Statistics options ----------
----------------------------------------
*/
/**
* LWIP_STATS==1: Enable statistics collection in lwip_stats.
*/
#ifndef LWIP_STATS
#define LWIP_STATS 1
#endif
#if LWIP_STATS
/**
* LWIP_STATS_DISPLAY==1: Compile in the statistics output functions.
*/
#ifndef LWIP_STATS_DISPLAY
#define LWIP_STATS_DISPLAY 0
#endif
/**
* LINK_STATS==1: Enable link stats.
*/
#ifndef LINK_STATS
#define LINK_STATS 1
#endif
/**
* ETHARP_STATS==1: Enable etharp stats.
*/
#ifndef ETHARP_STATS
#define ETHARP_STATS (LWIP_ARP)
#endif
/**
* IP_STATS==1: Enable IP stats.
*/
#ifndef IP_STATS
#define IP_STATS 1
#endif
/**
* IPFRAG_STATS==1: Enable IP fragmentation stats. Default is
* on if using either frag or reass.
*/
#ifndef IPFRAG_STATS
#define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG)
#endif
/**
* ICMP_STATS==1: Enable ICMP stats.
*/
#ifndef ICMP_STATS
#define ICMP_STATS 1
#endif
/**
* IGMP_STATS==1: Enable IGMP stats.
*/
#ifndef IGMP_STATS
#define IGMP_STATS (LWIP_IGMP)
#endif
/**
* UDP_STATS==1: Enable UDP stats. Default is on if
* UDP enabled, otherwise off.
*/
#ifndef UDP_STATS
#define UDP_STATS (LWIP_UDP)
#endif
/**
* TCP_STATS==1: Enable TCP stats. Default is on if TCP
* enabled, otherwise off.
*/
#ifndef TCP_STATS
#define TCP_STATS (LWIP_TCP)
#endif
/**
* MEM_STATS==1: Enable mem.c stats.
*/
#ifndef MEM_STATS
#define MEM_STATS 1
#endif
/**
* MEMP_STATS==1: Enable memp.c pool stats.
*/
#ifndef MEMP_STATS
#define MEMP_STATS 1
#endif
/**
* SYS_STATS==1: Enable system stats (sem and mbox counts, etc).
*/
#ifndef SYS_STATS
#define SYS_STATS 1
#endif
#else
#define LINK_STATS 0
#define IP_STATS 0
#define IPFRAG_STATS 0
#define ICMP_STATS 0
#define IGMP_STATS 0
#define UDP_STATS 0
#define TCP_STATS 0
#define MEM_STATS 0
#define MEMP_STATS 0
#define SYS_STATS 0
#define LWIP_STATS_DISPLAY 0
#endif /* LWIP_STATS */
/*
---------------------------------
---------- PPP options ----------
---------------------------------
*/
/**
* PPP_SUPPORT==1: Enable PPP.
*/
#ifndef PPP_SUPPORT
#define PPP_SUPPORT 0
#endif
/**
* PPPOE_SUPPORT==1: Enable PPP Over Ethernet
*/
#ifndef PPPOE_SUPPORT
#define PPPOE_SUPPORT 0
#endif
/**
* PPPOS_SUPPORT==1: Enable PPP Over Serial
*/
#ifndef PPPOS_SUPPORT
#define PPPOS_SUPPORT PPP_SUPPORT
#endif
#if PPP_SUPPORT
/**
* NUM_PPP: Max PPP sessions.
*/
#ifndef NUM_PPP
#define NUM_PPP 1
#endif
/**
* PAP_SUPPORT==1: Support PAP.
*/
#ifndef PAP_SUPPORT
#define PAP_SUPPORT 0
#endif
/**
* CHAP_SUPPORT==1: Support CHAP.
*/
#ifndef CHAP_SUPPORT
#define CHAP_SUPPORT 0
#endif
/**
* MSCHAP_SUPPORT==1: Support MSCHAP. CURRENTLY NOT SUPPORTED! DO NOT SET!
*/
#ifndef MSCHAP_SUPPORT
#define MSCHAP_SUPPORT 0
#endif
/**
* CBCP_SUPPORT==1: Support CBCP. CURRENTLY NOT SUPPORTED! DO NOT SET!
*/
#ifndef CBCP_SUPPORT
#define CBCP_SUPPORT 0
#endif
/**
* CCP_SUPPORT==1: Support CCP. CURRENTLY NOT SUPPORTED! DO NOT SET!
*/
#ifndef CCP_SUPPORT
#define CCP_SUPPORT 0
#endif
/**
* VJ_SUPPORT==1: Support VJ header compression.
*/
#ifndef VJ_SUPPORT
#define VJ_SUPPORT 0
#endif
/**
* MD5_SUPPORT==1: Support MD5 (see also CHAP).
*/
#ifndef MD5_SUPPORT
#define MD5_SUPPORT 0
#endif
/*
* Timeouts
*/
#ifndef FSM_DEFTIMEOUT
#define FSM_DEFTIMEOUT 6 /* Timeout time in seconds */
#endif
#ifndef FSM_DEFMAXTERMREQS
#define FSM_DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */
#endif
#ifndef FSM_DEFMAXCONFREQS
#define FSM_DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */
#endif
#ifndef FSM_DEFMAXNAKLOOPS
#define FSM_DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */
#endif
#ifndef UPAP_DEFTIMEOUT
#define UPAP_DEFTIMEOUT 6 /* Timeout (seconds) for retransmitting req */
#endif
#ifndef UPAP_DEFREQTIME
#define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */
#endif
#ifndef CHAP_DEFTIMEOUT
#define CHAP_DEFTIMEOUT 6 /* Timeout time in seconds */
#endif
#ifndef CHAP_DEFTRANSMITS
#define CHAP_DEFTRANSMITS 10 /* max # times to send challenge */
#endif
/* Interval in seconds between keepalive echo requests, 0 to disable. */
#ifndef LCP_ECHOINTERVAL
#define LCP_ECHOINTERVAL 0
#endif
/* Number of unanswered echo requests before failure. */
#ifndef LCP_MAXECHOFAILS
#define LCP_MAXECHOFAILS 3
#endif
/* Max Xmit idle time (in jiffies) before resend flag char. */
#ifndef PPP_MAXIDLEFLAG
#define PPP_MAXIDLEFLAG 100
#endif
/*
* Packet sizes
*
* Note - lcp shouldn't be allowed to negotiate stuff outside these
* limits. See lcp.h in the pppd directory.
* (XXX - these constants should simply be shared by lcp.c instead
* of living in lcp.h)
*/
#define PPP_MTU 1500 /* Default MTU (size of Info field) */
#ifndef PPP_MAXMTU
/* #define PPP_MAXMTU 65535 - (PPP_HDRLEN + PPP_FCSLEN) */
#define PPP_MAXMTU 1500 /* Largest MTU we allow */
#endif
#define PPP_MINMTU 64
#define PPP_MRU 1500 /* default MRU = max length of info field */
#define PPP_MAXMRU 1500 /* Largest MRU we allow */
#ifndef PPP_DEFMRU
#define PPP_DEFMRU 296 /* Try for this */
#endif
#define PPP_MINMRU 128 /* No MRUs below this */
#define MAXNAMELEN 256 /* max length of hostname or name for auth */
#define MAXSECRETLEN 256 /* max length of password or secret */
#endif /* PPP_SUPPORT */
/*
--------------------------------------
---------- Checksum options ----------
--------------------------------------
*/
/**
* CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets.
*/
#ifndef CHECKSUM_GEN_IP
#define CHECKSUM_GEN_IP 1
#endif
/**
* CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets.
*/
#ifndef CHECKSUM_GEN_UDP
#define CHECKSUM_GEN_UDP 1
#endif
/**
* CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets.
*/
#ifndef CHECKSUM_GEN_TCP
#define CHECKSUM_GEN_TCP 1
#endif
/**
* CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets.
*/
#ifndef CHECKSUM_CHECK_IP
#define CHECKSUM_CHECK_IP 1
#endif
/**
* CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets.
*/
#ifndef CHECKSUM_CHECK_UDP
#define CHECKSUM_CHECK_UDP 1
#endif
/**
* CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets.
*/
#ifndef CHECKSUM_CHECK_TCP
#define CHECKSUM_CHECK_TCP 1
#endif
/*
---------------------------------------
---------- Debugging options ----------
---------------------------------------
*/
/**
* LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is
* compared against this value. If it is smaller, then debugging
* messages are written.
*/
#ifndef LWIP_DBG_MIN_LEVEL
#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_OFF
#endif
/**
* LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable
* debug messages of certain types.
*/
#ifndef LWIP_DBG_TYPES_ON
#define LWIP_DBG_TYPES_ON LWIP_DBG_ON
#endif
/**
* ETHARP_DEBUG: Enable debugging in etharp.c.
*/
#ifndef ETHARP_DEBUG
#define ETHARP_DEBUG LWIP_DBG_OFF
#endif
/**
* NETIF_DEBUG: Enable debugging in netif.c.
*/
#ifndef NETIF_DEBUG
#define NETIF_DEBUG LWIP_DBG_OFF
#endif
/**
* PBUF_DEBUG: Enable debugging in pbuf.c.
*/
#ifndef PBUF_DEBUG
#define PBUF_DEBUG LWIP_DBG_OFF
#endif
/**
* API_LIB_DEBUG: Enable debugging in api_lib.c.
*/
#ifndef API_LIB_DEBUG
#define API_LIB_DEBUG LWIP_DBG_OFF
#endif
/**
* API_MSG_DEBUG: Enable debugging in api_msg.c.
*/
#ifndef API_MSG_DEBUG
#define API_MSG_DEBUG LWIP_DBG_OFF
#endif
/**
* SOCKETS_DEBUG: Enable debugging in sockets.c.
*/
#ifndef SOCKETS_DEBUG
#define SOCKETS_DEBUG LWIP_DBG_OFF
#endif
/**
* ICMP_DEBUG: Enable debugging in icmp.c.
*/
#ifndef ICMP_DEBUG
#define ICMP_DEBUG LWIP_DBG_OFF
#endif
/**
* IGMP_DEBUG: Enable debugging in igmp.c.
*/
#ifndef IGMP_DEBUG
#define IGMP_DEBUG LWIP_DBG_OFF
#endif
/**
* INET_DEBUG: Enable debugging in inet.c.
*/
#ifndef INET_DEBUG
#define INET_DEBUG LWIP_DBG_OFF
#endif
/**
* IP_DEBUG: Enable debugging for IP.
*/
#ifndef IP_DEBUG
#define IP_DEBUG LWIP_DBG_OFF
#endif
/**
* IP_REASS_DEBUG: Enable debugging in ip_frag.c for both frag & reass.
*/
#ifndef IP_REASS_DEBUG
#define IP_REASS_DEBUG LWIP_DBG_OFF
#endif
/**
* RAW_DEBUG: Enable debugging in raw.c.
*/
#ifndef RAW_DEBUG
#define RAW_DEBUG LWIP_DBG_OFF
#endif
/**
* MEM_DEBUG: Enable debugging in mem.c.
*/
#ifndef MEM_DEBUG
#define MEM_DEBUG LWIP_DBG_OFF
#endif
/**
* MEMP_DEBUG: Enable debugging in memp.c.
*/
#ifndef MEMP_DEBUG
#define MEMP_DEBUG LWIP_DBG_OFF
#endif
/**
* SYS_DEBUG: Enable debugging in sys.c.
*/
#ifndef SYS_DEBUG
#define SYS_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_DEBUG: Enable debugging for TCP.
*/
#ifndef TCP_DEBUG
#define TCP_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_INPUT_DEBUG: Enable debugging in tcp_in.c for incoming debug.
*/
#ifndef TCP_INPUT_DEBUG
#define TCP_INPUT_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_FR_DEBUG: Enable debugging in tcp_in.c for fast retransmit.
*/
#ifndef TCP_FR_DEBUG
#define TCP_FR_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_RTO_DEBUG: Enable debugging in TCP for retransmit
* timeout.
*/
#ifndef TCP_RTO_DEBUG
#define TCP_RTO_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_CWND_DEBUG: Enable debugging for TCP congestion window.
*/
#ifndef TCP_CWND_DEBUG
#define TCP_CWND_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_WND_DEBUG: Enable debugging in tcp_in.c for window updating.
*/
#ifndef TCP_WND_DEBUG
#define TCP_WND_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions.
*/
#ifndef TCP_OUTPUT_DEBUG
#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_RST_DEBUG: Enable debugging for TCP with the RST message.
*/
#ifndef TCP_RST_DEBUG
#define TCP_RST_DEBUG LWIP_DBG_OFF
#endif
/**
* TCP_QLEN_DEBUG: Enable debugging for TCP queue lengths.
*/
#ifndef TCP_QLEN_DEBUG
#define TCP_QLEN_DEBUG LWIP_DBG_OFF
#endif
/**
* UDP_DEBUG: Enable debugging in UDP.
*/
#ifndef UDP_DEBUG
#define UDP_DEBUG LWIP_DBG_OFF
#endif
/**
* TCPIP_DEBUG: Enable debugging in tcpip.c.
*/
#ifndef TCPIP_DEBUG
#define TCPIP_DEBUG LWIP_DBG_OFF
#endif
/**
* PPP_DEBUG: Enable debugging for PPP.
*/
#ifndef PPP_DEBUG
#define PPP_DEBUG LWIP_DBG_OFF
#endif
/**
* SLIP_DEBUG: Enable debugging in slipif.c.
*/
#ifndef SLIP_DEBUG
#define SLIP_DEBUG LWIP_DBG_OFF
#endif
/**
* DHCP_DEBUG: Enable debugging in dhcp.c.
*/
#ifndef DHCP_DEBUG
#define DHCP_DEBUG LWIP_DBG_OFF
#endif
/**
* AUTOIP_DEBUG: Enable debugging in autoip.c.
*/
#ifndef AUTOIP_DEBUG
#define AUTOIP_DEBUG LWIP_DBG_OFF
#endif
/**
* SNMP_MSG_DEBUG: Enable debugging for SNMP messages.
*/
#ifndef SNMP_MSG_DEBUG
#define SNMP_MSG_DEBUG LWIP_DBG_OFF
#endif
/**
* SNMP_MIB_DEBUG: Enable debugging for SNMP MIBs.
*/
#ifndef SNMP_MIB_DEBUG
#define SNMP_MIB_DEBUG LWIP_DBG_OFF
#endif
/**
* DNS_DEBUG: Enable debugging for DNS.
*/
#ifndef DNS_DEBUG
#define DNS_DEBUG LWIP_DBG_OFF
#endif
#endif /* __LWIP_OPT_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/opt.h | C | oos | 44,227 |
/**
* @file
* SNMP Agent message handling structures.
*/
/*
* Copyright (c) 2006 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* Author: Christiaan Simons <christiaan.simons@axon.tv>
*/
#ifndef __LWIP_SNMP_MSG_H__
#define __LWIP_SNMP_MSG_H__
#include "lwip/opt.h"
#include "lwip/snmp.h"
#include "lwip/snmp_structs.h"
#if SNMP_PRIVATE_MIB
#include "private_mib.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* The listen port of the SNMP agent. Clients have to make their requests to
this port. Most standard clients won't work if you change this! */
#ifndef SNMP_IN_PORT
#define SNMP_IN_PORT 161
#endif
/* The remote port the SNMP agent sends traps to. Most standard trap sinks won't
work if you change this! */
#ifndef SNMP_TRAP_PORT
#define SNMP_TRAP_PORT 162
#endif
#define SNMP_ES_NOERROR 0
#define SNMP_ES_TOOBIG 1
#define SNMP_ES_NOSUCHNAME 2
#define SNMP_ES_BADVALUE 3
#define SNMP_ES_READONLY 4
#define SNMP_ES_GENERROR 5
#define SNMP_GENTRAP_COLDSTART 0
#define SNMP_GENTRAP_WARMSTART 1
#define SNMP_GENTRAP_AUTHFAIL 4
#define SNMP_GENTRAP_ENTERPRISESPC 6
struct snmp_varbind
{
/* next pointer, NULL for last in list */
struct snmp_varbind *next;
/* previous pointer, NULL for first in list */
struct snmp_varbind *prev;
/* object identifier length (in s32_t) */
u8_t ident_len;
/* object identifier array */
s32_t *ident;
/* object value ASN1 type */
u8_t value_type;
/* object value length (in u8_t) */
u8_t value_len;
/* object value */
void *value;
/* encoding varbind seq length length */
u8_t seqlenlen;
/* encoding object identifier length length */
u8_t olenlen;
/* encoding object value length length */
u8_t vlenlen;
/* encoding varbind seq length */
u16_t seqlen;
/* encoding object identifier length */
u16_t olen;
/* encoding object value length */
u16_t vlen;
};
struct snmp_varbind_root
{
struct snmp_varbind *head;
struct snmp_varbind *tail;
/* number of variable bindings in list */
u8_t count;
/* encoding varbind-list seq length length */
u8_t seqlenlen;
/* encoding varbind-list seq length */
u16_t seqlen;
};
/** output response message header length fields */
struct snmp_resp_header_lengths
{
/* encoding error-index length length */
u8_t erridxlenlen;
/* encoding error-status length length */
u8_t errstatlenlen;
/* encoding request id length length */
u8_t ridlenlen;
/* encoding pdu length length */
u8_t pdulenlen;
/* encoding community length length */
u8_t comlenlen;
/* encoding version length length */
u8_t verlenlen;
/* encoding sequence length length */
u8_t seqlenlen;
/* encoding error-index length */
u16_t erridxlen;
/* encoding error-status length */
u16_t errstatlen;
/* encoding request id length */
u16_t ridlen;
/* encoding pdu length */
u16_t pdulen;
/* encoding community length */
u16_t comlen;
/* encoding version length */
u16_t verlen;
/* encoding sequence length */
u16_t seqlen;
};
/** output response message header length fields */
struct snmp_trap_header_lengths
{
/* encoding timestamp length length */
u8_t tslenlen;
/* encoding specific-trap length length */
u8_t strplenlen;
/* encoding generic-trap length length */
u8_t gtrplenlen;
/* encoding agent-addr length length */
u8_t aaddrlenlen;
/* encoding enterprise-id length length */
u8_t eidlenlen;
/* encoding pdu length length */
u8_t pdulenlen;
/* encoding community length length */
u8_t comlenlen;
/* encoding version length length */
u8_t verlenlen;
/* encoding sequence length length */
u8_t seqlenlen;
/* encoding timestamp length */
u16_t tslen;
/* encoding specific-trap length */
u16_t strplen;
/* encoding generic-trap length */
u16_t gtrplen;
/* encoding agent-addr length */
u16_t aaddrlen;
/* encoding enterprise-id length */
u16_t eidlen;
/* encoding pdu length */
u16_t pdulen;
/* encoding community length */
u16_t comlen;
/* encoding version length */
u16_t verlen;
/* encoding sequence length */
u16_t seqlen;
};
/* Accepting new SNMP messages. */
#define SNMP_MSG_EMPTY 0
/* Search for matching object for variable binding. */
#define SNMP_MSG_SEARCH_OBJ 1
/* Perform SNMP operation on in-memory object.
Pass-through states, for symmetry only. */
#define SNMP_MSG_INTERNAL_GET_OBJDEF 2
#define SNMP_MSG_INTERNAL_GET_VALUE 3
#define SNMP_MSG_INTERNAL_SET_TEST 4
#define SNMP_MSG_INTERNAL_GET_OBJDEF_S 5
#define SNMP_MSG_INTERNAL_SET_VALUE 6
/* Perform SNMP operation on object located externally.
In theory this could be used for building a proxy agent.
Practical use is for an enterprise spc. app. gateway. */
#define SNMP_MSG_EXTERNAL_GET_OBJDEF 7
#define SNMP_MSG_EXTERNAL_GET_VALUE 8
#define SNMP_MSG_EXTERNAL_SET_TEST 9
#define SNMP_MSG_EXTERNAL_GET_OBJDEF_S 10
#define SNMP_MSG_EXTERNAL_SET_VALUE 11
#define SNMP_COMMUNITY_STR_LEN 64
struct snmp_msg_pstat
{
/* lwIP local port (161) binding */
struct udp_pcb *pcb;
/* source IP address */
struct ip_addr sip;
/* source UDP port */
u16_t sp;
/* request type */
u8_t rt;
/* request ID */
s32_t rid;
/* error status */
s32_t error_status;
/* error index */
s32_t error_index;
/* community name (zero terminated) */
u8_t community[SNMP_COMMUNITY_STR_LEN + 1];
/* community string length (exclusive zero term) */
u8_t com_strlen;
/* one out of MSG_EMPTY, MSG_DEMUX, MSG_INTERNAL, MSG_EXTERNAL_x */
u8_t state;
/* saved arguments for MSG_EXTERNAL_x */
struct mib_external_node *ext_mib_node;
struct snmp_name_ptr ext_name_ptr;
struct obj_def ext_object_def;
struct snmp_obj_id ext_oid;
/* index into input variable binding list */
u8_t vb_idx;
/* ptr into input variable binding list */
struct snmp_varbind *vb_ptr;
/* list of variable bindings from input */
struct snmp_varbind_root invb;
/* list of variable bindings to output */
struct snmp_varbind_root outvb;
/* output response lengths used in ASN encoding */
struct snmp_resp_header_lengths rhl;
};
struct snmp_msg_trap
{
/* lwIP local port (161) binding */
struct udp_pcb *pcb;
/* destination IP address in network order */
struct ip_addr dip;
/* source enterprise ID (sysObjectID) */
struct snmp_obj_id *enterprise;
/* source IP address, raw network order format */
u8_t sip_raw[4];
/* generic trap code */
u32_t gen_trap;
/* specific trap code */
u32_t spc_trap;
/* timestamp */
u32_t ts;
/* list of variable bindings to output */
struct snmp_varbind_root outvb;
/* output trap lengths used in ASN encoding */
struct snmp_trap_header_lengths thl;
};
/** Agent Version constant, 0 = v1 oddity */
extern const s32_t snmp_version;
/** Agent default "public" community string */
extern const char snmp_publiccommunity[7];
extern struct snmp_msg_trap trap_msg;
/** Agent setup, start listening to port 161. */
void snmp_init(void);
void snmp_trap_dst_enable(u8_t dst_idx, u8_t enable);
void snmp_trap_dst_ip_set(u8_t dst_idx, struct ip_addr *dst);
/** Varbind-list functions. */
struct snmp_varbind* snmp_varbind_alloc(struct snmp_obj_id *oid, u8_t type, u8_t len);
void snmp_varbind_free(struct snmp_varbind *vb);
void snmp_varbind_list_free(struct snmp_varbind_root *root);
void snmp_varbind_tail_add(struct snmp_varbind_root *root, struct snmp_varbind *vb);
struct snmp_varbind* snmp_varbind_tail_remove(struct snmp_varbind_root *root);
/** Handle an internal (recv) or external (private response) event. */
void snmp_msg_event(u8_t request_id);
err_t snmp_send_response(struct snmp_msg_pstat *m_stat);
err_t snmp_send_trap(s8_t generic_trap, struct snmp_obj_id *eoid, s32_t specific_trap);
void snmp_coldstart_trap(void);
void snmp_authfail_trap(void);
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_SNMP_MSG_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/lwip/snmp_msg.h | C | oos | 9,601 |
/*****************************************************************************
* ppp_oe.h - PPP Over Ethernet implementation for lwIP.
*
* Copyright (c) 2006 by Marc Boucher, Services Informatiques (MBSI) inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS *AS IS* AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
* REVISION HISTORY
*
* 06-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
*****************************************************************************/
/* based on NetBSD: if_pppoe.c,v 1.64 2006/01/31 23:50:15 martin Exp */
/*-
* Copyright (c) 2002 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Martin Husemann <martin@NetBSD.org>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PPP_OE_H
#define PPP_OE_H
#include "lwip/opt.h"
#if PPPOE_SUPPORT > 0
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct pppoehdr {
PACK_STRUCT_FIELD(u8_t vertype);
PACK_STRUCT_FIELD(u8_t code);
PACK_STRUCT_FIELD(u16_t session);
PACK_STRUCT_FIELD(u16_t plen);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct pppoetag {
PACK_STRUCT_FIELD(u16_t tag);
PACK_STRUCT_FIELD(u16_t len);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define PPPOE_STATE_INITIAL 0
#define PPPOE_STATE_PADI_SENT 1
#define PPPOE_STATE_PADR_SENT 2
#define PPPOE_STATE_SESSION 3
#define PPPOE_STATE_CLOSING 4
/* passive */
#define PPPOE_STATE_PADO_SENT 1
#define PPPOE_HEADERLEN sizeof(struct pppoehdr)
#define PPPOE_VERTYPE 0x11 /* VER=1, TYPE = 1 */
#define PPPOE_TAG_EOL 0x0000 /* end of list */
#define PPPOE_TAG_SNAME 0x0101 /* service name */
#define PPPOE_TAG_ACNAME 0x0102 /* access concentrator name */
#define PPPOE_TAG_HUNIQUE 0x0103 /* host unique */
#define PPPOE_TAG_ACCOOKIE 0x0104 /* AC cookie */
#define PPPOE_TAG_VENDOR 0x0105 /* vendor specific */
#define PPPOE_TAG_RELAYSID 0x0110 /* relay session id */
#define PPPOE_TAG_SNAME_ERR 0x0201 /* service name error */
#define PPPOE_TAG_ACSYS_ERR 0x0202 /* AC system error */
#define PPPOE_TAG_GENERIC_ERR 0x0203 /* gerneric error */
#define PPPOE_CODE_PADI 0x09 /* Active Discovery Initiation */
#define PPPOE_CODE_PADO 0x07 /* Active Discovery Offer */
#define PPPOE_CODE_PADR 0x19 /* Active Discovery Request */
#define PPPOE_CODE_PADS 0x65 /* Active Discovery Session confirmation */
#define PPPOE_CODE_PADT 0xA7 /* Active Discovery Terminate */
#ifndef ETHERMTU
#define ETHERMTU 1500
#endif
/* two byte PPP protocol discriminator, then IP data */
#define PPPOE_MAXMTU (ETHERMTU-PPPOE_HEADERLEN-2)
struct pppoe_softc;
void pppoe_init(void);
err_t pppoe_create(struct netif *ethif, int pd, void (*linkStatusCB)(int pd, int up), struct pppoe_softc **scptr);
err_t pppoe_destroy(struct netif *ifp);
int pppoe_connect(struct pppoe_softc *sc);
void pppoe_disconnect(struct pppoe_softc *sc);
void pppoe_disc_input(struct netif *netif, struct pbuf *p);
void pppoe_data_input(struct netif *netif, struct pbuf *p);
err_t pppoe_xmit(struct pppoe_softc *sc, struct pbuf *pb);
extern int pppoe_hdrlen;
#endif /* PPPOE_SUPPORT */
#endif /* PPP_OE_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/netif/ppp_oe.h | C | oos | 6,548 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* Copyright (c) 2003-2004 Leon Woestenberg <leon.woestenberg@axon.tv>
* Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __NETIF_ETHARP_H__
#define __NETIF_ETHARP_H__
#include "lwip/opt.h"
#if LWIP_ARP /* don't build if not configured for use in lwipopts.h */
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/ip.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef ETH_PAD_SIZE
#define ETH_PAD_SIZE 0
#endif
#ifndef ETHARP_HWADDR_LEN
#define ETHARP_HWADDR_LEN 6
#endif
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct eth_addr {
PACK_STRUCT_FIELD(u8_t addr[ETHARP_HWADDR_LEN]);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct eth_hdr {
#if ETH_PAD_SIZE
PACK_STRUCT_FIELD(u8_t padding[ETH_PAD_SIZE]);
#endif
PACK_STRUCT_FIELD(struct eth_addr dest);
PACK_STRUCT_FIELD(struct eth_addr src);
PACK_STRUCT_FIELD(u16_t type);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
/** the ARP message */
struct etharp_hdr {
PACK_STRUCT_FIELD(struct eth_hdr ethhdr);
PACK_STRUCT_FIELD(u16_t hwtype);
PACK_STRUCT_FIELD(u16_t proto);
PACK_STRUCT_FIELD(u16_t _hwlen_protolen);
PACK_STRUCT_FIELD(u16_t opcode);
PACK_STRUCT_FIELD(struct eth_addr shwaddr);
PACK_STRUCT_FIELD(struct ip_addr2 sipaddr);
PACK_STRUCT_FIELD(struct eth_addr dhwaddr);
PACK_STRUCT_FIELD(struct ip_addr2 dipaddr);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct ethip_hdr {
PACK_STRUCT_FIELD(struct eth_hdr eth);
PACK_STRUCT_FIELD(struct ip_hdr ip);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/** 5 seconds period */
#define ARP_TMR_INTERVAL 5000
#define ETHTYPE_ARP 0x0806
#define ETHTYPE_IP 0x0800
#define ETHTYPE_PPPOEDISC 0x8863 /* PPP Over Ethernet Discovery Stage */
#define ETHTYPE_PPPOE 0x8864 /* PPP Over Ethernet Session Stage */
/** ARP message types (opcodes) */
#define ARP_REQUEST 1
#define ARP_REPLY 2
#if ARP_QUEUEING
/** struct for queueing outgoing packets for unknown address
* defined here to be accessed by memp.h
*/
struct etharp_q_entry {
struct etharp_q_entry *next;
struct pbuf *p;
};
#endif /* ARP_QUEUEING */
#define etharp_init() /* Compatibility define, not init needed. */
void etharp_tmr(void);
s8_t etharp_find_addr(struct netif *netif, struct ip_addr *ipaddr,
struct eth_addr **eth_ret, struct ip_addr **ip_ret);
void etharp_ip_input(struct netif *netif, struct pbuf *p);
void etharp_arp_input(struct netif *netif, struct eth_addr *ethaddr,
struct pbuf *p);
err_t etharp_output(struct netif *netif, struct pbuf *q, struct ip_addr *ipaddr);
err_t etharp_query(struct netif *netif, struct ip_addr *ipaddr, struct pbuf *q);
err_t etharp_request(struct netif *netif, struct ip_addr *ipaddr);
err_t ethernet_input(struct pbuf *p, struct netif *netif);
#if LWIP_AUTOIP
err_t etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr,
const struct eth_addr *ethdst_addr,
const struct eth_addr *hwsrc_addr, const struct ip_addr *ipsrc_addr,
const struct eth_addr *hwdst_addr, const struct ip_addr *ipdst_addr,
const u16_t opcode);
#endif /* LWIP_AUTOIP */
#define eth_addr_cmp(addr1, addr2) (memcmp((addr1)->addr, (addr2)->addr, ETHARP_HWADDR_LEN) == 0)
extern const struct eth_addr ethbroadcast, ethzero;
#ifdef __cplusplus
}
#endif
#endif /* LWIP_ARP */
#endif /* __NETIF_ARP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/netif/etharp.h | C | oos | 6,098 |
/*
* Copyright (c) 2001, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __NETIF_SLIPIF_H__
#define __NETIF_SLIPIF_H__
#include "lwip/netif.h"
#ifdef __cplusplus
extern "C" {
#endif
err_t slipif_init(struct netif * netif);
#ifdef __cplusplus
}
#endif
#endif
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/netif/slipif.h | C | oos | 1,955 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __NETIF_LOOPIF_H__
#define __NETIF_LOOPIF_H__
#include "lwip/netif.h"
#include "lwip/err.h"
#ifdef __cplusplus
extern "C" {
#endif
#if !LWIP_LOOPIF_MULTITHREADING
void loopif_poll(struct netif *netif);
#endif
err_t loopif_init(struct netif *netif);
#ifdef __cplusplus
}
#endif
#endif /* __NETIF_LOOPIF_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/netif/loopif.h | C | oos | 1,969 |
/**
* @file
*
* AutoIP Automatic LinkLocal IP Configuration
*/
/*
*
* Copyright (c) 2007 Dominik Spies <kontakt@dspies.de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* Author: Dominik Spies <kontakt@dspies.de>
*
* This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform
* with RFC 3927.
*
*
* Please coordinate changes and requests with Dominik Spies
* <kontakt@dspies.de>
*/
#ifndef __LWIP_AUTOIP_H__
#define __LWIP_AUTOIP_H__
#include "lwip/opt.h"
#if LWIP_AUTOIP /* don't build if not configured for use in lwipopts.h */
#include "lwip/netif.h"
#include "lwip/udp.h"
#include "netif/etharp.h"
/* AutoIP Timing */
#define AUTOIP_TMR_INTERVAL 100
#define AUTOIP_TICKS_PER_SECOND (1000 / AUTOIP_TMR_INTERVAL)
/* RFC 3927 Constants */
#define PROBE_WAIT 1 /* second (initial random delay) */
#define PROBE_MIN 1 /* second (minimum delay till repeated probe) */
#define PROBE_MAX 2 /* seconds (maximum delay till repeated probe) */
#define PROBE_NUM 3 /* (number of probe packets) */
#define ANNOUNCE_NUM 2 /* (number of announcement packets) */
#define ANNOUNCE_INTERVAL 2 /* seconds (time between announcement packets) */
#define ANNOUNCE_WAIT 2 /* seconds (delay before announcing) */
#define MAX_CONFLICTS 10 /* (max conflicts before rate limiting) */
#define RATE_LIMIT_INTERVAL 60 /* seconds (delay between successive attempts) */
#define DEFEND_INTERVAL 10 /* seconds (min. wait between defensive ARPs) */
/* AutoIP client states */
#define AUTOIP_STATE_OFF 0
#define AUTOIP_STATE_PROBING 1
#define AUTOIP_STATE_ANNOUNCING 2
#define AUTOIP_STATE_BOUND 3
struct autoip
{
struct ip_addr llipaddr; /* the currently selected, probed, announced or used LL IP-Address */
u8_t state; /* current AutoIP state machine state */
u8_t sent_num; /* sent number of probes or announces, dependent on state */
u16_t ttw; /* ticks to wait, tick is AUTOIP_TMR_INTERVAL long */
u8_t lastconflict; /* ticks until a conflict can be solved by defending */
u8_t tried_llipaddr; /* total number of probed/used Link Local IP-Addresses */
};
/** Init srand, has to be called before entering mainloop */
void autoip_init(void);
/** Start AutoIP client */
err_t autoip_start(struct netif *netif);
/** Stop AutoIP client */
err_t autoip_stop(struct netif *netif);
/** Handles every incoming ARP Packet, called by etharp_arp_input */
void autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr);
/** Has to be called in loop every AUTOIP_TMR_INTERVAL milliseconds */
void autoip_tmr(void);
#endif /* LWIP_AUTOIP */
#endif /* __LWIP_AUTOIP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv4/lwip/autoip.h | C | oos | 4,394 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_IP_ADDR_H__
#define __LWIP_IP_ADDR_H__
#include "lwip/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct ip_addr {
PACK_STRUCT_FIELD(u32_t addr);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/*
* struct ipaddr2 is used in the definition of the ARP packet format in
* order to support compilers that don't have structure packing.
*/
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct ip_addr2 {
PACK_STRUCT_FIELD(u16_t addrw[2]);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/* For compatibility with BSD code */
struct in_addr {
u32_t s_addr;
};
struct netif;
extern const struct ip_addr ip_addr_any;
extern const struct ip_addr ip_addr_broadcast;
/** IP_ADDR_ can be used as a fixed IP address
* for the wildcard and the broadcast address
*/
#define IP_ADDR_ANY ((struct ip_addr *)&ip_addr_any)
#define IP_ADDR_BROADCAST ((struct ip_addr *)&ip_addr_broadcast)
#define INADDR_NONE ((u32_t)0xffffffffUL) /* 255.255.255.255 */
#define INADDR_LOOPBACK ((u32_t)0x7f000001UL) /* 127.0.0.1 */
/* Definitions of the bits in an Internet address integer.
On subnets, host and network parts are found according to
the subnet mask, not these masks. */
#define IN_CLASSA(a) ((((u32_t)(a)) & 0x80000000UL) == 0)
#define IN_CLASSA_NET 0xff000000
#define IN_CLASSA_NSHIFT 24
#define IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET)
#define IN_CLASSA_MAX 128
#define IN_CLASSB(a) ((((u32_t)(a)) & 0xc0000000UL) == 0x80000000UL)
#define IN_CLASSB_NET 0xffff0000
#define IN_CLASSB_NSHIFT 16
#define IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET)
#define IN_CLASSB_MAX 65536
#define IN_CLASSC(a) ((((u32_t)(a)) & 0xe0000000UL) == 0xc0000000UL)
#define IN_CLASSC_NET 0xffffff00
#define IN_CLASSC_NSHIFT 8
#define IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET)
#define IN_CLASSD(a) (((u32_t)(a) & 0xf0000000UL) == 0xe0000000UL)
#define IN_CLASSD_NET 0xf0000000 /* These ones aren't really */
#define IN_CLASSD_NSHIFT 28 /* net and host fields, but */
#define IN_CLASSD_HOST 0x0fffffff /* routing needn't know. */
#define IN_MULTICAST(a) IN_CLASSD(a)
#define IN_EXPERIMENTAL(a) (((u32_t)(a) & 0xf0000000UL) == 0xf0000000UL)
#define IN_BADCLASS(a) (((u32_t)(a) & 0xf0000000UL) == 0xf0000000UL)
#define IN_LOOPBACKNET 127 /* official! */
#define IP4_ADDR(ipaddr, a,b,c,d) \
(ipaddr)->addr = htonl(((u32_t)((a) & 0xff) << 24) | \
((u32_t)((b) & 0xff) << 16) | \
((u32_t)((c) & 0xff) << 8) | \
(u32_t)((d) & 0xff))
#define ip_addr_set(dest, src) (dest)->addr = \
((src) == NULL? 0:\
(src)->addr)
/**
* Determine if two address are on the same network.
*
* @arg addr1 IP address 1
* @arg addr2 IP address 2
* @arg mask network identifier mask
* @return !0 if the network identifiers of both address match
*/
#define ip_addr_netcmp(addr1, addr2, mask) (((addr1)->addr & \
(mask)->addr) == \
((addr2)->addr & \
(mask)->addr))
#define ip_addr_cmp(addr1, addr2) ((addr1)->addr == (addr2)->addr)
#define ip_addr_isany(addr1) ((addr1) == NULL || (addr1)->addr == 0)
u8_t ip_addr_isbroadcast(struct ip_addr *, struct netif *);
#define ip_addr_ismulticast(addr1) (((addr1)->addr & ntohl(0xf0000000UL)) == ntohl(0xe0000000UL))
#define ip_addr_islinklocal(addr1) (((addr1)->addr & ntohl(0xffff0000UL)) == ntohl(0xa9fe0000UL))
#define ip_addr_debug_print(debug, ipaddr) \
LWIP_DEBUGF(debug, ("%"U16_F".%"U16_F".%"U16_F".%"U16_F, \
ipaddr ? (u16_t)(ntohl((ipaddr)->addr) >> 24) & 0xff : 0, \
ipaddr ? (u16_t)(ntohl((ipaddr)->addr) >> 16) & 0xff : 0, \
ipaddr ? (u16_t)(ntohl((ipaddr)->addr) >> 8) & 0xff : 0, \
ipaddr ? (u16_t)ntohl((ipaddr)->addr) & 0xff : 0))
/* These are cast to u16_t, with the intent that they are often arguments
* to printf using the U16_F format from cc.h. */
#define ip4_addr1(ipaddr) ((u16_t)(ntohl((ipaddr)->addr) >> 24) & 0xff)
#define ip4_addr2(ipaddr) ((u16_t)(ntohl((ipaddr)->addr) >> 16) & 0xff)
#define ip4_addr3(ipaddr) ((u16_t)(ntohl((ipaddr)->addr) >> 8) & 0xff)
#define ip4_addr4(ipaddr) ((u16_t)(ntohl((ipaddr)->addr)) & 0xff)
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_IP_ADDR_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv4/lwip/ip_addr.h | C | oos | 6,805 |
/*
* Copyright (c) 2002 CITEL Technologies Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of CITEL Technologies Ltd nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY CITEL TECHNOLOGIES AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL CITEL TECHNOLOGIES OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is a contribution to the lwIP TCP/IP stack.
* The Swedish Institute of Computer Science and Adam Dunkels
* are specifically granted permission to redistribute this
* source code.
*/
#ifndef __LWIP_IGMP_H__
#define __LWIP_IGMP_H__
#include "lwip/opt.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/pbuf.h"
#if LWIP_IGMP /* don't build if not configured for use in lwipopts.h */
#ifdef __cplusplus
extern "C" {
#endif
/*
* IGMP constants
*/
#define IP_PROTO_IGMP 2
#define IGMP_TTL 1
#define IGMP_MINLEN 8
#define ROUTER_ALERT 0x9404
#define ROUTER_ALERTLEN 4
/*
* IGMP message types, including version number.
*/
#define IGMP_MEMB_QUERY 0x11 /* Membership query */
#define IGMP_V1_MEMB_REPORT 0x12 /* Ver. 1 membership report */
#define IGMP_V2_MEMB_REPORT 0x16 /* Ver. 2 membership report */
#define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */
/* IGMP timer */
#define IGMP_TMR_INTERVAL 100 /* Milliseconds */
#define IGMP_V1_DELAYING_MEMBER_TMR (1000/IGMP_TMR_INTERVAL)
#define IGMP_JOIN_DELAYING_MEMBER_TMR (500 /IGMP_TMR_INTERVAL)
/* MAC Filter Actions */
#define IGMP_DEL_MAC_FILTER 0
#define IGMP_ADD_MAC_FILTER 1
/* Group membership states */
#define IGMP_GROUP_NON_MEMBER 0
#define IGMP_GROUP_DELAYING_MEMBER 1
#define IGMP_GROUP_IDLE_MEMBER 2
/*
* IGMP packet format.
*/
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct igmp_msg {
PACK_STRUCT_FIELD(u8_t igmp_msgtype);
PACK_STRUCT_FIELD(u8_t igmp_maxresp);
PACK_STRUCT_FIELD(u16_t igmp_checksum);
PACK_STRUCT_FIELD(struct ip_addr igmp_group_address);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/*
* now a group structure - there is
* a list of groups for each interface
* these should really be linked from the interface, but
* if we keep them separate we will not affect the lwip original code
* too much
*
* There will be a group for the all systems group address but this
* will not run the state machine as it is used to kick off reports
* from all the other groups
*/
struct igmp_group {
struct igmp_group *next;
struct netif *interface;
struct ip_addr group_address;
u8_t last_reporter_flag; /* signifies we were the last person to report */
u8_t group_state;
u16_t timer;
u8_t use; /* counter of simultaneous uses */
};
/* Prototypes */
void igmp_init(void);
err_t igmp_start( struct netif *netif);
err_t igmp_stop( struct netif *netif);
void igmp_report_groups( struct netif *netif);
struct igmp_group *igmp_lookfor_group( struct netif *ifp, struct ip_addr *addr);
struct igmp_group *igmp_lookup_group( struct netif *ifp, struct ip_addr *addr);
err_t igmp_remove_group( struct igmp_group *group);
void igmp_input( struct pbuf *p, struct netif *inp, struct ip_addr *dest);
err_t igmp_joingroup( struct ip_addr *ifaddr, struct ip_addr *groupaddr);
err_t igmp_leavegroup( struct ip_addr *ifaddr, struct ip_addr *groupaddr);
void igmp_tmr(void);
void igmp_timeout( struct igmp_group *group);
void igmp_start_timer( struct igmp_group *group, u8_t max_time);
void igmp_stop_timer( struct igmp_group *group);
void igmp_delaying_member( struct igmp_group *group, u8_t maxresp);
err_t igmp_ip_output_if( struct pbuf *p, struct ip_addr *src, struct ip_addr *dest, u8_t ttl, u8_t proto, struct netif *netif);
void igmp_send( struct igmp_group *group, u8_t type);
#ifdef __cplusplus
}
#endif
#endif /* LWIP_IGMP */
#endif /* __LWIP_IGMP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv4/lwip/igmp.h | C | oos | 5,682 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_INET_CHKSUM_H__
#define __LWIP_INET_CHKSUM_H__
#include "lwip/opt.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#ifdef __cplusplus
extern "C" {
#endif
u16_t inet_chksum(void *dataptr, u16_t len);
u16_t inet_chksum_pbuf(struct pbuf *p);
u16_t inet_chksum_pseudo(struct pbuf *p,
struct ip_addr *src, struct ip_addr *dest,
u8_t proto, u16_t proto_len);
u16_t inet_chksum_pseudo_partial(struct pbuf *p,
struct ip_addr *src, struct ip_addr *dest,
u8_t proto, u16_t proto_len, u16_t chksum_len);
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_INET_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv4/lwip/inet_chksum.h | C | oos | 2,255 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_ICMP_H__
#define __LWIP_ICMP_H__
#include "lwip/opt.h"
#if LWIP_ICMP /* don't build if not configured for use in lwipopts.h */
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ICMP_ER 0 /* echo reply */
#define ICMP_DUR 3 /* destination unreachable */
#define ICMP_SQ 4 /* source quench */
#define ICMP_RD 5 /* redirect */
#define ICMP_ECHO 8 /* echo */
#define ICMP_TE 11 /* time exceeded */
#define ICMP_PP 12 /* parameter problem */
#define ICMP_TS 13 /* timestamp */
#define ICMP_TSR 14 /* timestamp reply */
#define ICMP_IRQ 15 /* information request */
#define ICMP_IR 16 /* information reply */
enum icmp_dur_type {
ICMP_DUR_NET = 0, /* net unreachable */
ICMP_DUR_HOST = 1, /* host unreachable */
ICMP_DUR_PROTO = 2, /* protocol unreachable */
ICMP_DUR_PORT = 3, /* port unreachable */
ICMP_DUR_FRAG = 4, /* fragmentation needed and DF set */
ICMP_DUR_SR = 5 /* source route failed */
};
enum icmp_te_type {
ICMP_TE_TTL = 0, /* time to live exceeded in transit */
ICMP_TE_FRAG = 1 /* fragment reassembly time exceeded */
};
void icmp_input(struct pbuf *p, struct netif *inp);
void icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t);
void icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t);
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct icmp_echo_hdr {
PACK_STRUCT_FIELD(u16_t _type_code);
PACK_STRUCT_FIELD(u16_t chksum);
PACK_STRUCT_FIELD(u16_t id);
PACK_STRUCT_FIELD(u16_t seqno);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct icmp_dur_hdr {
PACK_STRUCT_FIELD(u16_t _type_code);
PACK_STRUCT_FIELD(u16_t chksum);
PACK_STRUCT_FIELD(u32_t unused);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct icmp_te_hdr {
PACK_STRUCT_FIELD(u16_t _type_code);
PACK_STRUCT_FIELD(u16_t chksum);
PACK_STRUCT_FIELD(u32_t unused);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define ICMPH_TYPE(hdr) (ntohs((hdr)->_type_code) >> 8)
#define ICMPH_CODE(hdr) (ntohs((hdr)->_type_code) & 0xff)
#define ICMPH_TYPE_SET(hdr, type) ((hdr)->_type_code = htons(ICMPH_CODE(hdr) | ((type) << 8)))
#define ICMPH_CODE_SET(hdr, code) ((hdr)->_type_code = htons((code) | (ICMPH_TYPE(hdr) << 8)))
#ifdef __cplusplus
}
#endif
#endif /* LWIP_ICMP */
#endif /* __LWIP_ICMP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv4/lwip/icmp.h | C | oos | 4,487 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_IP_H__
#define __LWIP_IP_H__
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#include "lwip/err.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ip_init() /* Compatibility define, not init needed. */
struct netif *ip_route(struct ip_addr *dest);
err_t ip_input(struct pbuf *p, struct netif *inp);
err_t ip_output(struct pbuf *p, struct ip_addr *src, struct ip_addr *dest,
u8_t ttl, u8_t tos, u8_t proto);
err_t ip_output_if(struct pbuf *p, struct ip_addr *src, struct ip_addr *dest,
u8_t ttl, u8_t tos, u8_t proto,
struct netif *netif);
#define IP_HLEN 20
#define IP_PROTO_ICMP 1
#define IP_PROTO_UDP 17
#define IP_PROTO_UDPLITE 136
#define IP_PROTO_TCP 6
/* This is passed as the destination address to ip_output_if (not
to ip_output), meaning that an IP header already is constructed
in the pbuf. This is used when TCP retransmits. */
#ifdef IP_HDRINCL
#undef IP_HDRINCL
#endif /* IP_HDRINCL */
#define IP_HDRINCL NULL
#if LWIP_NETIF_HWADDRHINT
#define IP_PCB_ADDRHINT ;u8_t addr_hint
#else
#define IP_PCB_ADDRHINT
#endif /* LWIP_NETIF_HWADDRHINT */
/* This is the common part of all PCB types. It needs to be at the
beginning of a PCB type definition. It is located here so that
changes to this common part are made in one location instead of
having to change all PCB structs. */
#define IP_PCB \
/* ip addresses in network byte order */ \
struct ip_addr local_ip; \
struct ip_addr remote_ip; \
/* Socket options */ \
u16_t so_options; \
/* Type Of Service */ \
u8_t tos; \
/* Time To Live */ \
u8_t ttl \
/* link layer address resolution hint */ \
IP_PCB_ADDRHINT
struct ip_pcb {
/* Common members of all PCB types */
IP_PCB;
};
/*
* Option flags per-socket. These are the same like SO_XXX.
*/
#define SOF_DEBUG (u16_t)0x0001U /* turn on debugging info recording */
#define SOF_ACCEPTCONN (u16_t)0x0002U /* socket has had listen() */
#define SOF_REUSEADDR (u16_t)0x0004U /* allow local address reuse */
#define SOF_KEEPALIVE (u16_t)0x0008U /* keep connections alive */
#define SOF_DONTROUTE (u16_t)0x0010U /* just use interface addresses */
#define SOF_BROADCAST (u16_t)0x0020U /* permit sending of broadcast msgs */
#define SOF_USELOOPBACK (u16_t)0x0040U /* bypass hardware when possible */
#define SOF_LINGER (u16_t)0x0080U /* linger on close if data present */
#define SOF_OOBINLINE (u16_t)0x0100U /* leave received OOB data in line */
#define SOF_REUSEPORT (u16_t)0x0200U /* allow local address & port reuse */
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#if (defined(__MWERKS__) || defined(__CWCC__))
#pragma options align= packed
#endif
struct ip_hdr {
/* version / header length / type of service */
PACK_STRUCT_FIELD(u16_t _v_hl_tos);
/* total length */
PACK_STRUCT_FIELD(u16_t _len);
/* identification */
PACK_STRUCT_FIELD(u16_t _id);
/* fragment offset field */
PACK_STRUCT_FIELD(u16_t _offset);
#define IP_RF 0x8000 /* reserved fragment flag */
#define IP_DF 0x4000 /* dont fragment flag */
#define IP_MF 0x2000 /* more fragments flag */
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
/* time to live / protocol*/
PACK_STRUCT_FIELD(u16_t _ttl_proto);
/* checksum */
PACK_STRUCT_FIELD(u16_t _chksum);
/* source and destination IP addresses */
PACK_STRUCT_FIELD(struct ip_addr src);
PACK_STRUCT_FIELD(struct ip_addr dest);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define IPH_V(hdr) (ntohs((hdr)->_v_hl_tos) >> 12)
#define IPH_HL(hdr) ((ntohs((hdr)->_v_hl_tos) >> 8) & 0x0f)
#define IPH_TOS(hdr) (ntohs((hdr)->_v_hl_tos) & 0xff)
#define IPH_LEN(hdr) ((hdr)->_len)
#define IPH_ID(hdr) ((hdr)->_id)
#define IPH_OFFSET(hdr) ((hdr)->_offset)
#define IPH_TTL(hdr) (ntohs((hdr)->_ttl_proto) >> 8)
#define IPH_PROTO(hdr) (ntohs((hdr)->_ttl_proto) & 0xff)
#define IPH_CHKSUM(hdr) ((hdr)->_chksum)
#define IPH_VHLTOS_SET(hdr, v, hl, tos) (hdr)->_v_hl_tos = (htons(((v) << 12) | ((hl) << 8) | (tos)))
#define IPH_LEN_SET(hdr, len) (hdr)->_len = (len)
#define IPH_ID_SET(hdr, id) (hdr)->_id = (id)
#define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off)
#define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl_proto = (htons(IPH_PROTO(hdr) | ((u16_t)(ttl) << 8)))
#define IPH_PROTO_SET(hdr, proto) (hdr)->_ttl_proto = (htons((proto) | (IPH_TTL(hdr) << 8)))
#define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum)
#if IP_DEBUG
void ip_debug_print(struct pbuf *p);
#else
#define ip_debug_print(p)
#endif /* IP_DEBUG */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_IP_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv4/lwip/ip.h | C | oos | 6,555 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LWIP_INET_H__
#define __LWIP_INET_H__
#include "lwip/opt.h"
#include "lwip/ip_addr.h"
#ifdef __cplusplus
extern "C" {
#endif
u32_t inet_addr(const char *cp);
int inet_aton(const char *cp, struct in_addr *addr);
char *inet_ntoa(struct in_addr addr); /* returns ptr to static buffer; not reentrant! */
#ifdef htons
#undef htons
#endif /* htons */
#ifdef htonl
#undef htonl
#endif /* htonl */
#ifdef ntohs
#undef ntohs
#endif /* ntohs */
#ifdef ntohl
#undef ntohl
#endif /* ntohl */
#ifndef LWIP_PLATFORM_BYTESWAP
#define LWIP_PLATFORM_BYTESWAP 0
#endif
#if BYTE_ORDER == BIG_ENDIAN
#define htons(x) (x)
#define ntohs(x) (x)
#define htonl(x) (x)
#define ntohl(x) (x)
#else /* BYTE_ORDER != BIG_ENDIAN */
#ifdef LWIP_PREFIX_BYTEORDER_FUNCS
/* workaround for naming collisions on some platforms */
#define htons lwip_htons
#define ntohs lwip_ntohs
#define htonl lwip_htonl
#define ntohl lwip_ntohl
#endif /* LWIP_PREFIX_BYTEORDER_FUNCS */
#if LWIP_PLATFORM_BYTESWAP
#define htons(x) LWIP_PLATFORM_HTONS(x)
#define ntohs(x) LWIP_PLATFORM_HTONS(x)
#define htonl(x) LWIP_PLATFORM_HTONL(x)
#define ntohl(x) LWIP_PLATFORM_HTONL(x)
#else /* LWIP_PLATFORM_BYTESWAP */
u16_t htons(u16_t x);
u16_t ntohs(u16_t x);
u32_t htonl(u32_t x);
u32_t ntohl(u32_t x);
#endif /* LWIP_PLATFORM_BYTESWAP */
#endif /* BYTE_ORDER == BIG_ENDIAN */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_INET_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv4/lwip/inet.h | C | oos | 3,084 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Jani Monoses <jani@iv.ro>
*
*/
#ifndef __LWIP_IP_FRAG_H__
#define __LWIP_IP_FRAG_H__
#include "lwip/opt.h"
#include "lwip/err.h"
#include "lwip/pbuf.h"
#include "lwip/netif.h"
#include "lwip/ip_addr.h"
#include "lwip/ip.h"
#ifdef __cplusplus
extern "C" {
#endif
#if IP_REASSEMBLY
/* The IP reassembly timer interval in milliseconds. */
#define IP_TMR_INTERVAL 1000
/* IP reassembly helper struct.
* This is exported because memp needs to know the size.
*/
struct ip_reassdata {
struct ip_reassdata *next;
struct pbuf *p;
struct ip_hdr iphdr;
u16_t datagram_len;
u8_t flags;
u8_t timer;
};
void ip_reass_init(void);
void ip_reass_tmr(void);
struct pbuf * ip_reass(struct pbuf *p);
#endif /* IP_REASSEMBLY */
#if IP_FRAG
err_t ip_frag(struct pbuf *p, struct netif *netif, struct ip_addr *dest);
#endif /* IP_FRAG */
#ifdef __cplusplus
}
#endif
#endif /* __LWIP_IP_FRAG_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/src/include/ipv4/lwip/ip_frag.h | C | oos | 2,534 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __LIB_H__
#define __LIB_H__
#include <string.h>
#endif /* __LIB_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/STR91x/arch/lib.h | C | oos | 1,728 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __CC_H__
#define __CC_H__
#include <stdio.h>
#include <stdlib.h>
#include "cpu.h"
typedef unsigned char u8_t;
typedef signed char s8_t;
typedef unsigned short u16_t;
typedef signed short s16_t;
typedef unsigned long u32_t;
typedef signed long s32_t;
typedef u32_t mem_ptr_t;
typedef int sys_prot_t;
#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_STRUCT
#define PACK_STRUCT_END
#define PACK_STRUCT_FIELD(x) x
#define LWIP_PLATFORM_DIAG(x)
#define LWIP_PLATFORM_ASSERT(x)
#endif /* __CC_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/STR91x/arch/cc.h | C | oos | 2,190 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __PERF_H__
#define __PERF_H__
#define PERF_START /* null definition */
#define PERF_STOP(x) /* null definition */
#endif /* __PERF_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/STR91x/arch/perf.h | C | oos | 1,798 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __ARCH_INIT_H__
#define __ARCH_INIT_H__
#define TCPIP_INIT_DONE(arg) tcpip_init_done(arg)
void tcpip_init_done(void *);
int wait_for_tcpip_init(void);
#endif /* __ARCH_INIT_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/STR91x/arch/init.h | C | oos | 1,848 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __CPU_H__
#define __CPU_H__
#define BYTE_ORDER LITTLE_ENDIAN
#endif /* __CPU_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/STR91x/arch/cpu.h | C | oos | 1,739 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __SYS_RTXC_H__
#define __SYS_RTXC_H__
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#define SYS_MBOX_NULL (xQueueHandle)0
#define SYS_SEM_NULL (xSemaphoreHandle)0
typedef xSemaphoreHandle sys_sem_t;
typedef xQueueHandle sys_mbox_t;
typedef xTaskHandle sys_thread_t;
/* Message queue constants. */
#define archMESG_QUEUE_LENGTH ( 6 )
#define archPOST_BLOCK_TIME_MS ( ( unsigned long ) 10000 )
#endif /* __SYS_RTXC_H__ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/STR91x/arch/sys_arch.h | C | oos | 2,128 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
/* lwIP includes. */
#include "lwip/debug.h"
#include "lwip/def.h"
#include "lwip/sys.h"
#include "lwip/mem.h"
#include "lwip/stats.h"
struct timeoutlist
{
struct sys_timeouts timeouts;
xTaskHandle pid;
};
/* This is the number of threads that can be started with sys_thread_new() */
#define SYS_THREAD_MAX 4
static struct timeoutlist s_timeoutlist[SYS_THREAD_MAX];
static u16_t s_nextthread = 0;
/*-----------------------------------------------------------------------------------*/
// Creates an empty mailbox.
sys_mbox_t sys_mbox_new(int size)
{
xQueueHandle mbox;
( void ) size;
mbox = xQueueCreate( archMESG_QUEUE_LENGTH, sizeof( void * ) );
#if SYS_STATS
++lwip_stats.sys.mbox.used;
if (lwip_stats.sys.mbox.max < lwip_stats.sys.mbox.used) {
lwip_stats.sys.mbox.max = lwip_stats.sys.mbox.used;
}
#endif /* SYS_STATS */
return mbox;
}
/*-----------------------------------------------------------------------------------*/
/*
Deallocates a mailbox. If there are messages still present in the
mailbox when the mailbox is deallocated, it is an indication of a
programming error in lwIP and the developer should be notified.
*/
void sys_mbox_free(sys_mbox_t mbox)
{
if( uxQueueMessagesWaiting( mbox ) )
{
/* Line for breakpoint. Should never break here! */
portNOP();
#if SYS_STATS
lwip_stats.sys.mbox.err++;
#endif /* SYS_STATS */
// TODO notify the user of failure.
}
vQueueDelete( mbox );
#if SYS_STATS
--lwip_stats.sys.mbox.used;
#endif /* SYS_STATS */
}
/*-----------------------------------------------------------------------------------*/
// Posts the "msg" to the mailbox.
void sys_mbox_post(sys_mbox_t mbox, void *data)
{
while ( xQueueSendToBack(mbox, &data, portMAX_DELAY ) != pdTRUE ){}
}
/*-----------------------------------------------------------------------------------*/
// Try to post the "msg" to the mailbox.
err_t sys_mbox_trypost(sys_mbox_t mbox, void *msg)
{
err_t result;
if ( xQueueSend( mbox, &msg, 0 ) == pdPASS )
{
result = ERR_OK;
}
else {
// could not post, queue must be full
result = ERR_MEM;
#if SYS_STATS
lwip_stats.sys.mbox.err++;
#endif /* SYS_STATS */
}
return result;
}
/*-----------------------------------------------------------------------------------*/
/*
Blocks the thread until a message arrives in the mailbox, but does
not block the thread longer than "timeout" milliseconds (similar to
the sys_arch_sem_wait() function). The "msg" argument is a result
parameter that is set by the function (i.e., by doing "*msg =
ptr"). The "msg" parameter maybe NULL to indicate that the message
should be dropped.
The return values are the same as for the sys_arch_sem_wait() function:
Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a
timeout.
Note that a function with a similar name, sys_mbox_fetch(), is
implemented by lwIP.
*/
u32_t sys_arch_mbox_fetch(sys_mbox_t mbox, void **msg, u32_t timeout)
{
void *dummyptr;
portTickType StartTime, EndTime, Elapsed;
StartTime = xTaskGetTickCount();
if ( msg == NULL )
{
msg = &dummyptr;
}
if ( timeout != 0 )
{
if ( pdTRUE == xQueueReceive( mbox, &(*msg), timeout / portTICK_RATE_MS ) )
{
EndTime = xTaskGetTickCount();
Elapsed = (EndTime - StartTime) * portTICK_RATE_MS;
return ( Elapsed );
}
else // timed out blocking for message
{
*msg = NULL;
return SYS_ARCH_TIMEOUT;
}
}
else // block forever for a message.
{
while( pdTRUE != xQueueReceive( mbox, &(*msg), portMAX_DELAY ) ){} // time is arbitrary
EndTime = xTaskGetTickCount();
Elapsed = (EndTime - StartTime) * portTICK_RATE_MS;
return ( Elapsed ); // return time blocked TODO test
}
}
/*-----------------------------------------------------------------------------------*/
/*
Similar to sys_arch_mbox_fetch, but if message is not ready immediately, we'll
return with SYS_MBOX_EMPTY. On success, 0 is returned.
*/
u32_t sys_arch_mbox_tryfetch(sys_mbox_t mbox, void **msg)
{
void *dummyptr;
if ( msg == NULL )
{
msg = &dummyptr;
}
if ( pdTRUE == xQueueReceive( mbox, &(*msg), 0 ) )
{
return ERR_OK;
}
else
{
return SYS_MBOX_EMPTY;
}
}
/*-----------------------------------------------------------------------------------*/
// Creates and returns a new semaphore. The "count" argument specifies
// the initial state of the semaphore.
sys_sem_t sys_sem_new(u8_t count)
{
xSemaphoreHandle xSemaphore;
vSemaphoreCreateBinary( xSemaphore );
if( xSemaphore == NULL )
{
#if SYS_STATS
++lwip_stats.sys.sem.err;
#endif /* SYS_STATS */
return SYS_SEM_NULL; // TODO need assert
}
if(count == 0) // Means it can't be taken
{
xSemaphoreTake(xSemaphore,1);
}
#if SYS_STATS
++lwip_stats.sys.sem.used;
if (lwip_stats.sys.sem.max < lwip_stats.sys.sem.used) {
lwip_stats.sys.sem.max = lwip_stats.sys.sem.used;
}
#endif /* SYS_STATS */
return xSemaphore;
}
/*-----------------------------------------------------------------------------------*/
/*
Blocks the thread while waiting for the semaphore to be
signaled. If the "timeout" argument is non-zero, the thread should
only be blocked for the specified time (measured in
milliseconds).
If the timeout argument is non-zero, the return value is the number of
milliseconds spent waiting for the semaphore to be signaled. If the
semaphore wasn't signaled within the specified time, the return value is
SYS_ARCH_TIMEOUT. If the thread didn't have to wait for the semaphore
(i.e., it was already signaled), the function may return zero.
Notice that lwIP implements a function with a similar name,
sys_sem_wait(), that uses the sys_arch_sem_wait() function.
*/
u32_t sys_arch_sem_wait(sys_sem_t sem, u32_t timeout)
{
portTickType StartTime, EndTime, Elapsed;
StartTime = xTaskGetTickCount();
if( timeout != 0)
{
if( xSemaphoreTake( sem, timeout / portTICK_RATE_MS ) == pdTRUE )
{
EndTime = xTaskGetTickCount();
Elapsed = (EndTime - StartTime) * portTICK_RATE_MS;
return (Elapsed); // return time blocked TODO test
}
else
{
return SYS_ARCH_TIMEOUT;
}
}
else // must block without a timeout
{
while( xSemaphoreTake( sem, portMAX_DELAY ) != pdTRUE ){}
EndTime = xTaskGetTickCount();
Elapsed = (EndTime - StartTime) * portTICK_RATE_MS;
return ( Elapsed ); // return time blocked
}
}
/*-----------------------------------------------------------------------------------*/
// Signals a semaphore
void sys_sem_signal(sys_sem_t sem)
{
xSemaphoreGive( sem );
}
/*-----------------------------------------------------------------------------------*/
// Deallocates a semaphore
void sys_sem_free(sys_sem_t sem)
{
#if SYS_STATS
--lwip_stats.sys.sem.used;
#endif /* SYS_STATS */
vQueueDelete( sem );
}
/*-----------------------------------------------------------------------------------*/
// Initialize sys arch
void sys_init(void)
{
int i;
// Initialize the the per-thread sys_timeouts structures
// make sure there are no valid pids in the list
for(i = 0; i < SYS_THREAD_MAX; i++)
{
s_timeoutlist[i].pid = 0;
s_timeoutlist[i].timeouts.next = NULL;
}
// keep track of how many threads have been created
s_nextthread = 0;
}
/*-----------------------------------------------------------------------------------*/
/*
Returns a pointer to the per-thread sys_timeouts structure. In lwIP,
each thread has a list of timeouts which is represented as a linked
list of sys_timeout structures. The sys_timeouts structure holds a
pointer to a linked list of timeouts. This function is called by
the lwIP timeout scheduler and must not return a NULL value.
In a single threaded sys_arch implementation, this function will
simply return a pointer to a global sys_timeouts variable stored in
the sys_arch module.
*/
struct sys_timeouts *sys_arch_timeouts(void)
{
int i;
xTaskHandle pid;
struct timeoutlist *tl;
pid = xTaskGetCurrentTaskHandle( );
for(i = 0; i < s_nextthread; i++)
{
tl = &(s_timeoutlist[i]);
if(tl->pid == pid)
{
return &(tl->timeouts);
}
}
// Error
return NULL;
}
/*-----------------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------------*/
// TODO
/*-----------------------------------------------------------------------------------*/
/*
Starts a new thread with priority "prio" that will begin its execution in the
function "thread()". The "arg" argument will be passed as an argument to the
thread() function. The id of the new thread is returned. Both the id and
the priority are system dependent.
*/
sys_thread_t sys_thread_new(char *name, void (* thread)(void *arg), void *arg, int stacksize, int prio)
{
xTaskHandle CreatedTask;
int result;
if ( s_nextthread < SYS_THREAD_MAX )
{
result = xTaskCreate( thread, ( signed portCHAR * ) name, stacksize, arg, prio, &CreatedTask );
// For each task created, store the task handle (pid) in the timers array.
// This scheme doesn't allow for threads to be deleted
s_timeoutlist[s_nextthread++].pid = CreatedTask;
if(result == pdPASS)
{
return CreatedTask;
}
else
{
return NULL;
}
}
else
{
return NULL;
}
}
/*
This optional function does a "fast" critical region protection and returns
the previous protection level. This function is only called during very short
critical regions. An embedded system which supports ISR-based drivers might
want to implement this function by disabling interrupts. Task-based systems
might want to implement this by using a mutex or disabling tasking. This
function should support recursive calls from the same task or interrupt. In
other words, sys_arch_protect() could be called while already protected. In
that case the return value indicates that it is already protected.
sys_arch_protect() is only required if your port is supporting an operating
system.
*/
sys_prot_t sys_arch_protect(void)
{
vPortEnterCritical();
return 1;
}
/*
This optional function does a "fast" set of critical region protection to the
value specified by pval. See the documentation for sys_arch_protect() for
more information. This function is only required if your port is supporting
an operating system.
*/
void sys_arch_unprotect(sys_prot_t pval)
{
( void ) pval;
vPortExitCritical();
}
/*
* Prints an assertion messages and aborts execution.
*/
void sys_assert( const char *msg )
{
( void ) msg;
/*FSL:only needed for debugging
printf(msg);
printf("\n\r");
*/
vPortEnterCritical( );
for(;;)
;
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/sys_arch.c | C | oos | 12,775 |
/*!
* \file eth.h
* \brief Definitions for Ethernet Physical Layer Interface
* \version $Revision: 1.3 $
* \author Michael Norman
*/
#ifndef _ETH_PHY_H
#define _ETH_PHY_H
/*******************************************************************/
int
eth_phy_autoneg(int phy_addr, MII_SPEED speed, MII_DUPLEX duplex);
int
eth_phy_manual(int phy_addr, MII_SPEED speed, MII_DUPLEX duplex, int loop);
int
eth_phy_get_speed(int, int*);
int
eth_phy_get_duplex(int, int*);
int
eth_phy_reg_dump(int);
/*******************************************************************/
/* MII Register Addresses */
#define PHY_BMCR (0x00)
#define PHY_BMSR (0x01)
#define PHY_PHYIDR1 (0x02)
#define PHY_PHYIDR2 (0x03)
#define PHY_ANAR (0x04)
#define PHY_ANLPAR (0x05)
/* Bit definitions and macros for PHY_CTRL */
#define PHY_BMCR_RESET (0x8000)
#define PHY_BMCR_LOOP (0x4000)
#define PHY_BMCR_SPEED (0x2000)
#define PHY_BMCR_AN_ENABLE (0x1000)
#define PHY_BMCR_POWERDOWN (0x0800)
#define PHY_BMCR_ISOLATE (0x0400)
#define PHY_BMCR_AN_RESTART (0x0200)
#define PHY_BMCR_FDX (0x0100)
#define PHY_BMCR_COL_TEST (0x0080)
/* Bit definitions and macros for PHY_STAT */
#define PHY_BMSR_100BT4 (0x8000)
#define PHY_BMSR_100BTX_FDX (0x4000)
#define PHY_BMSR_100BTX (0x2000)
#define PHY_BMSR_10BT_FDX (0x1000)
#define PHY_BMSR_10BT (0x0800)
#define PHY_BMSR_NO_PREAMBLE (0x0040)
#define PHY_BMSR_AN_COMPLETE (0x0020)
#define PHY_BMSR_REMOTE_FAULT (0x0010)
#define PHY_BMSR_AN_ABILITY (0x0008)
#define PHY_BMSR_LINK (0x0004)
#define PHY_BMSR_JABBER (0x0002)
#define PHY_BMSR_EXTENDED (0x0001)
/* Bit definitions and macros for PHY_AN_ADV */
#define PHY_ANAR_NEXT_PAGE (0x8001)
#define PHY_ANAR_REM_FAULT (0x2001)
#define PHY_ANAR_PAUSE (0x0401)
#define PHY_ANAR_100BT4 (0x0201)
#define PHY_ANAR_100BTX_FDX (0x0101)
#define PHY_ANAR_100BTX (0x0081)
#define PHY_ANAR_10BT_FDX (0x0041)
#define PHY_ANAR_10BT (0x0021)
#define PHY_ANAR_802_3 (0x0001)
/* Bit definitions and macros for PHY_AN_LINK_PAR */
#define PHY_ANLPAR_NEXT_PAGE (0x8000)
#define PHY_ANLPAR_ACK (0x4000)
#define PHY_ANLPAR_REM_FAULT (0x2000)
#define PHY_ANLPAR_PAUSE (0x0400)
#define PHY_ANLPAR_100BT4 (0x0200)
#define PHY_ANLPAR_100BTX_FDX (0x0100)
#define PHY_ANLPAR_100BTX (0x0080)
#define PHY_ANLPAR_10BTX_FDX (0x0040)
#define PHY_ANLPAR_10BT (0x0020)
/*******************************************************************/
#endif /* _ETH_PHY_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/eth_phy.h | C | oos | 2,875 |
/*!
* \file mii.h
* \brief Media Independent Interface (MII) driver
* \version $Revision: 1.3 $
* \author Michael Norman
*
* \warning This driver assumes that FEC0 is used for all MII management
* communications. For dual PHYs, etc., insure that FEC0_MDC and
* FEC0_MDIO are connected to the PHY's MDC and MDIO.
*/
#ifndef _MII_H_
#define _MII_H_
/*******************************************************************/
int
mii_write(int, int, uint16);
int
mii_read(int, int, uint16*);
void
mii_init(int);
/* MII Speed Settings */
typedef enum {
MII_10BASE_T, /*!< 10Base-T operation */
MII_100BASE_TX /*!< 100Base-TX operation */
} MII_SPEED;
/* MII Duplex Settings */
typedef enum {
MII_HDX, /*!< half-duplex */
MII_FDX /*!< full-duplex */
} MII_DUPLEX;
#define MII_TIMEOUT 0x10000
#define MII_LINK_TIMEOUT 0x10000
/*******************************************************************/
#endif /* _MII_H_ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/mii.h | C | oos | 1,006 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* Modifications Copyright (c) 2006 Christian Walter <wolti@sil.at>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
* Modifcations: Christian Walter <wolti@sil.at>
*
* $Id: sys_arch.c,v 1.1 2008/08/05 00:10:49 b06862 Exp $
*/
/* ------------------------ System includes ------------------------------- */
#include "stdlib.h"
/* ------------------------ FreeRTOS includes ----------------------------- */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* ------------------------ lwIP includes --------------------------------- */
#include "lwip/debug.h"
#include "lwip/def.h"
#include "lwip/sys.h"
#include "lwip/mem.h"
#include "lwip/sio.h"
#include "lwip/stats.h"
/* ------------------------ Project includes ------------------------------ */
/* ------------------------ Defines --------------------------------------- */
/* This is the number of threads that can be started with sys_thead_new() */
#define SYS_MBOX_SIZE ( 16 )
#define MS_TO_TICKS( ms ) \
( portTickType )( ( portTickType ) ( ms ) / portTICK_RATE_MS )
#define TICKS_TO_MS( ticks ) \
( unsigned long )( ( portTickType ) ( ticks ) * portTICK_RATE_MS )
#define THREAD_STACK_SIZE ( 256 /*FSL:1024*/ )
#define THREAD_NAME "lwIP"
#define THREAD_INIT( tcb ) \
do { \
tcb->next = NULL; \
tcb->pid = ( xTaskHandle )0; \
tcb->timeouts.next = NULL; \
} while( 0 )
/* ------------------------ Type definitions ------------------------------ */
typedef struct sys_tcb
{
struct sys_tcb *next;
struct sys_timeouts timeouts;
xTaskHandle pid;
} sys_tcb_t;
/* ------------------------ Prototypes ------------------------------------ */
/* ------------------------ Static functions ------------------------------ */
sys_tcb_t *sys_thread_current( void );
/* ------------------------ Static variables ------------------------------ */
static sys_tcb_t *tasks = NULL;
/* ------------------------ Start implementation -------------------------- */
void
sys_init( void )
{
LWIP_ASSERT( "sys_init: not called first", tasks == NULL );
tasks = NULL;
}
/*
* This optional function does a "fast" critical region protection and returns
* the previous protection level. This function is only called during very short
* critical regions. An embedded system which supports ISR-based drivers might
* want to implement this function by disabling interrupts. Task-based systems
* might want to implement this by using a mutex or disabling tasking. This
* function should support recursive calls from the same task or interrupt. In
* other words, sys_arch_protect() could be called while already protected. In
* that case the return value indicates that it is already protected.
*
* sys_arch_protect() is only required if your port is supporting an operating
* system.
*/
sys_prot_t
sys_arch_protect( void )
{
vPortEnterCritical( );
return 1;
}
/*
* This optional function does a "fast" set of critical region protection to the
* value specified by pval. See the documentation for sys_arch_protect() for
* more information. This function is only required if your port is supporting
* an operating system.
*/
void
sys_arch_unprotect( sys_prot_t pval )
{
( void )pval;
vPortExitCritical( );
}
/*
* Prints an assertion messages and aborts execution.
*/
void
sys_assert( const char *msg )
{
/*FSL:only needed for debugging
printf(msg);
printf("\n\r");
*/
vPortEnterCritical( );
for(;;)
;
}
void
sys_debug( const char *const fmt, ... )
{
/*FSL: same implementation as printf*/
/*FSL: removed due to lack of space*/
//printf(fmt);
}
/* ------------------------ Start implementation ( Threads ) -------------- */
/*
* Starts a new thread with priority "prio" that will begin its execution in the
* function "thread()". The "arg" argument will be passed as an argument to the
* thread() function. The argument "ssize" is the requested stack size for the
* new thread. The id of the new thread is returned. Both the id and the
* priority are system dependent.
*/
sys_thread_t
sys_thread_new(char *name, void ( *thread ) ( void *arg ), void *arg, int /*size_t*/ stacksize, int prio )
{
sys_thread_t thread_hdl = SYS_THREAD_NULL;
int i;
sys_tcb_t *p;
/* We disable the FreeRTOS scheduler because it might be the case that the new
* tasks gets scheduled inside the xTaskCreate function. To prevent this we
* disable the scheduling. Note that this can happen although we have interrupts
* disabled because xTaskCreate contains a call to taskYIELD( ).
*/
vPortEnterCritical( );
p = tasks;
i = 0;
/* We are called the first time. Initialize it. */
if( p == NULL )
{
p = (sys_tcb_t *)pvPortMalloc( sizeof( sys_tcb_t ) );
if( p != NULL )
{
tasks = p;
}
}
else
{
/* First task already counter. */
i++;
/* Cycle to the end of the list. */
while( p->next != NULL )
{
i++;
p = p->next;
}
p->next = (sys_tcb_t *)pvPortMalloc( sizeof( sys_tcb_t ) );
p = p->next;
}
if( p != NULL )
{
/* Memory allocated. Initialize the data structure. */
THREAD_INIT( p );
/* Now q points to a free element in the list. */
if( xTaskCreate( thread, (const signed char *const)name, stacksize, arg, prio, &p->pid ) == pdPASS )
{
thread_hdl = p;
}
else
{
vPortFree( p );
}
}
vPortExitCritical( );
return thread_hdl;
}
void
sys_arch_thread_remove( sys_thread_t hdl )
{
sys_tcb_t *current = tasks, *prev;
sys_tcb_t *toremove = hdl;
xTaskHandle pid = ( xTaskHandle ) 0;
LWIP_ASSERT( "sys_arch_thread_remove: assertion hdl != NULL failed!", hdl != NULL );
/* If we have to remove the first task we must update the global "tasks"
* variable. */
vPortEnterCritical( );
if( hdl != NULL )
{
prev = NULL;
while( ( current != NULL ) && ( current != toremove ) )
{
prev = current;
current = current->next;
}
/* Found it. */
if( current == toremove )
{
/* Not the first entry in the list. */
if( prev != NULL )
{
prev->next = toremove->next;
}
else
{
tasks = toremove->next;
}
LWIP_ASSERT( "sys_arch_thread_remove: can't remove thread with timeouts!",
toremove->timeouts.next == NULL );
pid = toremove->pid;
THREAD_INIT( toremove );
vPortFree( toremove );
}
}
/* We are done with accessing the shared datastructure. Release the
* resources.
*/
vPortExitCritical( );
if( pid != ( xTaskHandle ) 0 )
{
vTaskDelete( pid );
/* not reached. */
}
}
/*
* Returns the thread control block for the currently active task. In case
* of an error the functions returns NULL.
*/
sys_thread_t
sys_arch_thread_current( void )
{
sys_tcb_t *p = tasks;
xTaskHandle pid = xTaskGetCurrentTaskHandle( );
vPortEnterCritical( );
while( ( p != NULL ) && ( p->pid != pid ) )
{
p = p->next;
}
vPortExitCritical( );
return p;
}
/*
* Returns a pointer to the per-thread sys_timeouts structure. In lwIP,
* each thread has a list of timeouts which is represented as a linked
* list of sys_timeout structures. The sys_timeouts structure holds a
* pointer to a linked list of timeouts. This function is called by
* the lwIP timeout scheduler and must not return a NULL value.
*
* In a single threaded sys_arch implementation, this function will
* simply return a pointer to a global sys_timeouts variable stored in
* the sys_arch module.
*/
struct sys_timeouts *
sys_arch_timeouts( void )
{
sys_tcb_t *ptask;
ptask = sys_arch_thread_current( );
LWIP_ASSERT( "sys_arch_timeouts: ptask != NULL", ptask != NULL );
return ptask != NULL ? &( ptask->timeouts ) : NULL;
}
/* ------------------------ Start implementation ( Semaphores ) ----------- */
/* Creates and returns a new semaphore. The "count" argument specifies
* the initial state of the semaphore.
*/
sys_sem_t
sys_sem_new( u8_t count )
{
xSemaphoreHandle xSemaphore;
vSemaphoreCreateBinary( xSemaphore );
if( xSemaphore != SYS_SEM_NULL )
{
if( count == 0 )
{
xSemaphoreTake( xSemaphore, 1 );
}
#if SYS_STATS == 1
vPortEnterCritical( );
lwip_stats.sys.sem.used++;
if( lwip_stats.sys.sem.used > lwip_stats.sys.sem.max )
{
lwip_stats.sys.sem.max = lwip_stats.sys.sem.used;
}
vPortExitCritical( );
#endif
}
else
{
LWIP_ASSERT( "sys_sem_new: xSemaphore == SYS_SEM_NULL", xSemaphore != SYS_SEM_NULL );
}
return xSemaphore;
}
/* Deallocates a semaphore */
void
sys_sem_free( sys_sem_t sem )
{
LWIP_ASSERT( "sys_sem_free: sem != SYS_SEM_NULL", sem != SYS_SEM_NULL );
if( sem != SYS_SEM_NULL )
{
#if SYS_STATS == 1
vPortEnterCritical( );
lwip_stats.sys.sem.used--;
vPortExitCritical( );
#endif
vQueueDelete( sem );
}
}
/* Signals a semaphore */
void
sys_sem_signal( sys_sem_t sem )
{
LWIP_ASSERT( "sys_sem_signal: sem != SYS_SEM_NULL", sem != SYS_SEM_NULL );
xSemaphoreGive( sem );
}
/*
* Blocks the thread while waiting for the semaphore to be
* signaled. If the "timeout" argument is non-zero, the thread should
* only be blocked for the specified time (measured in
* milliseconds).
*
* If the timeout argument is non-zero, the return value is the number of
* milliseconds spent waiting for the semaphore to be signaled. If the
* semaphore wasn't signaled within the specified time, the return value is
* SYS_ARCH_TIMEOUT. If the thread didn't have to wait for the semaphore
* (i.e., it was already signaled), the function may return zero.
*
* Notice that lwIP implements a function with a similar name,
* sys_sem_wait(), that uses the sys_arch_sem_wait() function.
*/
u32_t
sys_arch_sem_wait( sys_sem_t sem, u32_t timeout )
{
portBASE_TYPE xStatus;
portTickType xTicksStart, xTicksEnd, xTicksElapsed;
u32_t timespent;
LWIP_ASSERT( "sys_arch_sem_wait: sem != SYS_SEM_NULL", sem != SYS_SEM_NULL );
xTicksStart = xTaskGetTickCount( );
if( timeout == 0 )
{
do
{
xStatus = xSemaphoreTake( sem, MS_TO_TICKS( 100 ) );
}
while( xStatus != pdTRUE );
}
else
{
xStatus = xSemaphoreTake( sem, MS_TO_TICKS( timeout ) );
}
/* Semaphore was signaled. */
if( xStatus == pdTRUE )
{
xTicksEnd = xTaskGetTickCount( );
xTicksElapsed = xTicksEnd - xTicksStart;
timespent = TICKS_TO_MS( xTicksElapsed );
}
else
{
timespent = SYS_ARCH_TIMEOUT;
}
return timespent;
}
/* ------------------------ Start implementation ( Mailboxes ) ------------ */
/* Creates an empty mailbox. */
sys_mbox_t
sys_mbox_new( /*paolo:void*/int size )
{
xQueueHandle mbox;
mbox = xQueueCreate( SYS_MBOX_SIZE/*size*/, sizeof( void * ) );
if( mbox != SYS_MBOX_NULL )
{
#if SYS_STATS == 1
vPortEnterCritical( );
lwip_stats.sys.mbox.used++;
if( lwip_stats.sys.mbox.used > lwip_stats.sys.mbox.max )
{
lwip_stats.sys.mbox.max = lwip_stats.sys.mbox.used;
}
vPortExitCritical( );
#endif
}
return mbox;
}
/*
Deallocates a mailbox. If there are messages still present in the
mailbox when the mailbox is deallocated, it is an indication of a
programming error in lwIP and the developer should be notified.
*/
void
sys_mbox_free( sys_mbox_t mbox )
{
void *msg;
LWIP_ASSERT( "sys_mbox_free: mbox != SYS_MBOX_NULL", mbox != SYS_MBOX_NULL );
if( mbox != SYS_MBOX_NULL )
{
while( uxQueueMessagesWaiting( mbox ) != 0 )
{
if( sys_arch_mbox_fetch( mbox, &msg, 1 ) != SYS_ARCH_TIMEOUT )
{
LWIP_ASSERT( "sys_mbox_free: memory leak (msg != NULL)", msg == NULL );
}
}
vQueueDelete( mbox );
#if SYS_STATS == 1
vPortEnterCritical( );
lwip_stats.sys.mbox.used--;
vPortExitCritical( );
#endif
}
}
/*
* This function sends a message to a mailbox. It is unusual in that no error
* return is made. This is because the caller is responsible for ensuring that
* the mailbox queue will not fail. The caller does this by limiting the number
* of msg structures which exist for a given mailbox.
*/
void
sys_mbox_post( sys_mbox_t mbox, void *data )
{
portBASE_TYPE xQueueSent;
/* Queue must not be full - Otherwise it is an error. */
xQueueSent = xQueueSend( mbox, &data, 0 );
LWIP_ASSERT( "sys_mbox_post: xQueueSent == pdPASS", xQueueSent == pdPASS );
}
/*FSL*/
/*
*Try to post the "msg" to the mailbox. Returns ERR_MEM if this one
*is full, else, ERR_OK if the "msg" is posted.
*/
err_t
sys_mbox_trypost( sys_mbox_t mbox, void *data )
{
/* Queue must not be full - Otherwise it is an error. */
if(xQueueSend( mbox, &data, 0 ) == pdPASS)
{
return ERR_OK;
}
else
{
return ERR_MEM;
}
}
/*
* Blocks the thread until a message arrives in the mailbox, but does
* not block the thread longer than "timeout" milliseconds (similar to
* the sys_arch_sem_wait() function). The "msg" argument is a result
* parameter that is set by the function (i.e., by doing "*msg =
* ptr"). The "msg" parameter maybe NULL to indicate that the message
* should be dropped.
*
* Note that a function with a similar name, sys_mbox_fetch(), is
* implemented by lwIP.
*/
u32_t
sys_arch_mbox_fetch( sys_mbox_t mbox, void **msg, u32_t timeout )
{
void *ret_msg;
portBASE_TYPE xStatus;
portTickType xTicksStart, xTicksEnd, xTicksElapsed;
u32_t timespent;
LWIP_ASSERT( "sys_arch_mbox_fetch: mbox != SYS_MBOX_NULL", mbox != SYS_MBOX_NULL );
xTicksStart = xTaskGetTickCount( );
if( timeout == 0 )
{
do
{
xStatus = xQueueReceive( mbox, &ret_msg, MS_TO_TICKS( 100 ) );
}
while( xStatus != pdTRUE );
}
else
{
xStatus = xQueueReceive( mbox, &ret_msg, MS_TO_TICKS( timeout ) );
}
if( xStatus == pdTRUE )
{
if( msg )
{
*msg = ret_msg;
}
xTicksEnd = xTaskGetTickCount( );
xTicksElapsed = xTicksEnd - xTicksStart;
timespent = TICKS_TO_MS( xTicksElapsed );
}
else
{
if( msg )
{
*msg = NULL;
}
timespent = SYS_ARCH_TIMEOUT;
}
return timespent;
}
u32_t
sys_jiffies( void )
{
portTickType xTicks = xTaskGetTickCount( );
return ( u32_t )TICKS_TO_MS( xTicks );
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/__sys_arch.c | C | oos | 17,289 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
* Modifcations: Christian Walter <wolti@sil.at>
*/
#ifndef __CC_H__
#define __CC_H__
/* ------------------------ System includes ------------------------------- */
/* ------------------------ Project includes ------------------------------ */
#include "cpu.h"
#include "sys_arch.h"
/* ------------------------ Defines --------------------------------------- */
//#pragma options align= packed
#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_STRUCT //non CW compatible: __attribute__ ((__packed__))
#define PACK_STRUCT_END
#define PACK_STRUCT_FIELD( x ) x
/*FSL: non used on code:
#define ALIGN_STRUCT_8_BEGIN
#define ALIGN_STRUCT_8 //non CW compatible: __attribute__ ((aligned (8)))
#define ALIGN_STRUCT_8_END
*/
#define LWIP_PLATFORM_ASSERT( x ) sys_assert( x )
#define LWIP_PLATFORM_DIAG( x, ... ) do{ sys_debug x; } while( 0 );
/* Define (sn)printf formatters for these lwIP types */
#define U16_F "hu"
#define S16_F "hd"
#define X16_F "hx"
#define U32_F "lu"
#define S32_F "ld"
#define X32_F "lx"
/* ------------------------ Type definitions (lwIP) ----------------------- */
typedef unsigned char u8_t;
typedef signed char s8_t;
typedef unsigned short u16_t;
typedef signed short s16_t;
typedef unsigned long u32_t;
typedef signed long s32_t;
typedef u32_t mem_ptr_t;
typedef int sys_prot_t;
/* ------------------------ Prototypes ------------------------------------ */
#endif
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/arch/cc.h | C | oos | 3,191 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __PERF_H__
#define __PERF_H__
/* ------------------------ Defines --------------------------------------- */
#define PERF_START /* null definition */
#define PERF_STOP(x) /* null definition */
#endif
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/arch/perf.h | C | oos | 1,867 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __CPU_H__
#define __CPU_H__
/* ------------------------ Defines --------------------------------------- */
#define BYTE_ORDER BIG_ENDIAN
#endif
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/arch/cpu.h | C | oos | 1,786 |
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#ifndef __SYS_RTXC_H__
#define __SYS_RTXC_H__
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#define SYS_MBOX_NULL (xQueueHandle)0
#define SYS_SEM_NULL (xSemaphoreHandle)0
typedef xSemaphoreHandle sys_sem_t;
typedef xQueueHandle sys_mbox_t;
typedef xTaskHandle sys_thread_t;
/* Message queue constants. */
#define archMESG_QUEUE_LENGTH ( 6 )
#define archPOST_BLOCK_TIME_MS ( ( unsigned long ) 10000 )
#endif
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/arch/sys_arch.h | C | oos | 2,091 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
/* Standard library includes. */
#include <stdio.h>
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
xTaskHandle xEthIntTask;
/* lwIP includes. */
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include "lwip/sys.h"
#include "lwip/stats.h"
#include "lwip/snmp.h"
#include "netif/etharp.h"
/* Hardware includes. */
#include "fec.h"
/* Delay to wait for a DMA buffer to become available if one is not already
available. */
#define netifBUFFER_WAIT_ATTEMPTS 10
#define netifBUFFER_WAIT_DELAY (10 / portTICK_RATE_MS)
/* Delay between polling the PHY to see if a link has been established. */
#define netifLINK_DELAY ( 500 / portTICK_RATE_MS )
/* Delay between looking for incoming packets. In ideal world this would be
infinite. */
#define netifBLOCK_TIME_WAITING_FOR_INPUT netifLINK_DELAY
/* Name for the netif. */
#define IFNAME0 'e'
#define IFNAME1 'n'
/* Hardware specific. */
#define netifFIRST_FEC_VECTOR 23
/*-----------------------------------------------------------*/
/* The DMA descriptors. This is a char array to allow us to align it correctly. */
static unsigned char xFECTxDescriptors_unaligned[ ( configNUM_FEC_TX_BUFFERS * sizeof( FECBD ) ) + 16 ];
static unsigned char xFECRxDescriptors_unaligned[ ( configNUM_FEC_RX_BUFFERS * sizeof( FECBD ) ) + 16 ];
static FECBD *xFECTxDescriptors;
static FECBD *xFECRxDescriptors;
/* The DMA buffers. These are char arrays to allow them to be alligned correctly. */
static unsigned char ucFECTxBuffers[ ( configNUM_FEC_TX_BUFFERS * configFEC_BUFFER_SIZE ) + 16 ];
static unsigned char ucFECRxBuffers[ ( configNUM_FEC_RX_BUFFERS * configFEC_BUFFER_SIZE ) + 16 ];
static unsigned portBASE_TYPE uxNextRxBuffer = 0, uxNextTxBuffer = 0;
/* Semaphore used by the FEC interrupt handler to wake the handler task. */
static xSemaphoreHandle xFecSemaphore;
#pragma options align= packed
struct ethernetif
{
struct eth_addr *ethaddr;
/* Add whatever per-interface state that is needed here. */
};
/*-----------------------------------------------------------*/
/* Standard lwIP netif handlers. */
static void prvInitialiseFECBuffers( void );
static void low_level_init( struct netif *netif );
static err_t low_level_output(struct netif *netif, struct pbuf *p);
static struct pbuf *low_level_input(struct netif *netif);
static void ethernetif_input( void *pParams );
/* Functions adapted from Freescale provided code. */
static int fec_mii_write( int phy_addr, int reg_addr, int data );
static int fec_mii_read( int phy_addr, int reg_addr, uint16* data );
static uint8 fec_hash_address( const uint8* addr );
static void fec_set_address( const uint8 *pa );
static void fec_irq_enable( void );
/*-----------------------------------------------------------*/
/********************************************************************/
/*
* Write a value to a PHY's MII register.
*
* Parameters:
* ch FEC channel
* phy_addr Address of the PHY.
* reg_addr Address of the register in the PHY.
* data Data to be written to the PHY register.
*
* Return Values:
* 0 on failure
* 1 on success.
*
* Please refer to your PHY manual for registers and their meanings.
* mii_write() polls for the FEC's MII interrupt event and clears it.
* If after a suitable amount of time the event isn't triggered, a
* value of 0 is returned.
*/
static int fec_mii_write( int phy_addr, int reg_addr, int data )
{
int timeout;
uint32 eimr;
/* Clear the MII interrupt bit */
MCF_FEC_EIR = MCF_FEC_EIR_MII;
/* Mask the MII interrupt */
eimr = MCF_FEC_EIMR;
MCF_FEC_EIMR &= ~MCF_FEC_EIMR_MII;
/* Write to the MII Management Frame Register to kick-off the MII write */
MCF_FEC_MMFR = MCF_FEC_MMFR_ST_01 | MCF_FEC_MMFR_OP_WRITE | MCF_FEC_MMFR_PA(phy_addr) | MCF_FEC_MMFR_RA(reg_addr) | MCF_FEC_MMFR_TA_10 | MCF_FEC_MMFR_DATA( data );
/* Poll for the MII interrupt (interrupt should be masked) */
for (timeout = 0; timeout < MII_TIMEOUT; timeout++)
{
if (MCF_FEC_EIR & MCF_FEC_EIR_MII)
{
break;
}
}
if( timeout == MII_TIMEOUT )
{
return 0;
}
/* Clear the MII interrupt bit */
MCF_FEC_EIR = MCF_FEC_EIR_MII;
/* Restore the EIMR */
MCF_FEC_EIMR = eimr;
return 1;
}
/********************************************************************/
/*
* Read a value from a PHY's MII register.
*
* Parameters:
* ch FEC channel
* phy_addr Address of the PHY.
* reg_addr Address of the register in the PHY.
* data Pointer to storage for the Data to be read
* from the PHY register (passed by reference)
*
* Return Values:
* 0 on failure
* 1 on success.
*
* Please refer to your PHY manual for registers and their meanings.
* mii_read() polls for the FEC's MII interrupt event and clears it.
* If after a suitable amount of time the event isn't triggered, a
* value of 0 is returned.
*/
static int fec_mii_read( int phy_addr, int reg_addr, uint16* data )
{
int timeout;
uint32 eimr;
/* Clear the MII interrupt bit */
MCF_FEC_EIR = MCF_FEC_EIR_MII;
/* Mask the MII interrupt */
eimr = MCF_FEC_EIMR;
MCF_FEC_EIMR &= ~MCF_FEC_EIMR_MII;
/* Write to the MII Management Frame Register to kick-off the MII read */
MCF_FEC_MMFR = MCF_FEC_MMFR_ST_01 | MCF_FEC_MMFR_OP_READ | MCF_FEC_MMFR_PA(phy_addr) | MCF_FEC_MMFR_RA(reg_addr) | MCF_FEC_MMFR_TA_10;
/* Poll for the MII interrupt (interrupt should be masked) */
for (timeout = 0; timeout < MII_TIMEOUT; timeout++)
{
if (MCF_FEC_EIR & MCF_FEC_EIR_MII)
{
break;
}
}
if(timeout == MII_TIMEOUT)
{
return 0;
}
/* Clear the MII interrupt bit */
MCF_FEC_EIR = MCF_FEC_EIR_MII;
/* Restore the EIMR */
MCF_FEC_EIMR = eimr;
*data = (uint16)(MCF_FEC_MMFR & 0x0000FFFF);
return 1;
}
/********************************************************************/
/*
* Generate the hash table settings for the given address
*
* Parameters:
* addr 48-bit (6 byte) Address to generate the hash for
*
* Return Value:
* The 6 most significant bits of the 32-bit CRC result
*/
static uint8 fec_hash_address( const uint8* addr )
{
uint32 crc;
uint8 byte;
int i, j;
crc = 0xFFFFFFFF;
for(i=0; i<6; ++i)
{
byte = addr[i];
for(j=0; j<8; ++j)
{
if((byte & 0x01)^(crc & 0x01))
{
crc >>= 1;
crc = crc ^ 0xEDB88320;
}
else
{
crc >>= 1;
}
byte >>= 1;
}
}
return (uint8)(crc >> 26);
}
/********************************************************************/
/*
* Set the Physical (Hardware) Address and the Individual Address
* Hash in the selected FEC
*
* Parameters:
* ch FEC channel
* pa Physical (Hardware) Address for the selected FEC
*/
static void fec_set_address( const uint8 *pa )
{
uint8 crc;
/*
* Set the Physical Address
*/
MCF_FEC_PALR = (uint32)((pa[0]<<24) | (pa[1]<<16) | (pa[2]<<8) | pa[3]);
MCF_FEC_PAUR = (uint32)((pa[4]<<24) | (pa[5]<<16));
/*
* Calculate and set the hash for given Physical Address
* in the Individual Address Hash registers
*/
crc = fec_hash_address(pa);
if(crc >= 32)
{
MCF_FEC_IAUR |= (uint32)(1 << (crc - 32));
}
else
{
MCF_FEC_IALR |= (uint32)(1 << crc);
}
}
/********************************************************************/
/*
* Enable interrupts on the selected FEC
*
*/
static void fec_irq_enable( void )
{
int fec_vbase;
#if INTC_LVL_FEC > configMAX_SYSCALL_INTERRUPT_PRIORITY
#error INTC_LVL_FEC must be less than or equal to configMAX_SYSCALL_INTERRUPT_PRIORITY
#endif
fec_vbase = 64 + netifFIRST_FEC_VECTOR;
/* Enable FEC interrupts to the ColdFire core
* Setup each ICR with a unique interrupt level combination */
fec_vbase -= 64;
/* FEC Rx Frame */
MCF_INTC0_ICR(fec_vbase+4) = MCF_INTC_ICR_IL(INTC_LVL_FEC);
/* FEC Rx Buffer */
MCF_INTC0_ICR(fec_vbase+5) = MCF_INTC_ICR_IL(INTC_LVL_FEC);
/* FEC FIFO Underrun */
MCF_INTC0_ICR(fec_vbase+2) = MCF_INTC_ICR_IL(INTC_LVL_FEC+1);
/* FEC Collision Retry Limit */
MCF_INTC0_ICR(fec_vbase+3) = MCF_INTC_ICR_IL(INTC_LVL_FEC+1);
/* FEC Late Collision */
MCF_INTC0_ICR(fec_vbase+7) = MCF_INTC_ICR_IL(INTC_LVL_FEC+1);
/* FEC Heartbeat Error */
MCF_INTC0_ICR(fec_vbase+8) = MCF_INTC_ICR_IL(INTC_LVL_FEC+1);
/* FEC Bus Error */
MCF_INTC0_ICR(fec_vbase+10) = MCF_INTC_ICR_IL(INTC_LVL_FEC+1);
/* FEC Babbling Transmit */
MCF_INTC0_ICR(fec_vbase+11) = MCF_INTC_ICR_IL(INTC_LVL_FEC+1);
/* FEC Babbling Receive */
MCF_INTC0_ICR(fec_vbase+12) = MCF_INTC_ICR_IL(INTC_LVL_FEC+1);
/* Enable the FEC interrupts in the mask register */
MCF_INTC0_IMRH &= ~( MCF_INTC_IMRH_INT_MASK33 | MCF_INTC_IMRH_INT_MASK34 | MCF_INTC_IMRH_INT_MASK35 );
MCF_INTC0_IMRL &= ~( MCF_INTC_IMRL_INT_MASK25 | MCF_INTC_IMRL_INT_MASK26 | MCF_INTC_IMRL_INT_MASK27 | MCF_INTC_IMRL_INT_MASK28 | MCF_INTC_IMRL_INT_MASK29 | MCF_INTC_IMRL_INT_MASK30 | MCF_INTC_IMRL_INT_MASK31 | MCF_INTC_IMRL_MASKALL );
/* Clear any pending FEC interrupt events */
MCF_FEC_EIR = MCF_FEC_EIR_CLEAR_ALL;
/* Unmask all FEC interrupts */
MCF_FEC_EIMR = MCF_FEC_EIMR_UNMASK_ALL;
}
/**
* In this function, the hardware should be initialized.
* Called from ethernetif_init().
*
* @param netif the already initialized lwip network interface structure
* for this ethernetif
*/
static void low_level_init( struct netif *netif )
{
unsigned short usData;
const unsigned char ucMACAddress[6] =
{
configMAC_0, configMAC_1,configMAC_2,configMAC_3,configMAC_4,configMAC_5
};
prvInitialiseFECBuffers();
vSemaphoreCreateBinary( xFecSemaphore );
for( usData = 0; usData < 6; usData++ )
{
netif->hwaddr[ usData ] = ucMACAddress[ usData ];
}
/* Set the Reset bit and clear the Enable bit */
MCF_FEC_ECR = MCF_FEC_ECR_RESET;
/* Wait at least 8 clock cycles */
for( usData = 0; usData < 10; usData++ )
{
asm( "NOP" );
}
/* Set MII speed to 2.5MHz. */
MCF_FEC_MSCR = MCF_FEC_MSCR_MII_SPEED( ( ( configCPU_CLOCK_HZ / 1000000 ) / 5 ) + 1 );
/*
* Make sure the external interface signals are enabled
*/
MCF_GPIO_PNQPAR = MCF_GPIO_PNQPAR_IRQ3_FEC_MDIO | MCF_GPIO_PNQPAR_IRQ5_FEC_MDC;
MCF_GPIO_PTIPAR = MCF_GPIO_PTIPAR_FEC_COL_FEC_COL
| MCF_GPIO_PTIPAR_FEC_CRS_FEC_CRS
| MCF_GPIO_PTIPAR_FEC_RXCLK_FEC_RXCLK
| MCF_GPIO_PTIPAR_FEC_RXD0_FEC_RXD0
| MCF_GPIO_PTIPAR_FEC_RXD1_FEC_RXD1
| MCF_GPIO_PTIPAR_FEC_RXD2_FEC_RXD2
| MCF_GPIO_PTIPAR_FEC_RXD3_FEC_RXD3
| MCF_GPIO_PTIPAR_FEC_RXDV_FEC_RXDV;
MCF_GPIO_PTJPAR = MCF_GPIO_PTJPAR_FEC_RXER_FEC_RXER
| MCF_GPIO_PTJPAR_FEC_TXCLK_FEC_TXCLK
| MCF_GPIO_PTJPAR_FEC_TXD0_FEC_TXD0
| MCF_GPIO_PTJPAR_FEC_TXD1_FEC_TXD1
| MCF_GPIO_PTJPAR_FEC_TXD2_FEC_TXD2
| MCF_GPIO_PTJPAR_FEC_TXD3_FEC_TXD3
| MCF_GPIO_PTJPAR_FEC_TXEN_FEC_TXEN
| MCF_GPIO_PTJPAR_FEC_TXER_FEC_TXER;
/* Can we talk to the PHY? */
do
{
vTaskDelay( netifLINK_DELAY );
usData = 0;
fec_mii_read( configPHY_ADDRESS, PHY_PHYIDR1, &usData );
} while( ( usData == 0xffff ) || ( usData == 0 ) );
/* Start auto negotiate. */
fec_mii_write( configPHY_ADDRESS, PHY_BMCR, ( PHY_BMCR_AN_RESTART | PHY_BMCR_AN_ENABLE ) );
/* Wait for auto negotiate to complete. */
do
{
vTaskDelay( netifLINK_DELAY );
fec_mii_read( configPHY_ADDRESS, PHY_BMSR, &usData );
} while( !( usData & PHY_BMSR_AN_COMPLETE ) );
/* When we get here we have a link - find out what has been negotiated. */
fec_mii_read( configPHY_ADDRESS, PHY_ANLPAR, &usData );
if( ( usData & PHY_ANLPAR_100BTX_FDX ) || ( usData & PHY_ANLPAR_100BTX ) )
{
/* Speed is 100. */
}
else
{
/* Speed is 10. */
}
if( ( usData & PHY_ANLPAR_100BTX_FDX ) || ( usData & PHY_ANLPAR_10BTX_FDX ) )
{
/* Full duplex. */
MCF_FEC_RCR &= (uint32)~MCF_FEC_RCR_DRT;
MCF_FEC_TCR |= MCF_FEC_TCR_FDEN;
}
else
{
MCF_FEC_RCR |= MCF_FEC_RCR_DRT;
MCF_FEC_TCR &= (uint32)~MCF_FEC_TCR_FDEN;
}
/* Clear the Individual and Group Address Hash registers */
MCF_FEC_IALR = 0;
MCF_FEC_IAUR = 0;
MCF_FEC_GALR = 0;
MCF_FEC_GAUR = 0;
/* Set the Physical Address for the selected FEC */
fec_set_address( ucMACAddress );
/* Set Rx Buffer Size */
MCF_FEC_EMRBR = (uint16)configFEC_BUFFER_SIZE;
/* Point to the start of the circular Rx buffer descriptor queue */
MCF_FEC_ERDSR = ( volatile unsigned long ) &( xFECRxDescriptors[ 0 ] );
/* Point to the start of the circular Tx buffer descriptor queue */
MCF_FEC_ETSDR = ( volatile unsigned long ) &( xFECTxDescriptors[ 0 ] );
/* Mask all FEC interrupts */
MCF_FEC_EIMR = MCF_FEC_EIMR_MASK_ALL;
/* Clear all FEC interrupt events */
MCF_FEC_EIR = MCF_FEC_EIR_CLEAR_ALL;
/* Initialize the Receive Control Register */
MCF_FEC_RCR = MCF_FEC_RCR_MAX_FL(ETH_MAX_FRM) | MCF_FEC_RCR_FCE;
MCF_FEC_RCR |= MCF_FEC_RCR_MII_MODE;
#if( configUSE_PROMISCUOUS_MODE == 1 )
{
MCF_FEC_RCR |= MCF_FEC_RCR_PROM;
}
#endif
/* Create the task that handles the EMAC. */
xTaskCreate( ethernetif_input, ( signed char * ) "ETH_INT", configETHERNET_INPUT_TASK_STACK_SIZE, (void *)netif, configETHERNET_INPUT_TASK_PRIORITY, &xEthIntTask );
fec_irq_enable();
MCF_FEC_ECR = MCF_FEC_ECR_ETHER_EN;
MCF_FEC_RDAR = MCF_FEC_RDAR_R_DES_ACTIVE;
}
/**
* This function should do the actual transmission of the packet. The packet is
* contained in the pbuf that is passed to the function. This pbuf
* might be chained.
*
* @param netif the lwip network interface structure for this ethernetif
* @param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
* @return ERR_OK if the packet could be sent
* an err_t value if the packet couldn't be sent
*
* @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
* strange results. You might consider waiting for space in the DMA queue
* to become availale since the stack doesn't retry to send a packet
* dropped because of memory failure (except for the TCP timers).
*/
static err_t low_level_output(struct netif *netif, struct pbuf *p)
{
struct pbuf *q;
u32_t l = 0;
unsigned char *pcTxData = NULL;
portBASE_TYPE i;
( void ) netif;
#if ETH_PAD_SIZE
pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
#endif
/* Get a DMA buffer into which we can write the data to send. */
for( i = 0; i < netifBUFFER_WAIT_ATTEMPTS; i++ )
{
if( xFECTxDescriptors[ uxNextTxBuffer ].status & TX_BD_R )
{
/* Wait for the buffer to become available. */
vTaskDelay( netifBUFFER_WAIT_DELAY );
}
else
{
pcTxData = xFECTxDescriptors[ uxNextTxBuffer ].data;
break;
}
}
if( pcTxData == NULL )
{
/* For break point only. */
portNOP();
return ERR_BUF;
}
else
{
for( q = p; q != NULL; q = q->next )
{
/* Send the data from the pbuf to the interface, one pbuf at a
time. The size of the data in each pbuf is kept in the ->len
variable. */
memcpy( &pcTxData[l], (u8_t*)q->payload, q->len );
l += q->len;
}
}
/* Setup the buffer descriptor for transmission */
xFECTxDescriptors[ uxNextTxBuffer ].length = l;//nbuf->length + ETH_HDR_LEN;
xFECTxDescriptors[ uxNextTxBuffer ].status |= (TX_BD_R | TX_BD_L);
/* Continue the Tx DMA task (in case it was waiting for a new TxBD) */
MCF_FEC_TDAR = MCF_FEC_TDAR_X_DES_ACTIVE;
uxNextTxBuffer++;
if( uxNextTxBuffer >= configNUM_FEC_TX_BUFFERS )
{
uxNextTxBuffer = 0;
}
#if ETH_PAD_SIZE
pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif
LINK_STATS_INC(link.xmit);
return ERR_OK;
}
/**
* Should allocate a pbuf and transfer the bytes of the incoming
* packet from the interface into the pbuf.
*
* @param netif the lwip network interface structure for this ethernetif
* @return a pbuf filled with the received packet (including MAC header)
* NULL on memory error
*/
static struct pbuf *low_level_input(struct netif *netif)
{
struct pbuf *p, *q;
u16_t len, l;
( void ) netif;
l = 0;
p = NULL;
/* Obtain the size of the packet and put it into the "len" variable. */
len = xFECRxDescriptors[ uxNextRxBuffer ].length;
if( ( len != 0 ) && ( ( xFECRxDescriptors[ uxNextRxBuffer ].status & RX_BD_E ) == 0 ) )
{
#if ETH_PAD_SIZE
len += ETH_PAD_SIZE; /* allow room for Ethernet padding */
#endif
/* We allocate a pbuf chain of pbufs from the pool. */
p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
if (p != NULL)
{
#if ETH_PAD_SIZE
pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */
#endif
/* We iterate over the pbuf chain until we have read the entire
* packet into the pbuf. */
for(q = p; q != NULL; q = q->next)
{
/* Read enough bytes to fill this pbuf in the chain. The
* available data in the pbuf is given by the q->len
* variable. */
memcpy((u8_t*)q->payload, &(xFECRxDescriptors[ uxNextRxBuffer ].data[l]), q->len);
l = l + q->len;
}
#if ETH_PAD_SIZE
pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif
LINK_STATS_INC(link.recv);
}
else
{
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
} /* End else */
/* Free the descriptor. */
xFECRxDescriptors[ uxNextRxBuffer ].status |= RX_BD_E;
MCF_FEC_RDAR = MCF_FEC_RDAR_R_DES_ACTIVE;
uxNextRxBuffer++;
if( uxNextRxBuffer >= configNUM_FEC_RX_BUFFERS )
{
uxNextRxBuffer = 0;
}
} /* End if */
return p;
}
/**
* This function should be called when a packet is ready to be read
* from the interface. It uses the function low_level_input() that
* should handle the actual reception of bytes from the network
* interface.Then the type of the received packet is determined and
* the appropriate input function is called.
*
* @param netif the lwip network interface structure for this ethernetif
*/
static void ethernetif_input( void *pParams )
{
struct netif *netif;
struct ethernetif *ethernetif;
struct eth_hdr *ethhdr;
struct pbuf *p;
netif = (struct netif*) pParams;
ethernetif = netif->state;
for( ;; )
{
do
{
/* move received packet into a new pbuf */
p = low_level_input( netif );
if( p == NULL )
{
/* No packet could be read. Wait a for an interrupt to tell us
there is more data available. */
xSemaphoreTake( xFecSemaphore, netifBLOCK_TIME_WAITING_FOR_INPUT );
}
} while( p == NULL );
/* points to packet payload, which starts with an Ethernet header */
ethhdr = p->payload;
switch (htons(ethhdr->type)) {
/* IP or ARP packet? */
case ETHTYPE_IP:
pbuf_header( p, (s16_t)-sizeof(struct eth_hdr) );
/* full packet send to tcpip_thread to process */
if (netif->input(p, netif) != ERR_OK)
{
LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n"));
pbuf_free(p);
p = NULL;
}
break;
case ETHTYPE_ARP:
#if ETHARP_TRUST_IP_MAC
etharp_ip_input(netif, p);
#endif
etharp_arp_input(netif, ethernetif->ethaddr, p);
break;
default:
pbuf_free(p);
p = NULL;
break;
}
}
}
/**
* Should be called at the beginning of the program to set up the
* network interface. It calls the function low_level_init() to do the
* actual setup of the hardware.
*
* This function should be passed as a parameter to netif_add().
*
* @param netif the lwip network interface structure for this ethernetif
* @return ERR_OK if the loopif is initialized
* ERR_MEM if private data couldn't be allocated
* any other err_t on error
*/
err_t ethernetif_init(struct netif *netif)
{
struct ethernetif *ethernetif;
LWIP_ASSERT("netif != NULL", (netif != NULL));
ethernetif = mem_malloc(sizeof(struct ethernetif));
if (ethernetif == NULL)
{
LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_init: out of memory\n"));
return ERR_MEM;
}
#if LWIP_NETIF_HOSTNAME
/* Initialize interface hostname */
netif->hostname = "lwip";
#endif /* LWIP_NETIF_HOSTNAME */
/*
* Initialize the snmp variables and counters inside the struct netif.
* The last argument should be replaced with your link speed, in units
* of bits per second.
*/
NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 100);
netif->state = ethernetif;
netif->name[0] = IFNAME0;
netif->name[1] = IFNAME1;
/* We directly use etharp_output() here to save a function call.
* You can instead declare your own function an call etharp_output()
* from it if you have to do some checks before sending (e.g. if link
* is available...)
*/
netif->output = etharp_output;
netif->linkoutput = low_level_output;
ethernetif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]);
low_level_init(netif);
return ERR_OK;
}
/*-----------------------------------------------------------*/
static void prvInitialiseFECBuffers( void )
{
unsigned portBASE_TYPE ux;
unsigned char *pcBufPointer;
pcBufPointer = &( xFECTxDescriptors_unaligned[ 0 ] );
while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 )
{
pcBufPointer++;
}
xFECTxDescriptors = ( FECBD * ) pcBufPointer;
pcBufPointer = &( xFECRxDescriptors_unaligned[ 0 ] );
while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 )
{
pcBufPointer++;
}
xFECRxDescriptors = ( FECBD * ) pcBufPointer;
/* Setup the buffers and descriptors. */
pcBufPointer = &( ucFECTxBuffers[ 0 ] );
while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 )
{
pcBufPointer++;
}
for( ux = 0; ux < configNUM_FEC_TX_BUFFERS; ux++ )
{
xFECTxDescriptors[ ux ].status = TX_BD_TC;
xFECTxDescriptors[ ux ].data = pcBufPointer;
pcBufPointer += configFEC_BUFFER_SIZE;
xFECTxDescriptors[ ux ].length = 0;
}
pcBufPointer = &( ucFECRxBuffers[ 0 ] );
while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 )
{
pcBufPointer++;
}
for( ux = 0; ux < configNUM_FEC_RX_BUFFERS; ux++ )
{
xFECRxDescriptors[ ux ].status = RX_BD_E;
xFECRxDescriptors[ ux ].length = configFEC_BUFFER_SIZE;
xFECRxDescriptors[ ux ].data = pcBufPointer;
pcBufPointer += configFEC_BUFFER_SIZE;
}
/* Set the wrap bit in the last descriptors to form a ring. */
xFECTxDescriptors[ configNUM_FEC_TX_BUFFERS - 1 ].status |= TX_BD_W;
xFECRxDescriptors[ configNUM_FEC_RX_BUFFERS - 1 ].status |= RX_BD_W;
uxNextRxBuffer = 0;
uxNextTxBuffer = 0;
}
/*-----------------------------------------------------------*/
__declspec(interrupt:0) void vFECISRHandler( void )
{
unsigned long ulEvent;
portBASE_TYPE xHighPriorityTaskWoken = pdFALSE;
ulEvent = MCF_FEC_EIR & MCF_FEC_EIMR;
MCF_FEC_EIR = ulEvent;
if( ( ulEvent & MCF_FEC_EIR_RXB ) || ( ulEvent & MCF_FEC_EIR_RXF ) )
{
/* A packet has been received. Wake the handler task. */
xSemaphoreGiveFromISR( xFecSemaphore, &xHighPriorityTaskWoken );
}
if (ulEvent & ( MCF_FEC_EIR_UN | MCF_FEC_EIR_RL | MCF_FEC_EIR_LC | MCF_FEC_EIR_EBERR | MCF_FEC_EIR_BABT | MCF_FEC_EIR_BABR | MCF_FEC_EIR_HBERR ) )
{
/* Sledge hammer error handling. */
prvInitialiseFECBuffers();
MCF_FEC_RDAR = MCF_FEC_RDAR_R_DES_ACTIVE;
}
portEND_SWITCHING_ISR( xHighPriorityTaskWoken );
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/MCF5225x_ethernetif.c | C | oos | 25,671 |
/*
* File: fecbd.h
* Purpose:
*
* Purpose: Provide a simple buffer management driver
*/
#ifndef _FECBD_H_
#define _FECBD_H_
/********************************************************************/
#define Rx 1
#define Tx 0
/*
* Buffer sizes in bytes
*/
#ifndef RX_BUF_SZ
#define RX_BUF_SZ 1520 //2048
#endif
#ifndef TX_BUF_SZ
#define TX_BUF_SZ 1520
#endif
/*
* Buffer Descriptor Format
*/
#pragma options align= packed
typedef struct
{
uint16 status; /* control and status */
uint16 length; /* transfer length */
uint8 *data; /* buffer address */
} FECBD;
/*
* Bit level definitions for status field of buffer descriptors
*/
#define TX_BD_R 0x8000
#define TX_BD_TO1 0x4000
#define TX_BD_W 0x2000
#define TX_BD_TO2 0x1000
#define TX_BD_INTERRUPT 0x1000 /* MCF547x/8x Only */
#define TX_BD_L 0x0800
#define TX_BD_TC 0x0400
#define TX_BD_DEF 0x0200 /* MCF5272 Only */
#define TX_BD_ABC 0x0200
#define TX_BD_HB 0x0100 /* MCF5272 Only */
#define TX_BD_LC 0x0080 /* MCF5272 Only */
#define TX_BD_RL 0x0040 /* MCF5272 Only */
#define TX_BD_UN 0x0002 /* MCF5272 Only */
#define TX_BD_CSL 0x0001 /* MCF5272 Only */
#define RX_BD_E 0x8000
#define RX_BD_R01 0x4000
#define RX_BD_W 0x2000
#define RX_BD_R02 0x1000
#define RX_BD_INTERRUPT 0x1000 /* MCF547x/8x Only */
#define RX_BD_L 0x0800
#define RX_BD_M 0x0100
#define RX_BD_BC 0x0080
#define RX_BD_MC 0x0040
#define RX_BD_LG 0x0020
#define RX_BD_NO 0x0010
#define RX_BD_CR 0x0004
#define RX_BD_OV 0x0002
#define RX_BD_TR 0x0001
#define RX_BD_ERROR (RX_BD_NO | RX_BD_CR | RX_BD_OV | RX_BD_TR)
/*
* The following defines are provided by the MCF547x/8x
* DMA API. These are shown here to show their correlation
* to the other FEC buffer descriptor status bits
*
* #define MCD_FEC_BUF_READY 0x8000
* #define MCD_FEC_WRAP 0x2000
* #define MCD_FEC_INTERRUPT 0x1000
* #define MCD_FEC_END_FRAME 0x0800
*/
/*
* Functions provided in fec_bd.c
*/
int fecbd_init(int, int, int);
void fecbd_flush(int);
void fecbd_dump( void );
uint32 fecbd_get_start(int, int);
FECBD* fecbd_rx_alloc(int);
FECBD* fecbd_tx_alloc(int);
FECBD* fecbd_tx_free(int);
/*
* Error codes
*/
#define ERR_MALLOC (-1)
#define ERR_NBUFALLOC (-2)
/*******************************************************************/
#endif /* _FECBD_H_ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/fecbd.h | C | oos | 2,638 |
/*!
* \file eth.h
* \brief Definitinos for Ethernet Frames
* \version $Revision: 1.2 $
* \author Michael Norman
*/
#ifndef _ETH_H
#define _ETH_H
/*******************************************************************/
/* Ethernet standard lengths in bytes*/
#define ETH_ADDR_LEN (6)
#define ETH_TYPE_LEN (2)
#define ETH_CRC_LEN (4)
#define ETH_MAX_DATA (1500)
#define ETH_MIN_DATA (46)
#define ETH_HDR_LEN (ETH_ADDR_LEN * 2 + ETH_TYPE_LEN)
/* Defined Ethernet Frame Types */
#define ETH_FRM_IP (0x0800)
#define ETH_FRM_ARP (0x0806)
#define ETH_FRM_RARP (0x8035)
#define ETH_FRM_TEST (0xA5A5)
/* Maximum and Minimum Ethernet Frame Sizes */
#define ETH_MAX_FRM (ETH_HDR_LEN + ETH_MAX_DATA + ETH_CRC_LEN)
#define ETH_MIN_FRM (ETH_HDR_LEN + ETH_MIN_DATA + ETH_CRC_LEN)
#define ETH_MTU (ETH_HDR_LEN + ETH_MAX_DATA)
/* Ethernet Addresses */
typedef uint8 ETH_ADDR[ETH_ADDR_LEN];
/* 16-bit Ethernet Frame Type, ie. Protocol */
typedef uint16 ETH_FRM_TYPE;
/* Ethernet Frame Header definition */
typedef struct
{
ETH_ADDR dest;
ETH_ADDR src;
ETH_FRM_TYPE type;
} ETH_HDR;
/* Ethernet Frame definition */
typedef struct
{
ETH_HDR head;
uint8* data;
} ETH_FRAME;
/*******************************************************************/
#endif /* _ETH_H */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/eth.h | C | oos | 1,399 |
/*
* File: fec.h
* Purpose: Driver for the Fast Ethernet Controller (FEC)
*
* Notes:
*/
#ifndef _FEC_H_
#define _FEC_H_
#include "eth.h"
#include "fecbd.h"
#include "mii.h"
#include "eth_phy.h"
/********************************************************************/
/* External Interface Modes */
#define FEC_MODE_7WIRE 0 /* Old 7-wire (AMD) mode */
#define FEC_MODE_MII 1 /* Media Independent Interface */
#define FEC_MODE_RMII 2 /* Reduced MII */
#define FEC_MODE_LOOPBACK 3 /* Internal Loopback */
#define INTC_LVL_FEC 3
/*
* FEC Configuration Parameters
*/
typedef struct
{
uint8 ch; /* FEC channel */
uint8 mode; /* Transceiver mode */
MII_SPEED speed; /* Ethernet Speed */
MII_DUPLEX duplex; /* Ethernet Duplex */
uint8 prom; /* Promiscuous Mode? */
uint8 mac[6]; /* Ethernet Address */
uint8 phyaddr; /* PHY address */
uint8 initphy; /* Init PHY? */
int nrxbd; /* Number of RxBDs */
int ntxbd; /* Number of TxBDs */
} FEC_CONFIG;
#define YES 1
#define NO 0
/*
* FEC Event Log
*/
typedef struct {
int errors; /* total count of errors */
int hberr; /* heartbeat error */
int babr; /* babbling receiver */
int babt; /* babbling transmitter */
int gra; /* graceful stop complete */
int txf; /* transmit frame */
int txb; /* transmit buffer */
int rxf; /* receive frame */
int rxb; /* received buffer */
int mii; /* MII */
int eberr; /* FEC/DMA fatal bus error */
int lc; /* late collision */
int rl; /* collision retry limit */
int un; /* Tx FIFO underflow */
int rfsw_inv; /* Invalid bit in RFSW */
int rfsw_l; /* RFSW Last in Frame */
int rfsw_m; /* RFSW Miss */
int rfsw_bc; /* RFSW Broadcast */
int rfsw_mc; /* RFSW Multicast */
int rfsw_lg; /* RFSW Length Violation */
int rfsw_no; /* RFSW Non-octet */
int rfsw_cr; /* RFSW Bad CRC */
int rfsw_ov; /* RFSW Overflow */
int rfsw_tr; /* RFSW Truncated */
} FEC_EVENT_LOG;
#if 0
int
fec_mii_write( int, int, int);
int
fec_mii_read(int, int, uint16*);
void
fec_mii_init(int, int);
void
fec_mib_init(void);
void
fec_mib_dump(void);
void
fec_log_init(int);
void
fec_log_dump(int);
void
fec_reg_dump(int);
void
fec_duplex (int, MII_DUPLEX);
void
fec_rmii_speed (int, MII_SPEED);
uint8
fec_hash_address(const uint8*);
void
fec_set_address (const uint8*);
void
fec_reset ( void );
void
fec_init (int, const uint8*);
void
fec_rx_start(int, uint8*, int);
void
fec_rx_continue( void );
void
fec_rx_handler(void);
void
fec0_rx_handler(void);
void
fec1_rx_handler(void);
void
fec_tx_continue( void );
void
fec_tx_stop (int);
void
fec_tx_handler(NIF*, int);
int
fec_send (uint8*, uint8*, uint16 , NBUF*);
int
fec0_send(uint8*, uint8*, uint16 , NBUF*);
int
fec1_send(uint8*, uint8*, uint16 , NBUF*);
void
fec_irq_enable( void );
void
fec_irq_disable(int);
int
fec_eth_start(FEC_CONFIG*, int);
void
fec_eth_stop(int);
#endif
/********************************************************************/
#endif /* _FEC_H_ */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP_130/contrib/port/FreeRTOS/ColdFire/fec.h | C | oos | 3,736 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
/* This is the part of the API that is linked with
the application */
#include "lwip/opt.h"
#include "lwip/api.h"
#include "lwip/api_msg.h"
#include "lwip/memp.h"
struct
netbuf *netbuf_new(void)
{
struct netbuf *buf;
buf = memp_malloc(MEMP_NETBUF);
if (buf != NULL) {
buf->p = NULL;
buf->ptr = NULL;
return buf;
} else {
return NULL;
}
}
void
netbuf_delete(struct netbuf *buf)
{
if (buf != NULL) {
if (buf->p != NULL) {
pbuf_free(buf->p);
buf->p = buf->ptr = NULL;
}
memp_free(MEMP_NETBUF, buf);
}
}
void *
netbuf_alloc(struct netbuf *buf, u16_t size)
{
/* Deallocate any previously allocated memory. */
if (buf->p != NULL) {
pbuf_free(buf->p);
}
buf->p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM);
if (buf->p == NULL) {
return NULL;
}
buf->ptr = buf->p;
return buf->p->payload;
}
void
netbuf_free(struct netbuf *buf)
{
if (buf->p != NULL) {
pbuf_free(buf->p);
}
buf->p = buf->ptr = NULL;
}
void
netbuf_ref(struct netbuf *buf, void *dataptr, u16_t size)
{
if (buf->p != NULL) {
pbuf_free(buf->p);
}
buf->p = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF);
buf->p->payload = dataptr;
buf->p->len = buf->p->tot_len = size;
buf->ptr = buf->p;
}
void
netbuf_chain(struct netbuf *head, struct netbuf *tail)
{
pbuf_chain(head->p, tail->p);
head->ptr = head->p;
memp_free(MEMP_NETBUF, tail);
}
u16_t
netbuf_len(struct netbuf *buf)
{
return buf->p->tot_len;
}
err_t
netbuf_data(struct netbuf *buf, void **dataptr, u16_t *len)
{
if (buf->ptr == NULL) {
return ERR_BUF;
}
*dataptr = buf->ptr->payload;
*len = buf->ptr->len;
return ERR_OK;
}
s8_t
netbuf_next(struct netbuf *buf)
{
if (buf->ptr->next == NULL) {
return -1;
}
buf->ptr = buf->ptr->next;
if (buf->ptr->next == NULL) {
return 1;
}
return 0;
}
void
netbuf_first(struct netbuf *buf)
{
buf->ptr = buf->p;
}
void
netbuf_copy_partial(struct netbuf *buf, void *dataptr, u16_t len, u16_t offset)
{
struct pbuf *p;
u16_t i, left;
left = 0;
if(buf == NULL || dataptr == NULL) {
return;
}
/* This implementation is bad. It should use bcopy
instead. */
for(p = buf->p; left < len && p != NULL; p = p->next) {
if (offset != 0 && offset >= p->len) {
offset -= p->len;
} else {
for(i = offset; i < p->len; ++i) {
((u8_t *)dataptr)[left] = ((u8_t *)p->payload)[i];
if (++left >= len) {
return;
}
}
offset = 0;
}
}
}
void
netbuf_copy(struct netbuf *buf, void *dataptr, u16_t len)
{
netbuf_copy_partial(buf, dataptr, len, 0);
}
struct ip_addr *
netbuf_fromaddr(struct netbuf *buf)
{
return buf->fromaddr;
}
u16_t
netbuf_fromport(struct netbuf *buf)
{
return buf->fromport;
}
struct
netconn *netconn_new_with_proto_and_callback(enum netconn_type t, u16_t proto,
void (*callback)(struct netconn *, enum netconn_evt, u16_t len))
{
struct netconn *conn;
struct api_msg *msg;
conn = memp_malloc(MEMP_NETCONN);
if (conn == NULL) {
return NULL;
}
conn->err = ERR_OK;
conn->type = t;
conn->pcb.tcp = NULL;
if ((conn->mbox = sys_mbox_new()) == SYS_MBOX_NULL) {
memp_free(MEMP_NETCONN, conn);
return NULL;
}
conn->recvmbox = SYS_MBOX_NULL;
conn->acceptmbox = SYS_MBOX_NULL;
conn->sem = sys_sem_new(0);
if (conn->sem == SYS_SEM_NULL) {
memp_free(MEMP_NETCONN, conn);
return NULL;
}
conn->state = NETCONN_NONE;
conn->socket = 0;
conn->callback = callback;
conn->recv_avail = 0;
if((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
memp_free(MEMP_NETCONN, conn);
return NULL;
}
msg->type = API_MSG_NEWCONN;
msg->msg.msg.bc.port = proto; /* misusing the port field */
msg->msg.conn = conn;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
memp_free(MEMP_API_MSG, msg);
if ( conn->err != ERR_OK ) {
memp_free(MEMP_NETCONN, conn);
return NULL;
}
return conn;
}
struct
netconn *netconn_new(enum netconn_type t)
{
return netconn_new_with_proto_and_callback(t,0,NULL);
}
struct
netconn *netconn_new_with_callback(enum netconn_type t,
void (*callback)(struct netconn *, enum netconn_evt, u16_t len))
{
return netconn_new_with_proto_and_callback(t,0,callback);
}
err_t
netconn_delete(struct netconn *conn)
{
struct api_msg *msg;
void *mem;
if (conn == NULL) {
return ERR_OK;
}
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
return ERR_MEM;
}
msg->type = API_MSG_DELCONN;
msg->msg.conn = conn;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
memp_free(MEMP_API_MSG, msg);
/* Drain the recvmbox. */
if (conn->recvmbox != SYS_MBOX_NULL) {
while (sys_arch_mbox_fetch(conn->recvmbox, &mem, 1) != SYS_ARCH_TIMEOUT) {
if (conn->type == NETCONN_TCP) {
if(mem != NULL)
pbuf_free((struct pbuf *)mem);
} else {
netbuf_delete((struct netbuf *)mem);
}
}
sys_mbox_free(conn->recvmbox);
conn->recvmbox = SYS_MBOX_NULL;
}
/* Drain the acceptmbox. */
if (conn->acceptmbox != SYS_MBOX_NULL) {
while (sys_arch_mbox_fetch(conn->acceptmbox, &mem, 1) != SYS_ARCH_TIMEOUT) {
netconn_delete((struct netconn *)mem);
}
sys_mbox_free(conn->acceptmbox);
conn->acceptmbox = SYS_MBOX_NULL;
}
sys_mbox_free(conn->mbox);
conn->mbox = SYS_MBOX_NULL;
if (conn->sem != SYS_SEM_NULL) {
sys_sem_free(conn->sem);
}
/* conn->sem = SYS_SEM_NULL;*/
memp_free(MEMP_NETCONN, conn);
return ERR_OK;
}
enum netconn_type
netconn_type(struct netconn *conn)
{
return conn->type;
}
err_t
netconn_peer(struct netconn *conn, struct ip_addr *addr,
u16_t *port)
{
switch (conn->type) {
case NETCONN_RAW:
/* return an error as connecting is only a helper for upper layers */
return ERR_CONN;
case NETCONN_UDPLITE:
case NETCONN_UDPNOCHKSUM:
case NETCONN_UDP:
if (conn->pcb.udp == NULL ||
((conn->pcb.udp->flags & UDP_FLAGS_CONNECTED) == 0))
return ERR_CONN;
*addr = (conn->pcb.udp->remote_ip);
*port = conn->pcb.udp->remote_port;
break;
case NETCONN_TCP:
if (conn->pcb.tcp == NULL)
return ERR_CONN;
*addr = (conn->pcb.tcp->remote_ip);
*port = conn->pcb.tcp->remote_port;
break;
}
return (conn->err = ERR_OK);
}
err_t
netconn_addr(struct netconn *conn, struct ip_addr **addr,
u16_t *port)
{
switch (conn->type) {
case NETCONN_RAW:
*addr = &(conn->pcb.raw->local_ip);
*port = conn->pcb.raw->protocol;
break;
case NETCONN_UDPLITE:
case NETCONN_UDPNOCHKSUM:
case NETCONN_UDP:
*addr = &(conn->pcb.udp->local_ip);
*port = conn->pcb.udp->local_port;
break;
case NETCONN_TCP:
*addr = &(conn->pcb.tcp->local_ip);
*port = conn->pcb.tcp->local_port;
break;
}
return (conn->err = ERR_OK);
}
err_t
netconn_bind(struct netconn *conn, struct ip_addr *addr,
u16_t port)
{
struct api_msg *msg;
if (conn == NULL) {
return ERR_VAL;
}
if (conn->type != NETCONN_TCP &&
conn->recvmbox == SYS_MBOX_NULL) {
if ((conn->recvmbox = sys_mbox_new()) == SYS_MBOX_NULL) {
return ERR_MEM;
}
}
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
return (conn->err = ERR_MEM);
}
msg->type = API_MSG_BIND;
msg->msg.conn = conn;
msg->msg.msg.bc.ipaddr = addr;
msg->msg.msg.bc.port = port;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
memp_free(MEMP_API_MSG, msg);
return conn->err;
}
err_t
netconn_connect(struct netconn *conn, struct ip_addr *addr,
u16_t port)
{
struct api_msg *msg;
if (conn == NULL) {
return ERR_VAL;
}
if (conn->recvmbox == SYS_MBOX_NULL) {
if ((conn->recvmbox = sys_mbox_new()) == SYS_MBOX_NULL) {
return ERR_MEM;
}
}
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
return ERR_MEM;
}
msg->type = API_MSG_CONNECT;
msg->msg.conn = conn;
msg->msg.msg.bc.ipaddr = addr;
msg->msg.msg.bc.port = port;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
memp_free(MEMP_API_MSG, msg);
return conn->err;
}
err_t
netconn_disconnect(struct netconn *conn)
{
struct api_msg *msg;
if (conn == NULL) {
return ERR_VAL;
}
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
return ERR_MEM;
}
msg->type = API_MSG_DISCONNECT;
msg->msg.conn = conn;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
memp_free(MEMP_API_MSG, msg);
return conn->err;
}
err_t
netconn_listen(struct netconn *conn)
{
struct api_msg *msg;
if (conn == NULL) {
return ERR_VAL;
}
if (conn->acceptmbox == SYS_MBOX_NULL) {
conn->acceptmbox = sys_mbox_new();
if (conn->acceptmbox == SYS_MBOX_NULL) {
return ERR_MEM;
}
}
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
return (conn->err = ERR_MEM);
}
msg->type = API_MSG_LISTEN;
msg->msg.conn = conn;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
memp_free(MEMP_API_MSG, msg);
return conn->err;
}
struct netconn *
netconn_accept(struct netconn *conn)
{
struct netconn *newconn;
if (conn == NULL) {
return NULL;
}
sys_mbox_fetch(conn->acceptmbox, (void *)&newconn);
/* Register event with callback */
if (conn->callback)
(*conn->callback)(conn, NETCONN_EVT_RCVMINUS, 0);
return newconn;
}
struct netbuf *
netconn_recv(struct netconn *conn)
{
struct api_msg *msg;
struct netbuf *buf;
struct pbuf *p;
u16_t len;
if (conn == NULL) {
return NULL;
}
if (conn->recvmbox == SYS_MBOX_NULL) {
conn->err = ERR_CONN;
return NULL;
}
if (conn->err != ERR_OK) {
return NULL;
}
if (conn->type == NETCONN_TCP) {
if (conn->pcb.tcp->state == LISTEN) {
conn->err = ERR_CONN;
return NULL;
}
buf = memp_malloc(MEMP_NETBUF);
if (buf == NULL) {
conn->err = ERR_MEM;
return NULL;
}
sys_mbox_fetch(conn->recvmbox, (void *)&p);
if (p != NULL)
{
len = p->tot_len;
conn->recv_avail -= len;
}
else
len = 0;
/* Register event with callback */
if (conn->callback)
(*conn->callback)(conn, NETCONN_EVT_RCVMINUS, len);
/* If we are closed, we indicate that we no longer wish to receive
data by setting conn->recvmbox to SYS_MBOX_NULL. */
if (p == NULL) {
memp_free(MEMP_NETBUF, buf);
sys_mbox_free(conn->recvmbox);
conn->recvmbox = SYS_MBOX_NULL;
return NULL;
}
buf->p = p;
buf->ptr = p;
buf->fromport = 0;
buf->fromaddr = NULL;
/* Let the stack know that we have taken the data. */
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
conn->err = ERR_MEM;
return buf;
}
msg->type = API_MSG_RECV;
msg->msg.conn = conn;
if (buf != NULL) {
msg->msg.msg.len = buf->p->tot_len;
} else {
msg->msg.msg.len = 1;
}
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
memp_free(MEMP_API_MSG, msg);
} else {
sys_mbox_fetch(conn->recvmbox, (void *)&buf);
conn->recv_avail -= buf->p->tot_len;
/* Register event with callback */
if (conn->callback)
(*conn->callback)(conn, NETCONN_EVT_RCVMINUS, buf->p->tot_len);
}
LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_recv: received %p (err %d)\n", (void *)buf, conn->err));
return buf;
}
err_t
netconn_send(struct netconn *conn, struct netbuf *buf)
{
struct api_msg *msg;
if (conn == NULL) {
return ERR_VAL;
}
if (conn->err != ERR_OK) {
return conn->err;
}
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
return (conn->err = ERR_MEM);
}
LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_send: sending %d bytes\n", buf->p->tot_len));
msg->type = API_MSG_SEND;
msg->msg.conn = conn;
msg->msg.msg.p = buf->p;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
memp_free(MEMP_API_MSG, msg);
return conn->err;
}
err_t
netconn_write(struct netconn *conn, void *dataptr, u16_t size, u8_t copy)
{
struct api_msg *msg;
u16_t len;
if (conn == NULL) {
return ERR_VAL;
}
if (conn->err != ERR_OK) {
return conn->err;
}
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
return (conn->err = ERR_MEM);
}
msg->type = API_MSG_WRITE;
msg->msg.conn = conn;
conn->state = NETCONN_WRITE;
while (conn->err == ERR_OK && size > 0) {
msg->msg.msg.w.dataptr = dataptr;
msg->msg.msg.w.copy = copy;
if (conn->type == NETCONN_TCP) {
if (tcp_sndbuf(conn->pcb.tcp) == 0) {
sys_sem_wait(conn->sem);
if (conn->err != ERR_OK) {
goto ret;
}
}
if (size > tcp_sndbuf(conn->pcb.tcp)) {
/* We cannot send more than one send buffer's worth of data at a
time. */
len = tcp_sndbuf(conn->pcb.tcp);
} else {
len = size;
}
} else {
len = size;
}
LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_write: writing %d bytes (%d)\n", len, copy));
msg->msg.msg.w.len = len;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
if (conn->err == ERR_OK) {
dataptr = (void *)((u8_t *)dataptr + len);
size -= len;
} else if (conn->err == ERR_MEM) {
conn->err = ERR_OK;
sys_sem_wait(conn->sem);
} else {
goto ret;
}
}
ret:
memp_free(MEMP_API_MSG, msg);
conn->state = NETCONN_NONE;
return conn->err;
}
err_t
netconn_close(struct netconn *conn)
{
struct api_msg *msg;
if (conn == NULL) {
return ERR_VAL;
}
if ((msg = memp_malloc(MEMP_API_MSG)) == NULL) {
return (conn->err = ERR_MEM);
}
conn->state = NETCONN_CLOSE;
again:
msg->type = API_MSG_CLOSE;
msg->msg.conn = conn;
api_msg_post(msg);
sys_mbox_fetch(conn->mbox, NULL);
if (conn->err == ERR_MEM &&
conn->sem != SYS_SEM_NULL) {
sys_sem_wait(conn->sem);
goto again;
}
conn->state = NETCONN_NONE;
memp_free(MEMP_API_MSG, msg);
return conn->err;
}
err_t
netconn_err(struct netconn *conn)
{
return conn->err;
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/api/api_lib.c | C | oos | 16,334 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include "lwip/opt.h"
#include "lwip/sys.h"
#include "lwip/memp.h"
#include "lwip/pbuf.h"
#include "lwip/ip.h"
#include "lwip/ip_frag.h"
#include "lwip/udp.h"
#include "lwip/tcp.h"
#include "lwip/tcpip.h"
static void (* tcpip_init_done)(void *arg) = NULL;
static void *tcpip_init_done_arg;
static sys_mbox_t mbox;
#if LWIP_TCP
static int tcpip_tcp_timer_active = 0;
static void
tcpip_tcp_timer(void *arg)
{
(void)arg;
/* call TCP timer handler */
tcp_tmr();
/* timer still needed? */
if (tcp_active_pcbs || tcp_tw_pcbs) {
/* restart timer */
sys_timeout(TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
} else {
/* disable timer */
tcpip_tcp_timer_active = 0;
}
}
#if !NO_SYS
void
tcp_timer_needed(void)
{
/* timer is off but needed again? */
if (!tcpip_tcp_timer_active && (tcp_active_pcbs || tcp_tw_pcbs)) {
/* enable and start timer */
tcpip_tcp_timer_active = 1;
sys_timeout(TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
}
}
#endif /* !NO_SYS */
#endif /* LWIP_TCP */
#if IP_REASSEMBLY
static void
ip_timer(void *data)
{
LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip: ip_reass_tmr()\n"));
ip_reass_tmr();
sys_timeout(1000, ip_timer, NULL);
}
#endif
static void
tcpip_thread(void *arg)
{
struct tcpip_msg *msg;
(void)arg;
ip_init();
#if LWIP_UDP
udp_init();
#endif
#if LWIP_TCP
tcp_init();
#endif
#if IP_REASSEMBLY
sys_timeout(1000, ip_timer, NULL);
#endif
if (tcpip_init_done != NULL) {
tcpip_init_done(tcpip_init_done_arg);
}
while (1) { /* MAIN Loop */
sys_mbox_fetch(mbox, (void *)&msg);
switch (msg->type) {
case TCPIP_MSG_API:
LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: API message %p\n", (void *)msg));
api_msg_input(msg->msg.apimsg);
break;
case TCPIP_MSG_INPUT:
LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: IP packet %p\n", (void *)msg));
ip_input(msg->msg.inp.p, msg->msg.inp.netif);
break;
case TCPIP_MSG_CALLBACK:
LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: CALLBACK %p\n", (void *)msg));
msg->msg.cb.f(msg->msg.cb.ctx);
break;
default:
break;
}
memp_free(MEMP_TCPIP_MSG, msg);
}
}
err_t
tcpip_input(struct pbuf *p, struct netif *inp)
{
struct tcpip_msg *msg;
msg = memp_malloc(MEMP_TCPIP_MSG);
if (msg == NULL) {
pbuf_free(p);
return ERR_MEM;
}
msg->type = TCPIP_MSG_INPUT;
msg->msg.inp.p = p;
msg->msg.inp.netif = inp;
sys_mbox_post(mbox, msg);
return ERR_OK;
}
err_t
tcpip_callback(void (*f)(void *ctx), void *ctx)
{
struct tcpip_msg *msg;
msg = memp_malloc(MEMP_TCPIP_MSG);
if (msg == NULL) {
return ERR_MEM;
}
msg->type = TCPIP_MSG_CALLBACK;
msg->msg.cb.f = f;
msg->msg.cb.ctx = ctx;
sys_mbox_post(mbox, msg);
return ERR_OK;
}
void
tcpip_apimsg(struct api_msg *apimsg)
{
struct tcpip_msg *msg;
msg = memp_malloc(MEMP_TCPIP_MSG);
if (msg == NULL) {
memp_free(MEMP_API_MSG, apimsg);
return;
}
msg->type = TCPIP_MSG_API;
msg->msg.apimsg = apimsg;
sys_mbox_post(mbox, msg);
}
void
tcpip_init(void (* initfunc)(void *), void *arg)
{
tcpip_init_done = initfunc;
tcpip_init_done_arg = arg;
mbox = sys_mbox_new();
sys_thread_new(tcpip_thread, NULL, TCPIP_THREAD_PRIO);
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/api/tcpip.c | C | oos | 5,074 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
* Improved by Marc Boucher <marc@mbsi.ca> and David Haas <dhaas@alum.rpi.edu>
*
*/
#include <string.h>
#include <errno.h>
#include "lwip/opt.h"
#include "lwip/api.h"
#include "lwip/arch.h"
#include "lwip/sys.h"
#include "lwip/sockets.h"
#define NUM_SOCKETS MEMP_NUM_NETCONN
struct lwip_socket {
struct netconn *conn;
struct netbuf *lastdata;
u16_t lastoffset;
u16_t rcvevent;
u16_t sendevent;
u16_t flags;
int err;
};
struct lwip_select_cb
{
struct lwip_select_cb *next;
fd_set *readset;
fd_set *writeset;
fd_set *exceptset;
int sem_signalled;
sys_sem_t sem;
};
static struct lwip_socket sockets[NUM_SOCKETS];
static struct lwip_select_cb *select_cb_list = 0;
static sys_sem_t socksem = 0;
static sys_sem_t selectsem = 0;
static void
event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len);
static int err_to_errno_table[11] = {
0, /* ERR_OK 0 No error, everything OK. */
ENOMEM, /* ERR_MEM -1 Out of memory error. */
ENOBUFS, /* ERR_BUF -2 Buffer error. */
ECONNABORTED, /* ERR_ABRT -3 Connection aborted. */
ECONNRESET, /* ERR_RST -4 Connection reset. */
ESHUTDOWN, /* ERR_CLSD -5 Connection closed. */
ENOTCONN, /* ERR_CONN -6 Not connected. */
EINVAL, /* ERR_VAL -7 Illegal value. */
EIO, /* ERR_ARG -8 Illegal argument. */
EHOSTUNREACH, /* ERR_RTE -9 Routing problem. */
EADDRINUSE /* ERR_USE -10 Address in use. */
};
#define ERR_TO_ERRNO_TABLE_SIZE \
(sizeof(err_to_errno_table)/sizeof(err_to_errno_table[0]))
#define err_to_errno(err) \
(-(err) >= 0 && -(err) < ERR_TO_ERRNO_TABLE_SIZE ? \
err_to_errno_table[-(err)] : EIO)
#ifdef ERRNO
#define set_errno(err) errno = (err)
#else
#define set_errno(err)
#endif
#define sock_set_errno(sk, e) do { \
sk->err = (e); \
set_errno(sk->err); \
} while (0)
static struct lwip_socket *
get_socket(int s)
{
struct lwip_socket *sock;
if ((s < 0) || (s > NUM_SOCKETS)) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): invalid\n", s));
set_errno(EBADF);
return NULL;
}
sock = &sockets[s];
if (!sock->conn) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): not active\n", s));
set_errno(EBADF);
return NULL;
}
return sock;
}
static int
alloc_socket(struct netconn *newconn)
{
int i;
if (!socksem)
socksem = sys_sem_new(1);
/* Protect socket array */
sys_sem_wait(socksem);
/* allocate a new socket identifier */
for(i = 0; i < NUM_SOCKETS; ++i) {
if (!sockets[i].conn) {
sockets[i].conn = newconn;
sockets[i].lastdata = NULL;
sockets[i].lastoffset = 0;
sockets[i].rcvevent = 0;
sockets[i].sendevent = 1; /* TCP send buf is empty */
sockets[i].flags = 0;
sockets[i].err = 0;
sys_sem_signal(socksem);
return i;
}
}
sys_sem_signal(socksem);
return -1;
}
int
lwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen)
{
struct lwip_socket *sock;
struct netconn *newconn;
struct ip_addr naddr;
u16_t port;
int newsock;
struct sockaddr_in sin;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d)...\n", s));
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
newconn = netconn_accept(sock->conn);
/* get the IP address and port of the remote host */
netconn_peer(newconn, &naddr, &port);
memset(&sin, 0, sizeof(sin));
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = naddr.addr;
if (*addrlen > sizeof(sin))
*addrlen = sizeof(sin);
memcpy(addr, &sin, *addrlen);
newsock = alloc_socket(newconn);
if (newsock == -1) {
netconn_delete(newconn);
sock_set_errno(sock, ENOBUFS);
return -1;
}
newconn->callback = event_callback;
sock = get_socket(newsock);
sys_sem_wait(socksem);
sock->rcvevent += -1 - newconn->socket;
newconn->socket = newsock;
sys_sem_signal(socksem);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d) returning new sock=%d addr=", s, newsock));
ip_addr_debug_print(SOCKETS_DEBUG, &naddr);
LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%u\n", port));
sock_set_errno(sock, 0);
return newsock;
}
int
lwip_bind(int s, struct sockaddr *name, socklen_t namelen)
{
struct lwip_socket *sock;
struct ip_addr local_addr;
u16_t local_port;
err_t err;
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
local_addr.addr = ((struct sockaddr_in *)name)->sin_addr.s_addr;
local_port = ((struct sockaddr_in *)name)->sin_port;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d, addr=", s));
ip_addr_debug_print(SOCKETS_DEBUG, &local_addr);
LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%u)\n", ntohs(local_port)));
err = netconn_bind(sock->conn, &local_addr, ntohs(local_port));
if (err != ERR_OK) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d) failed, err=%d\n", s, err));
sock_set_errno(sock, err_to_errno(err));
return -1;
}
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d) succeeded\n", s));
sock_set_errno(sock, 0);
return 0;
}
int
lwip_close(int s)
{
struct lwip_socket *sock;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_close(%d)\n", s));
if (!socksem)
socksem = sys_sem_new(1);
/* We cannot allow multiple closes of the same socket. */
sys_sem_wait(socksem);
sock = get_socket(s);
if (!sock) {
sys_sem_signal(socksem);
set_errno(EBADF);
return -1;
}
netconn_delete(sock->conn);
if (sock->lastdata) {
netbuf_delete(sock->lastdata);
}
sock->lastdata = NULL;
sock->lastoffset = 0;
sock->conn = NULL;
sys_sem_signal(socksem);
sock_set_errno(sock, 0);
return 0;
}
int
lwip_connect(int s, struct sockaddr *name, socklen_t namelen)
{
struct lwip_socket *sock;
err_t err;
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
if (((struct sockaddr_in *)name)->sin_family == AF_UNSPEC) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d, AF_UNSPEC)\n", s));
err = netconn_disconnect(sock->conn);
} else {
struct ip_addr remote_addr;
u16_t remote_port;
remote_addr.addr = ((struct sockaddr_in *)name)->sin_addr.s_addr;
remote_port = ((struct sockaddr_in *)name)->sin_port;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d, addr=", s));
ip_addr_debug_print(SOCKETS_DEBUG, &remote_addr);
LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%u)\n", ntohs(remote_port)));
err = netconn_connect(sock->conn, &remote_addr, ntohs(remote_port));
}
if (err != ERR_OK) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d) failed, err=%d\n", s, err));
sock_set_errno(sock, err_to_errno(err));
return -1;
}
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d) succeeded\n", s));
sock_set_errno(sock, 0);
return 0;
}
int
lwip_listen(int s, int backlog)
{
struct lwip_socket *sock;
err_t err;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_listen(%d, backlog=%d)\n", s, backlog));
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
err = netconn_listen(sock->conn);
if (err != ERR_OK) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_listen(%d) failed, err=%d\n", s, err));
sock_set_errno(sock, err_to_errno(err));
return -1;
}
sock_set_errno(sock, 0);
return 0;
}
int
lwip_recvfrom(int s, void *mem, int len, unsigned int flags,
struct sockaddr *from, socklen_t *fromlen)
{
struct lwip_socket *sock;
struct netbuf *buf;
u16_t buflen, copylen;
struct ip_addr *addr;
u16_t port;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d, %p, %d, 0x%x, ..)\n", s, mem, len, flags));
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
/* Check if there is data left from the last recv operation. */
if (sock->lastdata) {
buf = sock->lastdata;
} else {
/* If this is non-blocking call, then check first */
if (((flags & MSG_DONTWAIT) || (sock->flags & O_NONBLOCK))
&& !sock->rcvevent)
{
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): returning EWOULDBLOCK\n", s));
sock_set_errno(sock, EWOULDBLOCK);
return -1;
}
/* No data was left from the previous operation, so we try to get
some from the network. */
buf = netconn_recv(sock->conn);
if (!buf) {
/* We should really do some error checking here. */
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): buf == NULL!\n", s));
sock_set_errno(sock, 0);
return 0;
}
}
buflen = netbuf_len(buf);
buflen -= sock->lastoffset;
if (len > buflen) {
copylen = buflen;
} else {
copylen = len;
}
/* copy the contents of the received buffer into
the supplied memory pointer mem */
netbuf_copy_partial(buf, mem, copylen, sock->lastoffset);
/* Check to see from where the data was. */
if (from && fromlen) {
struct sockaddr_in sin;
addr = netbuf_fromaddr(buf);
port = netbuf_fromport(buf);
memset(&sin, 0, sizeof(sin));
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = addr->addr;
if (*fromlen > sizeof(sin))
*fromlen = sizeof(sin);
memcpy(from, &sin, *fromlen);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s));
ip_addr_debug_print(SOCKETS_DEBUG, addr);
LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%u len=%u\n", port, copylen));
} else {
#if SOCKETS_DEBUG
addr = netbuf_fromaddr(buf);
port = netbuf_fromport(buf);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s));
ip_addr_debug_print(SOCKETS_DEBUG, addr);
LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%u len=%u\n", port, copylen));
#endif
}
/* If this is a TCP socket, check if there is data left in the
buffer. If so, it should be saved in the sock structure for next
time around. */
if (netconn_type(sock->conn) == NETCONN_TCP && buflen - copylen > 0) {
sock->lastdata = buf;
sock->lastoffset += copylen;
} else {
sock->lastdata = NULL;
sock->lastoffset = 0;
netbuf_delete(buf);
}
sock_set_errno(sock, 0);
return copylen;
}
int
lwip_read(int s, void *mem, int len)
{
return lwip_recvfrom(s, mem, len, 0, NULL, NULL);
}
int
lwip_recv(int s, void *mem, int len, unsigned int flags)
{
return lwip_recvfrom(s, mem, len, flags, NULL, NULL);
}
int
lwip_send(int s, void *data, int size, unsigned int flags)
{
struct lwip_socket *sock;
struct netbuf *buf;
err_t err;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d, data=%p, size=%d, flags=0x%x)\n", s, data, size, flags));
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
switch (netconn_type(sock->conn)) {
case NETCONN_RAW:
case NETCONN_UDP:
case NETCONN_UDPLITE:
case NETCONN_UDPNOCHKSUM:
/* create a buffer */
buf = netbuf_new();
if (!buf) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) ENOBUFS\n", s));
sock_set_errno(sock, ENOBUFS);
return -1;
}
/* make the buffer point to the data that should
be sent */
netbuf_ref(buf, data, size);
/* send the data */
err = netconn_send(sock->conn, buf);
/* deallocated the buffer */
netbuf_delete(buf);
break;
case NETCONN_TCP:
err = netconn_write(sock->conn, data, size, NETCONN_COPY);
break;
default:
err = ERR_ARG;
break;
}
if (err != ERR_OK) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) err=%d\n", s, err));
sock_set_errno(sock, err_to_errno(err));
return -1;
}
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) ok size=%d\n", s, size));
sock_set_errno(sock, 0);
return size;
}
int
lwip_sendto(int s, void *data, int size, unsigned int flags,
struct sockaddr *to, socklen_t tolen)
{
struct lwip_socket *sock;
struct ip_addr remote_addr, addr;
u16_t remote_port, port;
int ret,connected;
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
/* get the peer if currently connected */
connected = (netconn_peer(sock->conn, &addr, &port) == ERR_OK);
remote_addr.addr = ((struct sockaddr_in *)to)->sin_addr.s_addr;
remote_port = ((struct sockaddr_in *)to)->sin_port;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_sendto(%d, data=%p, size=%d, flags=0x%x to=", s, data, size, flags));
ip_addr_debug_print(SOCKETS_DEBUG, &remote_addr);
LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%u\n", ntohs(remote_port)));
netconn_connect(sock->conn, &remote_addr, ntohs(remote_port));
ret = lwip_send(s, data, size, flags);
/* reset the remote address and port number
of the connection */
if (connected)
netconn_connect(sock->conn, &addr, port);
else
netconn_disconnect(sock->conn);
return ret;
}
int
lwip_socket(int domain, int type, int protocol)
{
struct netconn *conn;
int i;
/* create a netconn */
switch (type) {
case SOCK_RAW:
conn = netconn_new_with_proto_and_callback(NETCONN_RAW, protocol, event_callback);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_RAW, %d) = ", domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol));
break;
case SOCK_DGRAM:
conn = netconn_new_with_callback(NETCONN_UDP, event_callback);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_DGRAM, %d) = ", domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol));
break;
case SOCK_STREAM:
conn = netconn_new_with_callback(NETCONN_TCP, event_callback);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_STREAM, %d) = ", domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol));
break;
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%d, %d/UNKNOWN, %d) = -1\n", domain, type, protocol));
set_errno(EINVAL);
return -1;
}
if (!conn) {
LWIP_DEBUGF(SOCKETS_DEBUG, ("-1 / ENOBUFS (could not create netconn)\n"));
set_errno(ENOBUFS);
return -1;
}
i = alloc_socket(conn);
if (i == -1) {
netconn_delete(conn);
set_errno(ENOBUFS);
return -1;
}
conn->socket = i;
LWIP_DEBUGF(SOCKETS_DEBUG, ("%d\n", i));
set_errno(0);
return i;
}
int
lwip_write(int s, void *data, int size)
{
return lwip_send(s, data, size, 0);
}
static int
lwip_selscan(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset)
{
int i, nready = 0;
fd_set lreadset, lwriteset, lexceptset;
struct lwip_socket *p_sock;
FD_ZERO(&lreadset);
FD_ZERO(&lwriteset);
FD_ZERO(&lexceptset);
/* Go through each socket in each list to count number of sockets which
currently match */
for(i = 0; i < maxfdp1; i++)
{
if (FD_ISSET(i, readset))
{
/* See if netconn of this socket is ready for read */
p_sock = get_socket(i);
if (p_sock && (p_sock->lastdata || p_sock->rcvevent))
{
FD_SET(i, &lreadset);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for reading\n", i));
nready++;
}
}
if (FD_ISSET(i, writeset))
{
/* See if netconn of this socket is ready for write */
p_sock = get_socket(i);
if (p_sock && p_sock->sendevent)
{
FD_SET(i, &lwriteset);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for writing\n", i));
nready++;
}
}
}
*readset = lreadset;
*writeset = lwriteset;
FD_ZERO(exceptset);
return nready;
}
int
lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset,
struct timeval *timeout)
{
int i;
int nready;
fd_set lreadset, lwriteset, lexceptset;
u32_t msectimeout;
struct lwip_select_cb select_cb;
struct lwip_select_cb *p_selcb;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select(%d, %p, %p, %p, tvsec=%ld tvusec=%ld)\n", maxfdp1, (void *)readset, (void *) writeset, (void *) exceptset, timeout ? timeout->tv_sec : -1L, timeout ? timeout->tv_usec : -1L));
select_cb.next = 0;
select_cb.readset = readset;
select_cb.writeset = writeset;
select_cb.exceptset = exceptset;
select_cb.sem_signalled = 0;
/* Protect ourselves searching through the list */
if (!selectsem)
selectsem = sys_sem_new(1);
sys_sem_wait(selectsem);
if (readset)
lreadset = *readset;
else
FD_ZERO(&lreadset);
if (writeset)
lwriteset = *writeset;
else
FD_ZERO(&lwriteset);
if (exceptset)
lexceptset = *exceptset;
else
FD_ZERO(&lexceptset);
/* Go through each socket in each list to count number of sockets which
currently match */
nready = lwip_selscan(maxfdp1, &lreadset, &lwriteset, &lexceptset);
/* If we don't have any current events, then suspend if we are supposed to */
if (!nready)
{
if (timeout && timeout->tv_sec == 0 && timeout->tv_usec == 0)
{
sys_sem_signal(selectsem);
if (readset)
FD_ZERO(readset);
if (writeset)
FD_ZERO(writeset);
if (exceptset)
FD_ZERO(exceptset);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: no timeout, returning 0\n"));
set_errno(0);
return 0;
}
/* add our semaphore to list */
/* We don't actually need any dynamic memory. Our entry on the
* list is only valid while we are in this function, so it's ok
* to use local variables */
select_cb.sem = sys_sem_new(0);
/* Note that we are still protected */
/* Put this select_cb on top of list */
select_cb.next = select_cb_list;
select_cb_list = &select_cb;
/* Now we can safely unprotect */
sys_sem_signal(selectsem);
/* Now just wait to be woken */
if (timeout == 0)
/* Wait forever */
msectimeout = 0;
else
msectimeout = ((timeout->tv_sec * 1000) + ((timeout->tv_usec + 500)/1000));
i = sys_sem_wait_timeout(select_cb.sem, msectimeout);
/* Take us off the list */
sys_sem_wait(selectsem);
if (select_cb_list == &select_cb)
select_cb_list = select_cb.next;
else
for (p_selcb = select_cb_list; p_selcb; p_selcb = p_selcb->next)
if (p_selcb->next == &select_cb)
{
p_selcb->next = select_cb.next;
break;
}
sys_sem_signal(selectsem);
sys_sem_free(select_cb.sem);
if (i == 0) /* Timeout */
{
if (readset)
FD_ZERO(readset);
if (writeset)
FD_ZERO(writeset);
if (exceptset)
FD_ZERO(exceptset);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: timeout expired\n"));
set_errno(0);
return 0;
}
if (readset)
lreadset = *readset;
else
FD_ZERO(&lreadset);
if (writeset)
lwriteset = *writeset;
else
FD_ZERO(&lwriteset);
if (exceptset)
lexceptset = *exceptset;
else
FD_ZERO(&lexceptset);
/* See what's set */
nready = lwip_selscan(maxfdp1, &lreadset, &lwriteset, &lexceptset);
}
else
sys_sem_signal(selectsem);
if (readset)
*readset = lreadset;
if (writeset)
*writeset = lwriteset;
if (exceptset)
*exceptset = lexceptset;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: nready=%d\n", nready));
set_errno(0);
return nready;
}
static void
event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len)
{
int s;
struct lwip_socket *sock;
struct lwip_select_cb *scb;
/* Get socket */
if (conn)
{
s = conn->socket;
if (s < 0)
{
/* Data comes in right away after an accept, even though
* the server task might not have created a new socket yet.
* Just count down (or up) if that's the case and we
* will use the data later. Note that only receive events
* can happen before the new socket is set up. */
if (evt == NETCONN_EVT_RCVPLUS)
conn->socket--;
return;
}
sock = get_socket(s);
if (!sock)
return;
}
else
return;
if (!selectsem)
selectsem = sys_sem_new(1);
sys_sem_wait(selectsem);
/* Set event as required */
switch (evt)
{
case NETCONN_EVT_RCVPLUS:
sock->rcvevent++;
break;
case NETCONN_EVT_RCVMINUS:
sock->rcvevent--;
break;
case NETCONN_EVT_SENDPLUS:
sock->sendevent = 1;
break;
case NETCONN_EVT_SENDMINUS:
sock->sendevent = 0;
break;
}
sys_sem_signal(selectsem);
/* Now decide if anyone is waiting for this socket */
/* NOTE: This code is written this way to protect the select link list
but to avoid a deadlock situation by releasing socksem before
signalling for the select. This means we need to go through the list
multiple times ONLY IF a select was actually waiting. We go through
the list the number of waiting select calls + 1. This list is
expected to be small. */
while (1)
{
sys_sem_wait(selectsem);
for (scb = select_cb_list; scb; scb = scb->next)
{
if (scb->sem_signalled == 0)
{
/* Test this select call for our socket */
if (scb->readset && FD_ISSET(s, scb->readset))
if (sock->rcvevent)
break;
if (scb->writeset && FD_ISSET(s, scb->writeset))
if (sock->sendevent)
break;
}
}
if (scb)
{
scb->sem_signalled = 1;
sys_sem_signal(selectsem);
sys_sem_signal(scb->sem);
} else {
sys_sem_signal(selectsem);
break;
}
}
}
int lwip_shutdown(int s, int how)
{
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_shutdown(%d, how=%d)\n", s, how));
return lwip_close(s); /* XXX temporary hack until proper implementation */
}
int lwip_getpeername (int s, struct sockaddr *name, socklen_t *namelen)
{
struct lwip_socket *sock;
struct sockaddr_in sin;
struct ip_addr naddr;
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
memset(&sin, 0, sizeof(sin));
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
/* get the IP address and port of the remote host */
netconn_peer(sock->conn, &naddr, &sin.sin_port);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getpeername(%d, addr=", s));
ip_addr_debug_print(SOCKETS_DEBUG, &naddr);
LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%d)\n", sin.sin_port));
sin.sin_port = htons(sin.sin_port);
sin.sin_addr.s_addr = naddr.addr;
if (*namelen > sizeof(sin))
*namelen = sizeof(sin);
memcpy(name, &sin, *namelen);
sock_set_errno(sock, 0);
return 0;
}
int lwip_getsockname (int s, struct sockaddr *name, socklen_t *namelen)
{
struct lwip_socket *sock;
struct sockaddr_in sin;
struct ip_addr *naddr;
sock = get_socket(s);
if (!sock) {
set_errno(EBADF);
return -1;
}
memset(&sin, 0, sizeof(sin));
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
/* get the IP address and port of the remote host */
netconn_addr(sock->conn, &naddr, &sin.sin_port);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockname(%d, addr=", s));
ip_addr_debug_print(SOCKETS_DEBUG, naddr);
LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%d)\n", sin.sin_port));
sin.sin_port = htons(sin.sin_port);
sin.sin_addr.s_addr = naddr->addr;
if (*namelen > sizeof(sin))
*namelen = sizeof(sin);
memcpy(name, &sin, *namelen);
sock_set_errno(sock, 0);
return 0;
}
int lwip_getsockopt (int s, int level, int optname, void *optval, socklen_t *optlen)
{
int err = 0;
struct lwip_socket *sock = get_socket(s);
if(!sock) {
set_errno(EBADF);
return -1;
}
if( NULL == optval || NULL == optlen ) {
sock_set_errno( sock, EFAULT );
return -1;
}
/* Do length and type checks for the various options first, to keep it readable. */
switch( level ) {
/* Level: SOL_SOCKET */
case SOL_SOCKET:
switch(optname) {
case SO_ACCEPTCONN:
case SO_BROADCAST:
/* UNIMPL case SO_DEBUG: */
/* UNIMPL case SO_DONTROUTE: */
case SO_ERROR:
case SO_KEEPALIVE:
/* UNIMPL case SO_OOBINLINE: */
/* UNIMPL case SO_RCVBUF: */
/* UNIMPL case SO_SNDBUF: */
/* UNIMPL case SO_RCVLOWAT: */
/* UNIMPL case SO_SNDLOWAT: */
#if SO_REUSE
case SO_REUSEADDR:
case SO_REUSEPORT:
#endif /* SO_REUSE */
case SO_TYPE:
/* UNIMPL case SO_USELOOPBACK: */
if( *optlen < sizeof(int) ) {
err = EINVAL;
}
break;
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n", s, optname));
err = ENOPROTOOPT;
} /* switch */
break;
/* Level: IPPROTO_IP */
case IPPROTO_IP:
switch(optname) {
/* UNIMPL case IP_HDRINCL: */
/* UNIMPL case IP_RCVDSTADDR: */
/* UNIMPL case IP_RCVIF: */
case IP_TTL:
case IP_TOS:
if( *optlen < sizeof(int) ) {
err = EINVAL;
}
break;
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n", s, optname));
err = ENOPROTOOPT;
} /* switch */
break;
/* Level: IPPROTO_TCP */
case IPPROTO_TCP:
if( *optlen < sizeof(int) ) {
err = EINVAL;
break;
}
/* If this is no TCP socket, ignore any options. */
if ( sock->conn->type != NETCONN_TCP ) return 0;
switch( optname ) {
case TCP_NODELAY:
case TCP_KEEPALIVE:
break;
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n", s, optname));
err = ENOPROTOOPT;
} /* switch */
break;
/* UNDEFINED LEVEL */
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n", s, level, optname));
err = ENOPROTOOPT;
} /* switch */
if( 0 != err ) {
sock_set_errno(sock, err);
return -1;
}
/* Now do the actual option processing */
switch(level) {
/* Level: SOL_SOCKET */
case SOL_SOCKET:
switch( optname ) {
/* The option flags */
case SO_ACCEPTCONN:
case SO_BROADCAST:
/* UNIMPL case SO_DEBUG: */
/* UNIMPL case SO_DONTROUTE: */
case SO_KEEPALIVE:
/* UNIMPL case SO_OOBINCLUDE: */
#if SO_REUSE
case SO_REUSEADDR:
case SO_REUSEPORT:
#endif /* SO_REUSE */
/*case SO_USELOOPBACK: UNIMPL */
*(int*)optval = sock->conn->pcb.tcp->so_options & optname;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, optname=0x%x, ..) = %s\n", s, optname, (*(int*)optval?"on":"off")));
break;
case SO_TYPE:
switch (sock->conn->type) {
case NETCONN_RAW:
*(int*)optval = SOCK_RAW;
break;
case NETCONN_TCP:
*(int*)optval = SOCK_STREAM;
break;
case NETCONN_UDP:
case NETCONN_UDPLITE:
case NETCONN_UDPNOCHKSUM:
*(int*)optval = SOCK_DGRAM;
break;
default: /* unrecognized socket type */
*(int*)optval = sock->conn->type;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE): unrecognized socket type %d\n", s, *(int *)optval));
} /* switch */
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE) = %d\n", s, *(int *)optval));
break;
case SO_ERROR:
*(int *)optval = sock->err;
sock->err = 0;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_ERROR) = %d\n", s, *(int *)optval));
break;
} /* switch */
break;
/* Level: IPPROTO_IP */
case IPPROTO_IP:
switch( optname ) {
case IP_TTL:
*(int*)optval = sock->conn->pcb.tcp->ttl;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TTL) = %d\n", s, *(int *)optval));
break;
case IP_TOS:
*(int*)optval = sock->conn->pcb.tcp->tos;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TOS) = %d\n", s, *(int *)optval));
break;
} /* switch */
break;
/* Level: IPPROTO_TCP */
case IPPROTO_TCP:
switch( optname ) {
case TCP_NODELAY:
*(int*)optval = (sock->conn->pcb.tcp->flags & TF_NODELAY);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_NODELAY) = %s\n", s, (*(int*)optval)?"on":"off") );
break;
case TCP_KEEPALIVE:
*(int*)optval = (int)sock->conn->pcb.tcp->keepalive;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, TCP_KEEPALIVE) = %d\n", s, *(int *)optval));
break;
} /* switch */
break;
}
sock_set_errno(sock, err);
return err ? -1 : 0;
}
int lwip_setsockopt (int s, int level, int optname, const void *optval, socklen_t optlen)
{
struct lwip_socket *sock = get_socket(s);
int err = 0;
if(!sock) {
set_errno(EBADF);
return -1;
}
if( NULL == optval ) {
sock_set_errno( sock, EFAULT );
return -1;
}
/* Do length and type checks for the various options first, to keep it readable. */
switch( level ) {
/* Level: SOL_SOCKET */
case SOL_SOCKET:
switch(optname) {
case SO_BROADCAST:
/* UNIMPL case SO_DEBUG: */
/* UNIMPL case SO_DONTROUTE: */
case SO_KEEPALIVE:
/* UNIMPL case SO_OOBINLINE: */
/* UNIMPL case SO_RCVBUF: */
/* UNIMPL case SO_SNDBUF: */
/* UNIMPL case SO_RCVLOWAT: */
/* UNIMPL case SO_SNDLOWAT: */
#if SO_REUSE
case SO_REUSEADDR:
case SO_REUSEPORT:
#endif /* SO_REUSE */
/* UNIMPL case SO_USELOOPBACK: */
if( optlen < sizeof(int) ) {
err = EINVAL;
}
break;
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n", s, optname));
err = ENOPROTOOPT;
} /* switch */
break;
/* Level: IPPROTO_IP */
case IPPROTO_IP:
switch(optname) {
/* UNIMPL case IP_HDRINCL: */
/* UNIMPL case IP_RCVDSTADDR: */
/* UNIMPL case IP_RCVIF: */
case IP_TTL:
case IP_TOS:
if( optlen < sizeof(int) ) {
err = EINVAL;
}
break;
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n", s, optname));
err = ENOPROTOOPT;
} /* switch */
break;
/* Level: IPPROTO_TCP */
case IPPROTO_TCP:
if( optlen < sizeof(int) ) {
err = EINVAL;
break;
}
/* If this is no TCP socket, ignore any options. */
if ( sock->conn->type != NETCONN_TCP ) return 0;
switch( optname ) {
case TCP_NODELAY:
case TCP_KEEPALIVE:
break;
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n", s, optname));
err = ENOPROTOOPT;
} /* switch */
break;
/* UNDEFINED LEVEL */
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n", s, level, optname));
err = ENOPROTOOPT;
} /* switch */
if( 0 != err ) {
sock_set_errno(sock, err);
return -1;
}
/* Now do the actual option processing */
switch(level) {
/* Level: SOL_SOCKET */
case SOL_SOCKET:
switch(optname) {
/* The option flags */
case SO_BROADCAST:
/* UNIMPL case SO_DEBUG: */
/* UNIMPL case SO_DONTROUTE: */
case SO_KEEPALIVE:
/* UNIMPL case SO_OOBINCLUDE: */
#if SO_REUSE
case SO_REUSEADDR:
case SO_REUSEPORT:
#endif /* SO_REUSE */
/* UNIMPL case SO_USELOOPBACK: */
if ( *(int*)optval ) {
sock->conn->pcb.tcp->so_options |= optname;
} else {
sock->conn->pcb.tcp->so_options &= ~optname;
}
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, optname=0x%x, ..) -> %s\n", s, optname, (*(int*)optval?"on":"off")));
break;
} /* switch */
break;
/* Level: IPPROTO_IP */
case IPPROTO_IP:
switch( optname ) {
case IP_TTL:
sock->conn->pcb.tcp->ttl = (u8_t)(*(int*)optval);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TTL, ..) -> %u\n", s, sock->conn->pcb.tcp->ttl));
break;
case IP_TOS:
sock->conn->pcb.tcp->tos = (u8_t)(*(int*)optval);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TOS, ..)-> %u\n", s, sock->conn->pcb.tcp->tos));
break;
} /* switch */
break;
/* Level: IPPROTO_TCP */
case IPPROTO_TCP:
switch( optname ) {
case TCP_NODELAY:
if ( *(int*)optval ) {
sock->conn->pcb.tcp->flags |= TF_NODELAY;
} else {
sock->conn->pcb.tcp->flags &= ~TF_NODELAY;
}
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_NODELAY) -> %s\n", s, (*(int *)optval)?"on":"off") );
break;
case TCP_KEEPALIVE:
sock->conn->pcb.tcp->keepalive = (u32_t)(*(int*)optval);
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPALIVE) -> %lu\n", s, sock->conn->pcb.tcp->keepalive));
break;
} /* switch */
break;
} /* switch */
sock_set_errno(sock, err);
return err ? -1 : 0;
}
int lwip_ioctl(int s, long cmd, void *argp)
{
struct lwip_socket *sock = get_socket(s);
if(!sock) {
set_errno(EBADF);
return -1;
}
switch (cmd) {
case FIONREAD:
if (!argp) {
sock_set_errno(sock, EINVAL);
return -1;
}
*((u16_t*)argp) = sock->conn->recv_avail;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, FIONREAD, %p) = %u\n", s, argp, *((u16_t*)argp)));
sock_set_errno(sock, 0);
return 0;
case FIONBIO:
if (argp && *(u32_t*)argp)
sock->flags |= O_NONBLOCK;
else
sock->flags &= ~O_NONBLOCK;
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, FIONBIO, %d)\n", s, !!(sock->flags & O_NONBLOCK)));
sock_set_errno(sock, 0);
return 0;
default:
LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, UNIMPL: 0x%lx, %p)\n", s, cmd, argp));
sock_set_errno(sock, ENOSYS); /* not yet implemented */
return -1;
}
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/api/sockets.c | C | oos | 37,377 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include "lwip/err.h"
#ifdef LWIP_DEBUG
static char *err_strerr[] = {"Ok.",
"Out of memory error.",
"Buffer error.",
"Connection aborted.",
"Connection reset.",
"Connection closed.",
"Not connected.",
"Illegal value.",
"Illegal argument.",
"Routing problem.",
"Address in use."
};
char *
lwip_strerr(err_t err)
{
return err_strerr[-err];
}
#endif /* LWIP_DEBUG */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/api/err.c | C | oos | 2,151 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include "lwip/opt.h"
#include "lwip/arch.h"
#include "lwip/api_msg.h"
#include "lwip/memp.h"
#include "lwip/sys.h"
#include "lwip/tcpip.h"
#if LWIP_RAW
static u8_t
recv_raw(void *arg, struct raw_pcb *pcb, struct pbuf *p,
struct ip_addr *addr)
{
struct netbuf *buf;
struct netconn *conn;
conn = arg;
if (!conn) return 0;
if (conn->recvmbox != SYS_MBOX_NULL) {
if (!(buf = memp_malloc(MEMP_NETBUF))) {
return 0;
}
pbuf_ref(p);
buf->p = p;
buf->ptr = p;
buf->fromaddr = addr;
buf->fromport = pcb->protocol;
conn->recv_avail += p->tot_len;
/* Register event with callback */
if (conn->callback)
(*conn->callback)(conn, NETCONN_EVT_RCVPLUS, p->tot_len);
sys_mbox_post(conn->recvmbox, buf);
}
return 0; /* do not eat the packet */
}
#endif
#if LWIP_UDP
static void
recv_udp(void *arg, struct udp_pcb *pcb, struct pbuf *p,
struct ip_addr *addr, u16_t port)
{
struct netbuf *buf;
struct netconn *conn;
conn = arg;
if (conn == NULL) {
pbuf_free(p);
return;
}
if (conn->recvmbox != SYS_MBOX_NULL) {
buf = memp_malloc(MEMP_NETBUF);
if (buf == NULL) {
pbuf_free(p);
return;
} else {
buf->p = p;
buf->ptr = p;
buf->fromaddr = addr;
buf->fromport = port;
}
conn->recv_avail += p->tot_len;
/* Register event with callback */
if (conn->callback)
(*conn->callback)(conn, NETCONN_EVT_RCVPLUS, p->tot_len);
sys_mbox_post(conn->recvmbox, buf);
}
}
#endif /* LWIP_UDP */
#if LWIP_TCP
static err_t
recv_tcp(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
{
struct netconn *conn;
u16_t len;
conn = arg;
if (conn == NULL) {
pbuf_free(p);
return ERR_VAL;
}
if (conn->recvmbox != SYS_MBOX_NULL) {
conn->err = err;
if (p != NULL) {
len = p->tot_len;
conn->recv_avail += len;
}
else
len = 0;
/* Register event with callback */
if (conn->callback)
(*conn->callback)(conn, NETCONN_EVT_RCVPLUS, len);
sys_mbox_post(conn->recvmbox, p);
}
return ERR_OK;
}
static err_t
poll_tcp(void *arg, struct tcp_pcb *pcb)
{
struct netconn *conn;
conn = arg;
if (conn != NULL &&
(conn->state == NETCONN_WRITE || conn->state == NETCONN_CLOSE) &&
conn->sem != SYS_SEM_NULL) {
sys_sem_signal(conn->sem);
}
return ERR_OK;
}
static err_t
sent_tcp(void *arg, struct tcp_pcb *pcb, u16_t len)
{
struct netconn *conn;
conn = arg;
if (conn != NULL && conn->sem != SYS_SEM_NULL) {
sys_sem_signal(conn->sem);
}
if (conn && conn->callback)
if (tcp_sndbuf(conn->pcb.tcp) > TCP_SNDLOWAT)
(*conn->callback)(conn, NETCONN_EVT_SENDPLUS, len);
return ERR_OK;
}
static void
err_tcp(void *arg, err_t err)
{
struct netconn *conn;
conn = arg;
conn->pcb.tcp = NULL;
conn->err = err;
if (conn->recvmbox != SYS_MBOX_NULL) {
/* Register event with callback */
if (conn->callback)
(*conn->callback)(conn, NETCONN_EVT_RCVPLUS, 0);
sys_mbox_post(conn->recvmbox, NULL);
}
if (conn->mbox != SYS_MBOX_NULL) {
sys_mbox_post(conn->mbox, NULL);
}
if (conn->acceptmbox != SYS_MBOX_NULL) {
/* Register event with callback */
if (conn->callback)
(*conn->callback)(conn, NETCONN_EVT_RCVPLUS, 0);
sys_mbox_post(conn->acceptmbox, NULL);
}
if (conn->sem != SYS_SEM_NULL) {
sys_sem_signal(conn->sem);
}
}
static void
setup_tcp(struct netconn *conn)
{
struct tcp_pcb *pcb;
pcb = conn->pcb.tcp;
tcp_arg(pcb, conn);
tcp_recv(pcb, recv_tcp);
tcp_sent(pcb, sent_tcp);
tcp_poll(pcb, poll_tcp, 4);
tcp_err(pcb, err_tcp);
}
static err_t
accept_function(void *arg, struct tcp_pcb *newpcb, err_t err)
{
sys_mbox_t mbox;
struct netconn *newconn;
struct netconn *conn;
#if API_MSG_DEBUG
#if TCP_DEBUG
tcp_debug_print_state(newpcb->state);
#endif /* TCP_DEBUG */
#endif /* API_MSG_DEBUG */
conn = (struct netconn *)arg;
mbox = conn->acceptmbox;
newconn = memp_malloc(MEMP_NETCONN);
if (newconn == NULL) {
return ERR_MEM;
}
newconn->recvmbox = sys_mbox_new();
if (newconn->recvmbox == SYS_MBOX_NULL) {
memp_free(MEMP_NETCONN, newconn);
return ERR_MEM;
}
newconn->mbox = sys_mbox_new();
if (newconn->mbox == SYS_MBOX_NULL) {
sys_mbox_free(newconn->recvmbox);
memp_free(MEMP_NETCONN, newconn);
return ERR_MEM;
}
newconn->sem = sys_sem_new(0);
if (newconn->sem == SYS_SEM_NULL) {
sys_mbox_free(newconn->recvmbox);
sys_mbox_free(newconn->mbox);
memp_free(MEMP_NETCONN, newconn);
return ERR_MEM;
}
/* Allocations were OK, setup the PCB etc */
newconn->type = NETCONN_TCP;
newconn->pcb.tcp = newpcb;
setup_tcp(newconn);
newconn->acceptmbox = SYS_MBOX_NULL;
newconn->err = err;
/* Register event with callback */
if (conn->callback)
{
(*conn->callback)(conn, NETCONN_EVT_RCVPLUS, 0);
}
/* We have to set the callback here even though
* the new socket is unknown. Mark the socket as -1. */
newconn->callback = conn->callback;
newconn->socket = -1;
newconn->recv_avail = 0;
sys_mbox_post(mbox, newconn);
return ERR_OK;
}
#endif /* LWIP_TCP */
static void
do_newconn(struct api_msg_msg *msg)
{
if(msg->conn->pcb.tcp != NULL) {
/* This "new" connection already has a PCB allocated. */
/* Is this an error condition? Should it be deleted?
We currently just are happy and return. */
sys_mbox_post(msg->conn->mbox, NULL);
return;
}
msg->conn->err = ERR_OK;
/* Allocate a PCB for this connection */
switch(msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
msg->conn->pcb.raw = raw_new(msg->msg.bc.port); /* misusing the port field */
raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn);
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
msg->conn->pcb.udp = udp_new();
if(msg->conn->pcb.udp == NULL) {
msg->conn->err = ERR_MEM;
break;
}
udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE);
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
case NETCONN_UDPNOCHKSUM:
msg->conn->pcb.udp = udp_new();
if(msg->conn->pcb.udp == NULL) {
msg->conn->err = ERR_MEM;
break;
}
udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM);
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
case NETCONN_UDP:
msg->conn->pcb.udp = udp_new();
if(msg->conn->pcb.udp == NULL) {
msg->conn->err = ERR_MEM;
break;
}
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
#endif /* LWIP_UDP */
#if LWIP_TCP
case NETCONN_TCP:
msg->conn->pcb.tcp = tcp_new();
if(msg->conn->pcb.tcp == NULL) {
msg->conn->err = ERR_MEM;
break;
}
setup_tcp(msg->conn);
break;
#endif
}
sys_mbox_post(msg->conn->mbox, NULL);
}
static void
do_delconn(struct api_msg_msg *msg)
{
if (msg->conn->pcb.tcp != NULL) {
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
raw_remove(msg->conn->pcb.raw);
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
msg->conn->pcb.udp->recv_arg = NULL;
udp_remove(msg->conn->pcb.udp);
break;
#endif /* LWIP_UDP */
#if LWIP_TCP
case NETCONN_TCP:
if (msg->conn->pcb.tcp->state == LISTEN) {
tcp_arg(msg->conn->pcb.tcp, NULL);
tcp_accept(msg->conn->pcb.tcp, NULL);
tcp_close(msg->conn->pcb.tcp);
} else {
tcp_arg(msg->conn->pcb.tcp, NULL);
tcp_sent(msg->conn->pcb.tcp, NULL);
tcp_recv(msg->conn->pcb.tcp, NULL);
tcp_poll(msg->conn->pcb.tcp, NULL, 0);
tcp_err(msg->conn->pcb.tcp, NULL);
if (tcp_close(msg->conn->pcb.tcp) != ERR_OK) {
tcp_abort(msg->conn->pcb.tcp);
}
}
#endif
default:
break;
}
}
/* Trigger select() in socket layer */
if (msg->conn->callback)
{
(*msg->conn->callback)(msg->conn, NETCONN_EVT_RCVPLUS, 0);
(*msg->conn->callback)(msg->conn, NETCONN_EVT_SENDPLUS, 0);
}
if (msg->conn->mbox != SYS_MBOX_NULL) {
sys_mbox_post(msg->conn->mbox, NULL);
}
}
static void
do_bind(struct api_msg_msg *msg)
{
if (msg->conn->pcb.tcp == NULL) {
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
msg->conn->pcb.raw = raw_new(msg->msg.bc.port); /* misusing the port field as protocol */
raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn);
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
msg->conn->pcb.udp = udp_new();
udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE);
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
case NETCONN_UDPNOCHKSUM:
msg->conn->pcb.udp = udp_new();
udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM);
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
case NETCONN_UDP:
msg->conn->pcb.udp = udp_new();
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
#endif /* LWIP_UDP */
#if LWIP_TCP
case NETCONN_TCP:
msg->conn->pcb.tcp = tcp_new();
setup_tcp(msg->conn);
#endif /* LWIP_TCP */
default:
break;
}
}
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
msg->conn->err = raw_bind(msg->conn->pcb.raw,msg->msg.bc.ipaddr);
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
msg->conn->err = udp_bind(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port);
break;
#endif /* LWIP_UDP */
#if LWIP_TCP
case NETCONN_TCP:
msg->conn->err = tcp_bind(msg->conn->pcb.tcp,
msg->msg.bc.ipaddr, msg->msg.bc.port);
#endif /* LWIP_TCP */
default:
break;
}
sys_mbox_post(msg->conn->mbox, NULL);
}
#if LWIP_TCP
static err_t
do_connected(void *arg, struct tcp_pcb *pcb, err_t err)
{
struct netconn *conn;
conn = arg;
if (conn == NULL) {
return ERR_VAL;
}
conn->err = err;
if (conn->type == NETCONN_TCP && err == ERR_OK) {
setup_tcp(conn);
}
sys_mbox_post(conn->mbox, NULL);
return ERR_OK;
}
#endif
static void
do_connect(struct api_msg_msg *msg)
{
if (msg->conn->pcb.tcp == NULL) {
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
msg->conn->pcb.raw = raw_new(msg->msg.bc.port); /* misusing the port field as protocol */
raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn);
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
msg->conn->pcb.udp = udp_new();
if (msg->conn->pcb.udp == NULL) {
msg->conn->err = ERR_MEM;
sys_mbox_post(msg->conn->mbox, NULL);
return;
}
udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE);
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
case NETCONN_UDPNOCHKSUM:
msg->conn->pcb.udp = udp_new();
if (msg->conn->pcb.udp == NULL) {
msg->conn->err = ERR_MEM;
sys_mbox_post(msg->conn->mbox, NULL);
return;
}
udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM);
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
case NETCONN_UDP:
msg->conn->pcb.udp = udp_new();
if (msg->conn->pcb.udp == NULL) {
msg->conn->err = ERR_MEM;
sys_mbox_post(msg->conn->mbox, NULL);
return;
}
udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn);
break;
#endif /* LWIP_UDP */
#if LWIP_TCP
case NETCONN_TCP:
msg->conn->pcb.tcp = tcp_new();
if (msg->conn->pcb.tcp == NULL) {
msg->conn->err = ERR_MEM;
sys_mbox_post(msg->conn->mbox, NULL);
return;
}
#endif
default:
break;
}
}
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
raw_connect(msg->conn->pcb.raw, msg->msg.bc.ipaddr);
sys_mbox_post(msg->conn->mbox, NULL);
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
udp_connect(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port);
sys_mbox_post(msg->conn->mbox, NULL);
break;
#endif
#if LWIP_TCP
case NETCONN_TCP:
/* tcp_arg(msg->conn->pcb.tcp, msg->conn);*/
setup_tcp(msg->conn);
tcp_connect(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, msg->msg.bc.port,
do_connected);
/*tcp_output(msg->conn->pcb.tcp);*/
#endif
default:
break;
}
}
static void
do_disconnect(struct api_msg_msg *msg)
{
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
/* Do nothing as connecting is only a helper for upper lwip layers */
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
udp_disconnect(msg->conn->pcb.udp);
break;
#endif
case NETCONN_TCP:
break;
}
sys_mbox_post(msg->conn->mbox, NULL);
}
static void
do_listen(struct api_msg_msg *msg)
{
if (msg->conn->pcb.tcp != NULL) {
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
LWIP_DEBUGF(API_MSG_DEBUG, ("api_msg: listen RAW: cannot listen for RAW.\n"));
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
LWIP_DEBUGF(API_MSG_DEBUG, ("api_msg: listen UDP: cannot listen for UDP.\n"));
break;
#endif /* LWIP_UDP */
#if LWIP_TCP
case NETCONN_TCP:
msg->conn->pcb.tcp = tcp_listen(msg->conn->pcb.tcp);
if (msg->conn->pcb.tcp == NULL) {
msg->conn->err = ERR_MEM;
} else {
if (msg->conn->acceptmbox == SYS_MBOX_NULL) {
msg->conn->acceptmbox = sys_mbox_new();
if (msg->conn->acceptmbox == SYS_MBOX_NULL) {
msg->conn->err = ERR_MEM;
break;
}
}
tcp_arg(msg->conn->pcb.tcp, msg->conn);
tcp_accept(msg->conn->pcb.tcp, accept_function);
}
#endif
default:
break;
}
}
sys_mbox_post(msg->conn->mbox, NULL);
}
static void
do_accept(struct api_msg_msg *msg)
{
if (msg->conn->pcb.tcp != NULL) {
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
LWIP_DEBUGF(API_MSG_DEBUG, ("api_msg: accept RAW: cannot accept for RAW.\n"));
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
LWIP_DEBUGF(API_MSG_DEBUG, ("api_msg: accept UDP: cannot accept for UDP.\n"));
break;
#endif /* LWIP_UDP */
case NETCONN_TCP:
break;
}
}
}
static void
do_send(struct api_msg_msg *msg)
{
if (msg->conn->pcb.tcp != NULL) {
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
raw_send(msg->conn->pcb.raw, msg->msg.p);
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
udp_send(msg->conn->pcb.udp, msg->msg.p);
break;
#endif /* LWIP_UDP */
case NETCONN_TCP:
break;
}
}
sys_mbox_post(msg->conn->mbox, NULL);
}
static void
do_recv(struct api_msg_msg *msg)
{
#if LWIP_TCP
if (msg->conn->pcb.tcp != NULL) {
if (msg->conn->type == NETCONN_TCP) {
tcp_recved(msg->conn->pcb.tcp, msg->msg.len);
}
}
#endif
sys_mbox_post(msg->conn->mbox, NULL);
}
static void
do_write(struct api_msg_msg *msg)
{
#if LWIP_TCP
err_t err;
#endif
if (msg->conn->pcb.tcp != NULL) {
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
msg->conn->err = ERR_VAL;
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
msg->conn->err = ERR_VAL;
break;
#endif /* LWIP_UDP */
#if LWIP_TCP
case NETCONN_TCP:
err = tcp_write(msg->conn->pcb.tcp, msg->msg.w.dataptr,
msg->msg.w.len, msg->msg.w.copy);
/* This is the Nagle algorithm: inhibit the sending of new TCP
segments when new outgoing data arrives from the user if any
previously transmitted data on the connection remains
unacknowledged. */
if(err == ERR_OK && (msg->conn->pcb.tcp->unacked == NULL ||
(msg->conn->pcb.tcp->flags & TF_NODELAY) ||
(msg->conn->pcb.tcp->snd_queuelen) > 1)) {
tcp_output(msg->conn->pcb.tcp);
}
msg->conn->err = err;
if (msg->conn->callback)
if (err == ERR_OK)
{
if (tcp_sndbuf(msg->conn->pcb.tcp) <= TCP_SNDLOWAT)
(*msg->conn->callback)(msg->conn, NETCONN_EVT_SENDMINUS, msg->msg.w.len);
}
#endif
default:
break;
}
}
sys_mbox_post(msg->conn->mbox, NULL);
}
static void
do_close(struct api_msg_msg *msg)
{
err_t err;
err = ERR_OK;
if (msg->conn->pcb.tcp != NULL) {
switch (msg->conn->type) {
#if LWIP_RAW
case NETCONN_RAW:
break;
#endif
#if LWIP_UDP
case NETCONN_UDPLITE:
/* FALLTHROUGH */
case NETCONN_UDPNOCHKSUM:
/* FALLTHROUGH */
case NETCONN_UDP:
break;
#endif /* LWIP_UDP */
#if LWIP_TCP
case NETCONN_TCP:
if (msg->conn->pcb.tcp->state == LISTEN) {
err = tcp_close(msg->conn->pcb.tcp);
}
else if (msg->conn->pcb.tcp->state == CLOSE_WAIT) {
err = tcp_output(msg->conn->pcb.tcp);
}
msg->conn->err = err;
#endif
default:
break;
}
}
sys_mbox_post(msg->conn->mbox, NULL);
}
typedef void (* api_msg_decode)(struct api_msg_msg *msg);
static api_msg_decode decode[API_MSG_MAX] = {
do_newconn,
do_delconn,
do_bind,
do_connect,
do_disconnect,
do_listen,
do_accept,
do_send,
do_recv,
do_write,
do_close
};
void
api_msg_input(struct api_msg *msg)
{
decode[msg->type](&(msg->msg));
}
void
api_msg_post(struct api_msg *msg)
{
tcpip_apimsg(msg);
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/api/api_msg.c | C | oos | 20,367 |
/** @file
*
* Dynamic memory manager
*
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include <string.h>
#include "lwip/arch.h"
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/sys.h"
#include "lwip/stats.h"
#if (MEM_LIBC_MALLOC == 0)
/* lwIP replacement for your libc malloc() */
struct mem {
mem_size_t next, prev;
#if MEM_ALIGNMENT == 1
u8_t used;
#elif MEM_ALIGNMENT == 2
u16_t used;
#elif MEM_ALIGNMENT == 4
u32_t used;
#elif MEM_ALIGNMENT == 8
u64_t used;
#else
#error "unhandled MEM_ALIGNMENT size"
#endif /* MEM_ALIGNMENT */
};
static struct mem *ram_end;
#if 1
/* Adam original */
static u8_t ram[MEM_SIZE + sizeof(struct mem) + MEM_ALIGNMENT];
#else
/* Christiaan alignment fix */
static u8_t *ram;
static struct mem ram_heap[1 + ( (MEM_SIZE + sizeof(struct mem) - 1) / sizeof(struct mem))];
#endif
#define MIN_SIZE 12
#if 0 /* this one does not align correctly for some, resulting in crashes */
#define SIZEOF_STRUCT_MEM (unsigned int)MEM_ALIGN_SIZE(sizeof(struct mem))
#else
#define SIZEOF_STRUCT_MEM (sizeof(struct mem) + \
(((sizeof(struct mem) % MEM_ALIGNMENT) == 0)? 0 : \
(4 - (sizeof(struct mem) % MEM_ALIGNMENT))))
#endif
static struct mem *lfree; /* pointer to the lowest free block */
static sys_sem_t mem_sem;
static void
plug_holes(struct mem *mem)
{
struct mem *nmem;
struct mem *pmem;
LWIP_ASSERT("plug_holes: mem >= ram", (u8_t *)mem >= ram);
LWIP_ASSERT("plug_holes: mem < ram_end", (u8_t *)mem < (u8_t *)ram_end);
LWIP_ASSERT("plug_holes: mem->used == 0", mem->used == 0);
/* plug hole forward */
LWIP_ASSERT("plug_holes: mem->next <= MEM_SIZE", mem->next <= MEM_SIZE);
nmem = (struct mem *)&ram[mem->next];
if (mem != nmem && nmem->used == 0 && (u8_t *)nmem != (u8_t *)ram_end) {
if (lfree == nmem) {
lfree = mem;
}
mem->next = nmem->next;
((struct mem *)&ram[nmem->next])->prev = (u8_t *)mem - ram;
}
/* plug hole backward */
pmem = (struct mem *)&ram[mem->prev];
if (pmem != mem && pmem->used == 0) {
if (lfree == mem) {
lfree = pmem;
}
pmem->next = mem->next;
((struct mem *)&ram[mem->next])->prev = (u8_t *)pmem - ram;
}
}
void
mem_init(void)
{
struct mem *mem;
#if 1
/* Adam original */
#else
/* Christiaan alignment fix */
ram = (u8_t*)ram_heap;
#endif
memset(ram, 0, MEM_SIZE);
mem = (struct mem *)ram;
mem->next = MEM_SIZE;
mem->prev = 0;
mem->used = 0;
ram_end = (struct mem *)&ram[MEM_SIZE];
ram_end->used = 1;
ram_end->next = MEM_SIZE;
ram_end->prev = MEM_SIZE;
mem_sem = sys_sem_new(1);
lfree = (struct mem *)ram;
#if MEM_STATS
lwip_stats.mem.avail = MEM_SIZE;
#endif /* MEM_STATS */
}
void
mem_free(void *rmem)
{
struct mem *mem;
if (rmem == NULL) {
LWIP_DEBUGF(MEM_DEBUG | DBG_TRACE | 2, ("mem_free(p == NULL) was called.\n"));
return;
}
sys_sem_wait(mem_sem);
LWIP_ASSERT("mem_free: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
(u8_t *)rmem < (u8_t *)ram_end);
if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
LWIP_DEBUGF(MEM_DEBUG | 3, ("mem_free: illegal memory\n"));
#if MEM_STATS
++lwip_stats.mem.err;
#endif /* MEM_STATS */
sys_sem_signal(mem_sem);
return;
}
mem = (struct mem *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
LWIP_ASSERT("mem_free: mem->used", mem->used);
mem->used = 0;
if (mem < lfree) {
lfree = mem;
}
#if MEM_STATS
lwip_stats.mem.used -= mem->next - ((u8_t *)mem - ram);
#endif /* MEM_STATS */
plug_holes(mem);
sys_sem_signal(mem_sem);
}
void *
mem_realloc(void *rmem, mem_size_t newsize)
{
mem_size_t size;
mem_size_t ptr, ptr2;
struct mem *mem, *mem2;
/* Expand the size of the allocated memory region so that we can
adjust for alignment. */
if ((newsize % MEM_ALIGNMENT) != 0) {
newsize += MEM_ALIGNMENT - ((newsize + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT);
}
if (newsize > MEM_SIZE) {
return NULL;
}
sys_sem_wait(mem_sem);
LWIP_ASSERT("mem_realloc: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
(u8_t *)rmem < (u8_t *)ram_end);
if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
LWIP_DEBUGF(MEM_DEBUG | 3, ("mem_realloc: illegal memory\n"));
return rmem;
}
mem = (struct mem *)((u8_t *)rmem - SIZEOF_STRUCT_MEM);
ptr = (u8_t *)mem - ram;
size = mem->next - ptr - SIZEOF_STRUCT_MEM;
#if MEM_STATS
lwip_stats.mem.used -= (size - newsize);
#endif /* MEM_STATS */
if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE < size) {
ptr2 = ptr + SIZEOF_STRUCT_MEM + newsize;
mem2 = (struct mem *)&ram[ptr2];
mem2->used = 0;
mem2->next = mem->next;
mem2->prev = ptr;
mem->next = ptr2;
if (mem2->next != MEM_SIZE) {
((struct mem *)&ram[mem2->next])->prev = ptr2;
}
plug_holes(mem2);
}
sys_sem_signal(mem_sem);
return rmem;
}
#if 1
/**
* Adam's mem_malloc(), suffers from bug #17922
* Set if to 0 for alternative mem_malloc().
*/
void *
mem_malloc(mem_size_t size)
{
mem_size_t ptr, ptr2;
struct mem *mem, *mem2;
if (size == 0) {
return NULL;
}
/* Expand the size of the allocated memory region so that we can
adjust for alignment. */
if ((size % MEM_ALIGNMENT) != 0) {
size += MEM_ALIGNMENT - ((size + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT);
}
if (size > MEM_SIZE) {
return NULL;
}
sys_sem_wait(mem_sem);
for (ptr = (u8_t *)lfree - ram; ptr < MEM_SIZE; ptr = ((struct mem *)&ram[ptr])->next) {
mem = (struct mem *)&ram[ptr];
if (!mem->used &&
mem->next - (ptr + SIZEOF_STRUCT_MEM) >= size + SIZEOF_STRUCT_MEM) {
ptr2 = ptr + SIZEOF_STRUCT_MEM + size;
mem2 = (struct mem *)&ram[ptr2];
mem2->prev = ptr;
mem2->next = mem->next;
mem->next = ptr2;
if (mem2->next != MEM_SIZE) {
((struct mem *)&ram[mem2->next])->prev = ptr2;
}
mem2->used = 0;
mem->used = 1;
#if MEM_STATS
lwip_stats.mem.used += (size + SIZEOF_STRUCT_MEM);
/* if (lwip_stats.mem.max < lwip_stats.mem.used) {
lwip_stats.mem.max = lwip_stats.mem.used;
} */
if (lwip_stats.mem.max < ptr2) {
lwip_stats.mem.max = ptr2;
}
#endif /* MEM_STATS */
if (mem == lfree) {
/* Find next free block after mem */
while (lfree->used && lfree != ram_end) {
lfree = (struct mem *)&ram[lfree->next];
}
LWIP_ASSERT("mem_malloc: !lfree->used", !lfree->used);
}
sys_sem_signal(mem_sem);
LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.",
(mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end);
LWIP_ASSERT("mem_malloc: allocated memory properly aligned.",
(unsigned long)((u8_t *)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0);
return (u8_t *)mem + SIZEOF_STRUCT_MEM;
}
}
LWIP_DEBUGF(MEM_DEBUG | 2, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size));
#if MEM_STATS
++lwip_stats.mem.err;
#endif /* MEM_STATS */
sys_sem_signal(mem_sem);
return NULL;
}
#else
/**
* Adam's mem_malloc() plus solution for bug #17922
*/
void *
mem_malloc(mem_size_t size)
{
mem_size_t ptr, ptr2;
struct mem *mem, *mem2;
if (size == 0) {
return NULL;
}
/* Expand the size of the allocated memory region so that we can
adjust for alignment. */
if ((size % MEM_ALIGNMENT) != 0) {
size += MEM_ALIGNMENT - ((size + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT);
}
if (size > MEM_SIZE) {
return NULL;
}
sys_sem_wait(mem_sem);
for (ptr = (u8_t *)lfree - ram; ptr < MEM_SIZE - size; ptr = ((struct mem *)&ram[ptr])->next) {
mem = (struct mem *)&ram[ptr];
if (!mem->used) {
ptr2 = ptr + SIZEOF_STRUCT_MEM + size;
if (mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) >= size) {
/* split large block, create empty remainder */
mem->next = ptr2;
mem->used = 1;
/* create mem2 struct */
mem2 = (struct mem *)&ram[ptr2];
mem2->used = 0;
mem2->next = mem->next;
mem2->prev = ptr;
if (mem2->next != MEM_SIZE) {
((struct mem *)&ram[mem2->next])->prev = ptr2;
}
}
else if (mem->next - (ptr + SIZEOF_STRUCT_MEM) > size) {
/* near fit, no split, no mem2 creation,
round up to mem->next */
ptr2 = mem->next;
mem->used = 1;
}
else if (mem->next - (ptr + SIZEOF_STRUCT_MEM) == size) {
/* exact fit, do not split, no mem2 creation */
mem->next = ptr2;
mem->used = 1;
}
if (mem->used) {
#if MEM_STATS
lwip_stats.mem.used += (size + SIZEOF_STRUCT_MEM);
if (lwip_stats.mem.max < ptr2) {
lwip_stats.mem.max = ptr2;
}
#endif /* MEM_STATS */
if (mem == lfree) {
/* Find next free block after mem */
while (lfree->used && lfree != ram_end) {
lfree = (struct mem *)&ram[lfree->next];
}
LWIP_ASSERT("mem_malloc: !lfree->used", !lfree->used);
}
sys_sem_signal(mem_sem);
LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.",
(mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end);
LWIP_ASSERT("mem_malloc: allocated memory properly aligned.",
(unsigned long)((u8_t *)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0);
return (u8_t *)mem + SIZEOF_STRUCT_MEM;
}
}
}
LWIP_DEBUGF(MEM_DEBUG | 2, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size));
#if MEM_STATS
++lwip_stats.mem.err;
#endif /* MEM_STATS */
sys_sem_signal(mem_sem);
return NULL;
}
#endif
#endif /* MEM_LIBC_MALLOC == 0 */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/core/mem.c | C | oos | 11,683 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include <string.h>
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/stats.h"
#include "lwip/mem.h"
#if LWIP_STATS
struct stats_ lwip_stats;
void
stats_init(void)
{
memset(&lwip_stats, 0, sizeof(struct stats_));
}
#if LWIP_STATS_DISPLAY
void
stats_display_proto(struct stats_proto *proto, char *name)
{
LWIP_PLATFORM_DIAG(("\n%s\n\t", name));
LWIP_PLATFORM_DIAG(("xmit: %"S16_F"\n\t", proto->xmit));
LWIP_PLATFORM_DIAG(("rexmit: %"S16_F"\n\t", proto->rexmit));
LWIP_PLATFORM_DIAG(("recv: %"S16_F"\n\t", proto->recv));
LWIP_PLATFORM_DIAG(("fw: %"S16_F"\n\t", proto->fw));
LWIP_PLATFORM_DIAG(("drop: %"S16_F"\n\t", proto->drop));
LWIP_PLATFORM_DIAG(("chkerr: %"S16_F"\n\t", proto->chkerr));
LWIP_PLATFORM_DIAG(("lenerr: %"S16_F"\n\t", proto->lenerr));
LWIP_PLATFORM_DIAG(("memerr: %"S16_F"\n\t", proto->memerr));
LWIP_PLATFORM_DIAG(("rterr: %"S16_F"\n\t", proto->rterr));
LWIP_PLATFORM_DIAG(("proterr: %"S16_F"\n\t", proto->proterr));
LWIP_PLATFORM_DIAG(("opterr: %"S16_F"\n\t", proto->opterr));
LWIP_PLATFORM_DIAG(("err: %"S16_F"\n\t", proto->err));
LWIP_PLATFORM_DIAG(("cachehit: %"S16_F"\n", proto->cachehit));
}
void
stats_display_pbuf(struct stats_pbuf *pbuf)
{
LWIP_PLATFORM_DIAG(("\nPBUF\n\t"));
LWIP_PLATFORM_DIAG(("avail: %"S16_F"\n\t", pbuf->avail));
LWIP_PLATFORM_DIAG(("used: %"S16_F"\n\t", pbuf->used));
LWIP_PLATFORM_DIAG(("max: %"S16_F"\n\t", pbuf->max));
LWIP_PLATFORM_DIAG(("err: %"S16_F"\n\t", pbuf->err));
LWIP_PLATFORM_DIAG(("alloc_locked: %"S16_F"\n\t", pbuf->alloc_locked));
LWIP_PLATFORM_DIAG(("refresh_locked: %"S16_F"\n", pbuf->refresh_locked));
}
void
stats_display_mem(struct stats_mem *mem, char *name)
{
LWIP_PLATFORM_DIAG(("\n MEM %s\n\t", name));
LWIP_PLATFORM_DIAG(("avail: %"MEM_SIZE_F"\n\t", mem->avail));
LWIP_PLATFORM_DIAG(("used: %"MEM_SIZE_F"\n\t", mem->used));
LWIP_PLATFORM_DIAG(("max: %"MEM_SIZE_F"\n\t", mem->max));
LWIP_PLATFORM_DIAG(("err: %"MEM_SIZE_F"\n", mem->err));
}
void
stats_display(void)
{
s16_t i;
char * memp_names[] = {"PBUF", "RAW_PCB", "UDP_PCB", "TCP_PCB", "TCP_PCB_LISTEN",
"TCP_SEG", "NETBUF", "NETCONN", "API_MSG", "TCP_MSG", "TIMEOUT"};
stats_display_proto(&lwip_stats.link, "LINK");
stats_display_proto(&lwip_stats.ip_frag, "IP_FRAG");
stats_display_proto(&lwip_stats.ip, "IP");
stats_display_proto(&lwip_stats.icmp, "ICMP");
stats_display_proto(&lwip_stats.udp, "UDP");
stats_display_proto(&lwip_stats.tcp, "TCP");
stats_display_pbuf(&lwip_stats.pbuf);
stats_display_mem(&lwip_stats.mem, "HEAP");
for (i = 0; i < MEMP_MAX; i++) {
stats_display_mem(&lwip_stats.memp[i], memp_names[i]);
}
}
#endif /* LWIP_STATS_DISPLAY */
#endif /* LWIP_STATS */
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/core/stats.c | C | oos | 4,470 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
/* inet6.c
*
* Functions common to all TCP/IP modules, such as the Internet checksum and the
* byte order functions.
*
*/
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/inet.h"
/* chksum:
*
* Sums up all 16 bit words in a memory portion. Also includes any odd byte.
* This function is used by the other checksum functions.
*
* For now, this is not optimized. Must be optimized for the particular processor
* arcitecture on which it is to run. Preferebly coded in assembler.
*/
static u32_t
chksum(void *dataptr, u16_t len)
{
u16_t *sdataptr = dataptr;
u32_t acc;
for(acc = 0; len > 1; len -= 2) {
acc += *sdataptr++;
}
/* add up any odd byte */
if (len == 1) {
acc += htons((u16_t)(*(u8_t *)dataptr) << 8);
}
return acc;
}
/* inet_chksum_pseudo:
*
* Calculates the pseudo Internet checksum used by TCP and UDP for a pbuf chain.
*/
u16_t
inet_chksum_pseudo(struct pbuf *p,
struct ip_addr *src, struct ip_addr *dest,
u8_t proto, u32_t proto_len)
{
u32_t acc;
struct pbuf *q;
u8_t swapped, i;
acc = 0;
swapped = 0;
for(q = p; q != NULL; q = q->next) {
acc += chksum(q->payload, q->len);
while (acc >> 16) {
acc = (acc & 0xffff) + (acc >> 16);
}
if (q->len % 2 != 0) {
swapped = 1 - swapped;
acc = ((acc & 0xff) << 8) | ((acc & 0xff00) >> 8);
}
}
if (swapped) {
acc = ((acc & 0xff) << 8) | ((acc & 0xff00) >> 8);
}
for(i = 0; i < 8; i++) {
acc += ((u16_t *)src->addr)[i] & 0xffff;
acc += ((u16_t *)dest->addr)[i] & 0xffff;
while (acc >> 16) {
acc = (acc & 0xffff) + (acc >> 16);
}
}
acc += (u16_t)htons((u16_t)proto);
acc += ((u16_t *)&proto_len)[0] & 0xffff;
acc += ((u16_t *)&proto_len)[1] & 0xffff;
while (acc >> 16) {
acc = (acc & 0xffff) + (acc >> 16);
}
return ~(acc & 0xffff);
}
/* inet_chksum:
*
* Calculates the Internet checksum over a portion of memory. Used primarely for IP
* and ICMP.
*/
u16_t
inet_chksum(void *dataptr, u16_t len)
{
u32_t acc, sum;
acc = chksum(dataptr, len);
sum = (acc & 0xffff) + (acc >> 16);
sum += (sum >> 16);
return ~(sum & 0xffff);
}
u16_t
inet_chksum_pbuf(struct pbuf *p)
{
u32_t acc;
struct pbuf *q;
u8_t swapped;
acc = 0;
swapped = 0;
for(q = p; q != NULL; q = q->next) {
acc += chksum(q->payload, q->len);
while (acc >> 16) {
acc = (acc & 0xffff) + (acc >> 16);
}
if (q->len % 2 != 0) {
swapped = 1 - swapped;
acc = (acc & 0xff << 8) | (acc & 0xff00 >> 8);
}
}
if (swapped) {
acc = ((acc & 0xff) << 8) | ((acc & 0xff00) >> 8);
}
return ~(acc & 0xffff);
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/core/inet6.c | C | oos | 4,458 |
/**
* @file
*
* lwIP network interface abstraction
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/tcp.h"
#include "lwip/snmp.h"
struct netif *netif_list = NULL;
struct netif *netif_default = NULL;
/**
* Add a network interface to the list of lwIP netifs.
*
* @param netif a pre-allocated netif structure
* @param ipaddr IP address for the new netif
* @param netmask network mask for the new netif
* @param gw default gateway IP address for the new netif
* @param state opaque data passed to the new netif
* @param init callback function that initializes the interface
* @param input callback function that is called to pass
* ingress packets up in the protocol layer stack.
*
* @return netif, or NULL if failed.
*/
struct netif *
netif_add(struct netif *netif, struct ip_addr *ipaddr, struct ip_addr *netmask,
struct ip_addr *gw,
void *state,
err_t (* init)(struct netif *netif),
err_t (* input)(struct pbuf *p, struct netif *netif))
{
static s16_t netifnum = 0;
/* reset new interface configuration state */
netif->ip_addr.addr = 0;
netif->netmask.addr = 0;
netif->gw.addr = 0;
netif->flags = 0;
#if LWIP_DHCP
/* netif not under DHCP control by default */
netif->dhcp = NULL;
#endif
/* remember netif specific state information data */
netif->state = state;
netif->num = netifnum++;
netif->input = input;
netif_set_addr(netif, ipaddr, netmask, gw);
/* call user specified initialization function for netif */
if (init(netif) != ERR_OK) {
return NULL;
}
/* add this netif to the list */
netif->next = netif_list;
netif_list = netif;
snmp_inc_iflist();
LWIP_DEBUGF(NETIF_DEBUG, ("netif: added interface %c%c IP addr ",
netif->name[0], netif->name[1]));
ip_addr_debug_print(NETIF_DEBUG, ipaddr);
LWIP_DEBUGF(NETIF_DEBUG, (" netmask "));
ip_addr_debug_print(NETIF_DEBUG, netmask);
LWIP_DEBUGF(NETIF_DEBUG, (" gw "));
ip_addr_debug_print(NETIF_DEBUG, gw);
LWIP_DEBUGF(NETIF_DEBUG, ("\n"));
return netif;
}
void
netif_set_addr(struct netif *netif,struct ip_addr *ipaddr, struct ip_addr *netmask,
struct ip_addr *gw)
{
netif_set_ipaddr(netif, ipaddr);
netif_set_netmask(netif, netmask);
netif_set_gw(netif, gw);
}
void netif_remove(struct netif * netif)
{
if ( netif == NULL ) return;
snmp_delete_ipaddridx_tree(netif);
/* is it the first netif? */
if (netif_list == netif) {
netif_list = netif->next;
snmp_dec_iflist();
}
else {
/* look for netif further down the list */
struct netif * tmpNetif;
for (tmpNetif = netif_list; tmpNetif != NULL; tmpNetif = tmpNetif->next) {
if (tmpNetif->next == netif) {
tmpNetif->next = netif->next;
snmp_dec_iflist();
break;
}
}
if (tmpNetif == NULL)
return; /* we didn't find any netif today */
}
/* this netif is default? */
if (netif_default == netif)
/* reset default netif */
netif_default = NULL;
LWIP_DEBUGF( NETIF_DEBUG, ("netif_remove: removed netif\n") );
}
struct netif *
netif_find(char *name)
{
struct netif *netif;
u8_t num;
if (name == NULL) {
return NULL;
}
num = name[2] - '0';
for(netif = netif_list; netif != NULL; netif = netif->next) {
if (num == netif->num &&
name[0] == netif->name[0] &&
name[1] == netif->name[1]) {
LWIP_DEBUGF(NETIF_DEBUG, ("netif_find: found %c%c\n", name[0], name[1]));
return netif;
}
}
LWIP_DEBUGF(NETIF_DEBUG, ("netif_find: didn't find %c%c\n", name[0], name[1]));
return NULL;
}
void
netif_set_ipaddr(struct netif *netif, struct ip_addr *ipaddr)
{
/* TODO: Handling of obsolete pcbs */
/* See: http://mail.gnu.org/archive/html/lwip-users/2003-03/msg00118.html */
#if LWIP_TCP
struct tcp_pcb *pcb;
struct tcp_pcb_listen *lpcb;
/* address is actually being changed? */
if ((ip_addr_cmp(ipaddr, &(netif->ip_addr))) == 0)
{
/* extern struct tcp_pcb *tcp_active_pcbs; defined by tcp.h */
LWIP_DEBUGF(NETIF_DEBUG | 1, ("netif_set_ipaddr: netif address being changed\n"));
pcb = tcp_active_pcbs;
while (pcb != NULL) {
/* PCB bound to current local interface address? */
if (ip_addr_cmp(&(pcb->local_ip), &(netif->ip_addr))) {
/* this connection must be aborted */
struct tcp_pcb *next = pcb->next;
LWIP_DEBUGF(NETIF_DEBUG | 1, ("netif_set_ipaddr: aborting TCP pcb %p\n", (void *)pcb));
tcp_abort(pcb);
pcb = next;
} else {
pcb = pcb->next;
}
}
for (lpcb = tcp_listen_pcbs.listen_pcbs; lpcb != NULL; lpcb = lpcb->next) {
/* PCB bound to current local interface address? */
if (ip_addr_cmp(&(lpcb->local_ip), &(netif->ip_addr))) {
/* The PCB is listening to the old ipaddr and
* is set to listen to the new one instead */
ip_addr_set(&(lpcb->local_ip), ipaddr);
}
}
}
#endif
snmp_delete_ipaddridx_tree(netif);
snmp_delete_iprteidx_tree(0,netif);
/* set new IP address to netif */
ip_addr_set(&(netif->ip_addr), ipaddr);
snmp_insert_ipaddridx_tree(netif);
snmp_insert_iprteidx_tree(0,netif);
#if 0 /* only allowed for Ethernet interfaces TODO: how can we check? */
/** For Ethernet network interfaces, we would like to send a
* "gratuitous ARP"; this is an ARP packet sent by a node in order
* to spontaneously cause other nodes to update an entry in their
* ARP cache. From RFC 3220 "IP Mobility Support for IPv4" section 4.6.
*/
etharp_query(netif, ipaddr, NULL);
#endif
LWIP_DEBUGF(NETIF_DEBUG | DBG_TRACE | DBG_STATE | 3, ("netif: IP address of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
netif->name[0], netif->name[1],
ip4_addr1(&netif->ip_addr),
ip4_addr2(&netif->ip_addr),
ip4_addr3(&netif->ip_addr),
ip4_addr4(&netif->ip_addr)));
}
void
netif_set_gw(struct netif *netif, struct ip_addr *gw)
{
ip_addr_set(&(netif->gw), gw);
LWIP_DEBUGF(NETIF_DEBUG | DBG_TRACE | DBG_STATE | 3, ("netif: GW address of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
netif->name[0], netif->name[1],
ip4_addr1(&netif->gw),
ip4_addr2(&netif->gw),
ip4_addr3(&netif->gw),
ip4_addr4(&netif->gw)));
}
void
netif_set_netmask(struct netif *netif, struct ip_addr *netmask)
{
snmp_delete_iprteidx_tree(0, netif);
/* set new netmask to netif */
ip_addr_set(&(netif->netmask), netmask);
snmp_insert_iprteidx_tree(0, netif);
LWIP_DEBUGF(NETIF_DEBUG | DBG_TRACE | DBG_STATE | 3, ("netif: netmask of interface %c%c set to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
netif->name[0], netif->name[1],
ip4_addr1(&netif->netmask),
ip4_addr2(&netif->netmask),
ip4_addr3(&netif->netmask),
ip4_addr4(&netif->netmask)));
}
void
netif_set_default(struct netif *netif)
{
if (netif == NULL)
{
/* remove default route */
snmp_delete_iprteidx_tree(1, netif);
}
else
{
/* install default route */
snmp_insert_iprteidx_tree(1, netif);
}
netif_default = netif;
LWIP_DEBUGF(NETIF_DEBUG, ("netif: setting default interface %c%c\n",
netif ? netif->name[0] : '\'', netif ? netif->name[1] : '\''));
}
/**
* Bring an interface up, available for processing
* traffic.
*
* @note: Enabling DHCP on a down interface will make it come
* up once configured.
*
* @see dhcp_start()
*/
void netif_set_up(struct netif *netif)
{
netif->flags |= NETIF_FLAG_UP;
#if LWIP_SNMP
snmp_get_sysuptime(&netif->ts);
#endif
}
/**
* Ask if an interface is up
*/
u8_t netif_is_up(struct netif *netif)
{
return (netif->flags & NETIF_FLAG_UP)?1:0;
}
/**
* Bring an interface down, disabling any traffic processing.
*
* @note: Enabling DHCP on a down interface will make it come
* up once configured.
*
* @see dhcp_start()
*/
void netif_set_down(struct netif *netif)
{
netif->flags &= ~NETIF_FLAG_UP;
#if LWIP_SNMP
snmp_get_sysuptime(&netif->ts);
#endif
}
void
netif_init(void)
{
netif_list = netif_default = NULL;
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/core/netif.c | C | oos | 9,952 |
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
#include "lwip/opt.h"
#include "lwip/memp.h"
#include "lwip/pbuf.h"
#include "lwip/udp.h"
#include "lwip/raw.h"
#include "lwip/tcp.h"
#include "lwip/api.h"
#include "lwip/api_msg.h"
#include "lwip/tcpip.h"
#include "lwip/sys.h"
#include "lwip/stats.h"
struct memp {
struct memp *next;
};
#define MEMP_SIZE MEM_ALIGN_SIZE(sizeof(struct memp))
static struct memp *memp_tab[MEMP_MAX];
static const u16_t memp_sizes[MEMP_MAX] = {
MEM_ALIGN_SIZE(sizeof(struct pbuf)),
MEM_ALIGN_SIZE(sizeof(struct raw_pcb)),
MEM_ALIGN_SIZE(sizeof(struct udp_pcb)),
MEM_ALIGN_SIZE(sizeof(struct tcp_pcb)),
MEM_ALIGN_SIZE(sizeof(struct tcp_pcb_listen)),
MEM_ALIGN_SIZE(sizeof(struct tcp_seg)),
MEM_ALIGN_SIZE(sizeof(struct netbuf)),
MEM_ALIGN_SIZE(sizeof(struct netconn)),
MEM_ALIGN_SIZE(sizeof(struct api_msg)),
MEM_ALIGN_SIZE(sizeof(struct tcpip_msg)),
MEM_ALIGN_SIZE(sizeof(struct sys_timeo))
};
static const u16_t memp_num[MEMP_MAX] = {
MEMP_NUM_PBUF,
MEMP_NUM_RAW_PCB,
MEMP_NUM_UDP_PCB,
MEMP_NUM_TCP_PCB,
MEMP_NUM_TCP_PCB_LISTEN,
MEMP_NUM_TCP_SEG,
MEMP_NUM_NETBUF,
MEMP_NUM_NETCONN,
MEMP_NUM_API_MSG,
MEMP_NUM_TCPIP_MSG,
MEMP_NUM_SYS_TIMEOUT
};
#define MEMP_TYPE_SIZE(qty, type) \
((qty) * (MEMP_SIZE + MEM_ALIGN_SIZE(sizeof(type))))
static u8_t memp_memory[MEM_ALIGNMENT - 1 +
MEMP_TYPE_SIZE(MEMP_NUM_PBUF, struct pbuf) +
MEMP_TYPE_SIZE(MEMP_NUM_RAW_PCB, struct raw_pcb) +
MEMP_TYPE_SIZE(MEMP_NUM_UDP_PCB, struct udp_pcb) +
MEMP_TYPE_SIZE(MEMP_NUM_TCP_PCB, struct tcp_pcb) +
MEMP_TYPE_SIZE(MEMP_NUM_TCP_PCB_LISTEN, struct tcp_pcb_listen) +
MEMP_TYPE_SIZE(MEMP_NUM_TCP_SEG, struct tcp_seg) +
MEMP_TYPE_SIZE(MEMP_NUM_NETBUF, struct netbuf) +
MEMP_TYPE_SIZE(MEMP_NUM_NETCONN, struct netconn) +
MEMP_TYPE_SIZE(MEMP_NUM_API_MSG, struct api_msg) +
MEMP_TYPE_SIZE(MEMP_NUM_TCPIP_MSG, struct tcpip_msg) +
MEMP_TYPE_SIZE(MEMP_NUM_SYS_TIMEOUT, struct sys_timeo)];
#if !SYS_LIGHTWEIGHT_PROT
static sys_sem_t mutex;
#endif
#if MEMP_SANITY_CHECK
static int
memp_sanity(void)
{
s16_t i, c;
struct memp *m, *n;
for (i = 0; i < MEMP_MAX; i++) {
for (m = memp_tab[i]; m != NULL; m = m->next) {
c = 1;
for (n = memp_tab[i]; n != NULL; n = n->next) {
if (n == m && --c < 0) {
return 0; /* LW was: abort(); */
}
}
}
}
return 1;
}
#endif /* MEMP_SANITY_CHECK*/
void
memp_init(void)
{
struct memp *memp;
u16_t i, j;
#if MEMP_STATS
for (i = 0; i < MEMP_MAX; ++i) {
lwip_stats.memp[i].used = lwip_stats.memp[i].max =
lwip_stats.memp[i].err = 0;
lwip_stats.memp[i].avail = memp_num[i];
}
#endif /* MEMP_STATS */
memp = MEM_ALIGN(memp_memory);
for (i = 0; i < MEMP_MAX; ++i) {
memp_tab[i] = NULL;
for (j = 0; j < memp_num[i]; ++j) {
memp->next = memp_tab[i];
memp_tab[i] = memp;
memp = (struct memp *)((u8_t *)memp + MEMP_SIZE + memp_sizes[i]);
}
}
#if !SYS_LIGHTWEIGHT_PROT
mutex = sys_sem_new(1);
#endif
}
void *
memp_malloc(memp_t type)
{
struct memp *memp;
void *mem;
#if SYS_LIGHTWEIGHT_PROT
SYS_ARCH_DECL_PROTECT(old_level);
#endif
LWIP_ASSERT("memp_malloc: type < MEMP_MAX", type < MEMP_MAX);
#if SYS_LIGHTWEIGHT_PROT
SYS_ARCH_PROTECT(old_level);
#else /* SYS_LIGHTWEIGHT_PROT */
sys_sem_wait(mutex);
#endif /* SYS_LIGHTWEIGHT_PROT */
memp = memp_tab[type];
if (memp != NULL) {
memp_tab[type] = memp->next;
memp->next = NULL;
#if MEMP_STATS
++lwip_stats.memp[type].used;
if (lwip_stats.memp[type].used > lwip_stats.memp[type].max) {
lwip_stats.memp[type].max = lwip_stats.memp[type].used;
}
#endif /* MEMP_STATS */
mem = (u8_t *)memp + MEMP_SIZE;
LWIP_ASSERT("memp_malloc: memp properly aligned",
((mem_ptr_t)memp % MEM_ALIGNMENT) == 0);
} else {
LWIP_DEBUGF(MEMP_DEBUG | 2, ("memp_malloc: out of memory in pool %"S16_F"\n", type));
#if MEMP_STATS
++lwip_stats.memp[type].err;
#endif /* MEMP_STATS */
mem = NULL;
}
#if SYS_LIGHTWEIGHT_PROT
SYS_ARCH_UNPROTECT(old_level);
#else /* SYS_LIGHTWEIGHT_PROT */
sys_sem_signal(mutex);
#endif /* SYS_LIGHTWEIGHT_PROT */
return mem;
}
void
memp_free(memp_t type, void *mem)
{
struct memp *memp;
#if SYS_LIGHTWEIGHT_PROT
SYS_ARCH_DECL_PROTECT(old_level);
#endif /* SYS_LIGHTWEIGHT_PROT */
if (mem == NULL) {
return;
}
memp = (struct memp *)((u8_t *)mem - MEMP_SIZE);
#if SYS_LIGHTWEIGHT_PROT
SYS_ARCH_PROTECT(old_level);
#else /* SYS_LIGHTWEIGHT_PROT */
sys_sem_wait(mutex);
#endif /* SYS_LIGHTWEIGHT_PROT */
#if MEMP_STATS
lwip_stats.memp[type].used--;
#endif /* MEMP_STATS */
memp->next = memp_tab[type];
memp_tab[type] = memp;
#if MEMP_SANITY_CHECK
LWIP_ASSERT("memp sanity", memp_sanity());
#endif
#if SYS_LIGHTWEIGHT_PROT
SYS_ARCH_UNPROTECT(old_level);
#else /* SYS_LIGHTWEIGHT_PROT */
sys_sem_signal(mutex);
#endif /* SYS_LIGHTWEIGHT_PROT */
}
| zz314326255--adkping | iNEMO-accessory/firmware/FreeRTOSv7.0.2/Demo/Common/ethernet/lwIP/core/memp.c | C | oos | 6,773 |