Unverified Commit 67027c0d authored by Marcel Stör's avatar Marcel Stör Committed by GitHub
Browse files

Merge pull request #2340 from nodemcu/dev

2.2 master snap
parents 5073c199 18f33f5f
......@@ -2,7 +2,8 @@
* \file version.h
*
* \brief Run-time version information
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
......@@ -38,17 +39,17 @@
* Major, Minor, Patchlevel
*/
#define MBEDTLS_VERSION_MAJOR 2
#define MBEDTLS_VERSION_MINOR 2
#define MBEDTLS_VERSION_PATCH 1
#define MBEDTLS_VERSION_MINOR 7
#define MBEDTLS_VERSION_PATCH 0
/**
* The single version number has the following structure:
* MMNNPP00
* Major version | Minor version | Patch version
*/
#define MBEDTLS_VERSION_NUMBER 0x02020100
#define MBEDTLS_VERSION_STRING "2.2.1"
#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.2.1"
#define MBEDTLS_VERSION_NUMBER 0x02070000
#define MBEDTLS_VERSION_STRING "2.7.0"
#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.7.0"
#if defined(MBEDTLS_VERSION_C)
......
......@@ -2,7 +2,8 @@
* \file x509.h
*
* \brief X.509 generic defines and structures
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
......@@ -76,6 +77,7 @@
#define MBEDTLS_ERR_X509_ALLOC_FAILED -0x2880 /**< Allocation of memory failed. */
#define MBEDTLS_ERR_X509_FILE_IO_ERROR -0x2900 /**< Read/write of file failed. */
#define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL -0x2980 /**< Destination buffer is too small. */
#define MBEDTLS_ERR_X509_FATAL_ERROR -0x3000 /**< A fatal error occured, eg the chain is too long or the vrfy callback failed. */
/* \} name */
/**
......@@ -157,7 +159,7 @@
#define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY (1 << 13)
#define MBEDTLS_X509_EXT_FRESHEST_CRL (1 << 14)
#define MBEDTLS_X509_EXT_NS_CERT_TYPE (1 << 16) /* Parsed (and then ?) */
#define MBEDTLS_X509_EXT_NS_CERT_TYPE (1 << 16)
/*
* Storage format identifiers
......@@ -246,12 +248,12 @@ int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *se
* \note Intended usage is "if( is_past( valid_to ) ) ERROR".
* Hence the return value of 1 if on internal errors.
*
* \param time mbedtls_x509_time to check
* \param to mbedtls_x509_time to check
*
* \return 1 if the given time is in the past or an error occured,
* 0 otherwise.
*/
int mbedtls_x509_time_is_past( const mbedtls_x509_time *time );
int mbedtls_x509_time_is_past( const mbedtls_x509_time *to );
/**
* \brief Check a given mbedtls_x509_time against the system time
......@@ -260,12 +262,12 @@ int mbedtls_x509_time_is_past( const mbedtls_x509_time *time );
* \note Intended usage is "if( is_future( valid_from ) ) ERROR".
* Hence the return value of 1 if on internal errors.
*
* \param time mbedtls_x509_time to check
* \param from mbedtls_x509_time to check
*
* \return 1 if the given time is in the future or an error occured,
* 0 otherwise.
*/
int mbedtls_x509_time_is_future( const mbedtls_x509_time *time );
int mbedtls_x509_time_is_future( const mbedtls_x509_time *from );
/**
* \brief Checkup routine
......@@ -294,7 +296,7 @@ int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x50
mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
void **sig_opts );
int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
mbedtls_x509_time *time );
mbedtls_x509_time *t );
int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *serial );
int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,
......
......@@ -2,7 +2,8 @@
* \file x509_crl.h
*
* \brief X.509 certificate revocation list parsing
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
......
......@@ -2,7 +2,8 @@
* \file x509_crt.h
*
* \brief X.509 certificate parsing and writing
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
......@@ -120,6 +121,10 @@ mbedtls_x509_crt_profile;
#define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 32
#define MBEDTLS_X509_RFC5280_UTC_TIME_LEN 15
#if !defined( MBEDTLS_X509_MAX_FILE_PATH_LEN )
#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512
#endif
/**
* Container for writing a certificate (CRT)
*/
......@@ -263,7 +268,13 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
*
* All flags left after returning from the callback
* are also returned to the application. The function should
* return 0 for anything but a fatal error.
* return 0 for anything (including invalid certificates)
* other than fatal error, as a non-zero return code
* immediately aborts the verification process. For fatal
* errors, a specific error code should be used (different
* from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not
* be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR
* can be used if no better code is available.
*
* \note In case verification failed, the results can be displayed
* using \c mbedtls_x509_crt_verify_info()
......@@ -271,21 +282,27 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
* \note Same as \c mbedtls_x509_crt_verify_with_profile() with the
* default security profile.
*
* \param crt a certificate to be verified
* \param trust_ca the trusted CA chain
* \param ca_crl the CRL chain for trusted CA's
* \note It is your responsibility to provide up-to-date CRLs for
* all trusted CAs. If no CRL is provided for the CA that was
* used to sign the certificate, CRL verification is skipped
* silently, that is *without* setting any flag.
*
* \param crt a certificate (chain) to be verified
* \param trust_ca the list of trusted CAs
* \param ca_crl the list of CRLs for trusted CAs (see note above)
* \param cn expected Common Name (can be set to
* NULL if the CN must not be verified)
* \param flags result of the verification
* \param f_vrfy verification function
* \param p_vrfy verification parameter
*
* \return 0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
* in which case *flags will have one or more
* MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags
* set,
* or another error in case of a fatal error encountered
* during the verification process.
* \return 0 (and flags set to 0) if the chain was verified and valid,
* MBEDTLS_ERR_X509_CERT_VERIFY_FAILED if the chain was verified
* but found to be invalid, in which case *flags will have one
* or more MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX
* flags set, or another error (and flags set to 0xffffffff)
* in case of a fatal error encountered during the
* verification process.
*/
int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
......@@ -304,9 +321,9 @@ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
* for ECDSA) apply to all certificates: trusted root,
* intermediate CAs if any, and end entity certificate.
*
* \param crt a certificate to be verified
* \param trust_ca the trusted CA chain
* \param ca_crl the CRL chain for trusted CA's
* \param crt a certificate (chain) to be verified
* \param trust_ca the list of trusted CAs
* \param ca_crl the list of CRLs for trusted CAs
* \param profile security profile for verification
* \param cn expected Common Name (can be set to
* NULL if the CN must not be verified)
......@@ -357,10 +374,11 @@ int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
/**
* \brief Check usage of certificate against extentedJeyUsage.
* \brief Check usage of certificate against extendedKeyUsage.
*
* \param crt Leaf certificate used.
* \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or MBEDTLS_OID_CLIENT_AUTH).
* \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or
* MBEDTLS_OID_CLIENT_AUTH).
* \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
*
* \return 0 if this use of the certificate is allowed,
......@@ -371,7 +389,7 @@ int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
const char *usage_oid,
size_t usage_len );
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) */
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/**
......
......@@ -2,7 +2,8 @@
* \file x509_csr.h
*
* \brief X.509 certificate signing request parsing and writing
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
......@@ -83,6 +84,8 @@ mbedtls_x509write_csr;
/**
* \brief Load a Certificate Signing Request (CSR) in DER format
*
* \note CSR attributes (if any) are currently silently ignored.
*
* \param csr CSR context to fill
* \param buf buffer holding the CRL data
* \param buflen size of the buffer
......@@ -95,6 +98,8 @@ int mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr,
/**
* \brief Load a Certificate Signing Request (CSR), DER or PEM format
*
* \note See notes for \c mbedtls_x509_csr_parse_der()
*
* \param csr CSR context to fill
* \param buf buffer holding the CRL data
* \param buflen size of the buffer
......@@ -108,6 +113,8 @@ int mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, siz
/**
* \brief Load a Certificate Signing Request (CSR)
*
* \note See notes for \c mbedtls_x509_csr_parse()
*
* \param csr CSR context to fill
* \param path filename to read the CSR from
*
......@@ -276,7 +283,7 @@ int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, s
*
* \note f_rng may be NULL if RSA is used for signature and the
* signature is made offline (otherwise f_rng is desirable
* for couermeasures against timing attacks).
* for countermeasures against timing attacks).
* ECDSA signatures always require a non-NULL f_rng.
*/
int mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,
......
......@@ -2,7 +2,8 @@
* \file xtea.h
*
* \brief XTEA block cipher (32-bit)
*
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
......@@ -36,6 +37,7 @@
#define MBEDTLS_XTEA_DECRYPT 0
#define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH -0x0028 /**< The data input has an invalid length. */
#define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED -0x0029 /**< XTEA hardware accelerator failed. */
#if !defined(MBEDTLS_XTEA_ALT)
// Regular implementation
......
......@@ -187,8 +187,9 @@
#define CPU_BOOTUP_MHZ 52
#ifdef RTC_DEBUG_ENABLED
#warn this does not really work....
#define RTC_DBG(...) do { if (rtc_dbg_enabled == 'R') { dbg_printf(__VA_ARGS__); } } while (0)
static bool rtc_dbg_enabled;
static char rtc_dbg_enabled;
#define RTC_DBG_ENABLED() rtc_dbg_enabled = 'R'
#define RTC_DBG_NOT_ENABLED() rtc_dbg_enabled = 0
#else
......@@ -197,6 +198,8 @@ static bool rtc_dbg_enabled;
#define RTC_DBG_NOT_ENABLED()
#endif
#define NOINIT_ATTR __attribute__((section(".noinit")))
// RTCTIME storage
#define RTC_TIME_MAGIC_POS (RTC_TIME_BASE+0)
#define RTC_CYCLEOFFSETL_POS (RTC_TIME_BASE+1)
......@@ -210,18 +213,18 @@ static bool rtc_dbg_enabled;
//#define RTC_LASTTODUS_POS (RTC_TIME_BASE+9)
#define RTC_USRATE_POS (RTC_TIME_BASE+8)
static uint32_t rtc_time_magic;
static uint64_t rtc_cycleoffset;
static uint32_t rtc_lastsourceval;
static uint32_t rtc_sourcecycleunits;
static uint32_t rtc_calibration;
static uint32_t rtc_sleeptotalus;
static uint32_t rtc_sleeptotalcycles;
static uint64_t rtc_usatlastrate;
static uint64_t rtc_rateadjustedus;
static uint32_t rtc_todoffsetus;
static uint32_t rtc_lasttodus;
static uint32_t rtc_usrate;
NOINIT_ATTR uint32_t rtc_time_magic;
NOINIT_ATTR uint64_t rtc_cycleoffset;
NOINIT_ATTR uint32_t rtc_lastsourceval;
NOINIT_ATTR uint32_t rtc_sourcecycleunits;
NOINIT_ATTR uint32_t rtc_calibration;
NOINIT_ATTR uint32_t rtc_sleeptotalus;
NOINIT_ATTR uint32_t rtc_sleeptotalcycles;
NOINIT_ATTR uint64_t rtc_usatlastrate;
NOINIT_ATTR uint64_t rtc_rateadjustedus;
NOINIT_ATTR uint32_t rtc_todoffsetus;
NOINIT_ATTR uint32_t rtc_lasttodus;
NOINIT_ATTR uint32_t rtc_usrate;
struct rtc_timeval
......@@ -503,11 +506,6 @@ extern void rtc_time_enter_deep_sleep_final(void);
static void rtc_time_enter_deep_sleep_us(uint32_t us)
{
if (rtc_time_check_wake_magic())
rtc_time_set_sleep_magic();
else
bbram_save();
rtc_reg_write(0,0);
rtc_reg_write(0,rtc_reg_read(0)&0xffffbfff);
rtc_reg_write(0,rtc_reg_read(0)|0x30);
......@@ -533,6 +531,11 @@ static void rtc_time_enter_deep_sleep_us(uint32_t us)
uint32_t cycles=rtc_time_us_to_ticks(us);
rtc_time_add_sleep_tracking(us,cycles);
if (rtc_time_check_wake_magic())
rtc_time_set_sleep_magic();
else
bbram_save();
rtc_reg_write(RTC_TARGET_ADDR,rtc_time_read_raw()+cycles);
rtc_reg_write(0x9c,17);
rtc_reg_write(0xa0,3);
......@@ -744,17 +747,15 @@ static void rtc_time_register_bootup(void)
if (reset_reason!=2) // This was *not* a proper wakeup from a deep sleep. All our time keeping is f*cked!
rtc_time_reset(erase_calibration); // Possibly keep the calibration, it should still be good
rtc_time_select_ccount_source(CPU_BOOTUP_MHZ,true);
rtc_rateadjustedus = rtc_usatlastrate = rtc_time_get_now_us_adjusted();
rtc_todoffsetus = 0;
rtc_rateadjustedus = rtc_usatlastrate = rtc_time_get_now_us_adjusted();
RTC_DBG_ENABLED();
return;
}
if (rtc_time_check_magic())
{
// We did not go to sleep properly. All our time keeping is f*cked!
rtc_time_reset(erase_calibration); // Possibly keep the calibration, it should still be good
}
RTC_DBG_ENABLED();
}
......@@ -778,6 +779,10 @@ static inline void rtc_time_prepare(void)
rtc_time_select_frc2_source();
}
static int32_t rtc_time_adjust_delta_by_rate(int32_t delta) {
return (delta * ((1ull << 32) + (int) rtc_usrate)) >> 32;
}
static uint64_t rtc_time_adjust_us_by_rate(uint64_t us, int force) {
uint64_t usoff = us - rtc_usatlastrate;
uint64_t usadj = (usoff * ((1ull << 32) + (int) rtc_usrate)) >> 32;
......@@ -856,7 +861,8 @@ static void rtc_time_settimeofday(const struct rtc_timeval* tv)
// calibrate sleep period based on difference between expected time and actual time
if (sleep_us>0 && sleep_us<0xffffffff &&
sleep_cycles>0 && sleep_cycles<0xffffffff)
sleep_cycles>0 && sleep_cycles<0xffffffff &&
tv->tv_sec)
{
uint64_t actual_sleep_us=sleep_us-diff_us;
uint32_t cali=(actual_sleep_us<<12)/sleep_cycles;
......@@ -872,14 +878,15 @@ static void rtc_time_settimeofday(const struct rtc_timeval* tv)
rtc_usrate = 0;
// Deal with time adjustment if necessary
if (diff_us>0) // Time went backwards. Avoid that....
if (diff_us>0 && tv->tv_sec) // Time went backwards. Avoid that....
{
if (diff_us>0xffffffffULL)
diff_us=0xffffffffULL;
now_ntp_us+=diff_us;
}
else
} else {
diff_us=0;
}
rtc_todoffsetus = diff_us;
uint32_t now_s=now_ntp_us/1000000;
......
......@@ -31,7 +31,7 @@
#if !defined(ESPCONN_MBEDTLS)
#include "mbedtls/net.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/entropy.h"
......
#define FRAME_TYPE_MANAGEMENT 0
#define FRAME_TYPE_CONTROL 1
#define FRAME_TYPE_DATA 2
#define FRAME_SUBTYPE_ASSOC_REQUEST 0x00
#define FRAME_SUBTYPE_ASSOC_RESPONSE 0x01
#define FRAME_SUBTYPE_REASSOC_REQUEST 0x02
#define FRAME_SUBTYPE_REASSOC_RESPONSE 0x03
#define FRAME_SUBTYPE_PROBE_REQUEST 0x04
#define FRAME_SUBTYPE_PROBE_RESPONSE 0x05
#define FRAME_SUBTYPE_BEACON 0x08
#define FRAME_SUBTYPE_ATIM 0x09
#define FRAME_SUBTYPE_DISASSOCIATION 0x0a
#define FRAME_SUBTYPE_AUTHENTICATION 0x0b
#define FRAME_SUBTYPE_DEAUTHENTICATION 0x0c
#define FRAME_SUBTYPE_DATA 0x14
typedef struct framectrl_80211
{
//buf[0]
u8 Protocol:2;
u8 Type:2;
u8 Subtype:4;
//buf[1]
u8 ToDS:1;
u8 FromDS:1;
u8 MoreFlag:1;
u8 Retry:1;
u8 PwrMgmt:1;
u8 MoreData:1;
u8 Protectedframe:1;
u8 Order:1;
} framectrl_80211,*lpframectrl_80211;
typedef struct management_80211
{
struct framectrl_80211 framectrl;
uint16 duration;
uint8 rdaddr[6];
uint8 tsaddr[6];
uint8 bssid[6];
uint16 number;
} management_request_t;
typedef struct
{
management_request_t hdr;
uint8 timestamp[8];
uint16 beacon_interval;
uint16 capability_info;
} wifi_beacon_t;
typedef struct tagged_parameter
{
/* SSID parameter */
uint8 tag_number;
uint8 tag_length;
} tagged_parameter, *ptagged_parameter;
struct RxControl {
signed rssi:8;//表示该包的信号强度
unsigned rate:4;
unsigned is_group:1;
unsigned:1;
unsigned sig_mode:2;//表示该包是否是11n的包,0表示非11n,非0表示11n
unsigned legacy_length:12;//如果不是11n的包,它表示包的长度
unsigned damatch0:1;
unsigned damatch1:1;
unsigned bssidmatch0:1;
unsigned bssidmatch1:1;
unsigned MCS:7;//如果是11n的包,它表示包的调制编码序列,有效值:0-76
unsigned CWB:1;//如果是11n的包,它表示是否为HT40的包
unsigned HT_length:16;//如果是11n的包,它表示包的长度
unsigned Smoothing:1;
unsigned Not_Sounding:1;
unsigned:1;
unsigned Aggregation:1;
unsigned STBC:2;
unsigned FEC_CODING:1;//如果是11n的包,它表示是否为LDPC的包
unsigned SGI:1;
unsigned rxend_state:8;
unsigned ampdu_cnt:8;
unsigned channel:4;//表示该包所在的信道
unsigned:12;
};
struct sniffer_buf2{
struct RxControl rx_ctrl;
u8 buf[112];//包含ieee80211包头
u16 cnt;//包的个数
u16 len[1];//包的长度
};
struct sniffer_buf{
struct RxControl rx_ctrl;
u8 buf[48];//包含ieee80211包头
u16 cnt;//包的个数
u16 len[1];//包的长度
};
#include "c_types.h"
#include "user_config.h"
#undef MBEDTLS_HAVE_ASM
#undef MBEDTLS_HAVE_SSE2
#define MBEDTLS_HAVE_TIME
#define MBEDTLS_HAVE_TIME_DATE
// These are disabled until we have a real, working RTC-based gettimeofday
#undef MBEDTLS_HAVE_TIME
#undef MBEDTLS_HAVE_TIME_DATE
#undef MBEDTLS_PLATFORM_MEMORY
#define MBEDTLS_PLATFORM_MEMORY
#undef MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
#undef MBEDTLS_PLATFORM_EXIT_ALT
......@@ -126,8 +129,6 @@
#define MBEDTLS_SHA256_SMALLER
#undef MBEDTLS_SSL_AEAD_RANDOM_IV
#define MBEDTLS_SSL_ALL_ALERT_MESSAGES
#undef MBEDTLS_SSL_DEBUG_ALL
......@@ -149,13 +150,13 @@
#define MBEDTLS_SSL_PROTO_TLS1
#define MBEDTLS_SSL_PROTO_TLS1_1
#define MBEDTLS_SSL_PROTO_TLS1_2
#define MBEDTLS_SSL_PROTO_DTLS
#undef MBEDTLS_SSL_PROTO_DTLS
#define MBEDTLS_SSL_ALPN
#define MBEDTLS_SSL_DTLS_ANTI_REPLAY
#define MBEDTLS_SSL_DTLS_HELLO_VERIFY
#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
#define MBEDTLS_SSL_DTLS_BADMAC_LIMIT
#undef MBEDTLS_SSL_DTLS_ANTI_REPLAY
#undef MBEDTLS_SSL_DTLS_HELLO_VERIFY
#undef MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
#undef MBEDTLS_SSL_DTLS_BADMAC_LIMIT
#define MBEDTLS_SSL_SESSION_TICKETS
#define MBEDTLS_SSL_EXPORT_KEYS
#define MBEDTLS_SSL_SERVER_NAME_INDICATION
......@@ -187,6 +188,7 @@
#define MBEDTLS_CCM_C
#undef MBEDTLS_CERTS_C
#define MBEDTLS_CIPHER_C
#define MBEDTLS_CMAC_C
#define MBEDTLS_CTR_DRBG_C
#undef MBEDTLS_DEBUG_C
#define MBEDTLS_DES_C
......@@ -260,13 +262,14 @@
//#define MBEDTLS_ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */
//#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */
//#define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /**< Default minimum number of bytes required for the hardware entropy source mbedtls_hardware_poll() before entropy is released */
//#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */
//#define MBEDTLS_PLATFORM_STD_MEM_HDR <stdlib.h> /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */
//#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< Default allocator to use, can be undefined */
//#define MBEDTLS_PLATFORM_STD_FREE free /**< Default free to use, can be undefined */
#define MBEDTLS_PLATFORM_STD_CALLOC pvPortCalloc /**< Default allocator to use, can be undefined */
#define MBEDTLS_PLATFORM_STD_FREE vPortFree /**< Default free to use, can be undefined */
//#define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use, can be undefined */
//#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be undefined */
//#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
//#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, can be undefined */
//#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use, can be undefined */
//#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use, can be undefined */
......@@ -278,19 +281,33 @@
//#define MBEDTLS_PLATFORM_CALLOC_MACRO calloc /**< Default allocator macro to use, can be undefined */
//#define MBEDTLS_PLATFORM_FREE_MACRO free /**< Default free macro to use, can be undefined */
//#define MBEDTLS_PLATFORM_EXIT_MACRO exit /**< Default exit macro to use, can be undefined */
//#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined */
//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to use, can be undefined */
//#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
//#define MBEDTLS_PLATFORM_FPRINTF_MACRO fprintf /**< Default fprintf macro to use, can be undefined */
//#define MBEDTLS_PLATFORM_PRINTF_MACRO printf /**< Default printf macro to use, can be undefined */
//#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf /**< Default snprintf macro to use, can be undefined */
#define MBEDTLS_PLATFORM_PRINTF_MACRO ets_printf /**< Default printf macro to use, can be undefined */
#define MBEDTLS_PLATFORM_SNPRINTF_MACRO ets_snprintf /**< Default snprintf macro to use, can be undefined */
#define MBEDTLS_PLATFORM_VSNPRINTF_MACRO ets_vsnprintf /**< Default vsnprintf macro to use, can be undefined */
//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */
//#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */
//#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /**< 1 day */
//#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */
#define MBEDTLS_SSL_MAX_CONTENT_LEN 4096 /**< Maxium fragment length in bytes, determines the size of each of the two internal I/O buffers */
#if 0
// dynamic buffer sizing with espconn_secure_set_size()
extern unsigned int max_content_len;
#define MBEDTLS_SSL_MAX_CONTENT_LEN max_content_len;
#else
// the current mbedtls integration doesn't allow to set the buffer size dynamically:
// MBEDTLS_SSL_MAX_FRAGMENT_LENGTH feature and dynamic sizing are mutually exclusive
// due to non-constant initializer element in app/mbedtls/library/ssl_tls.c:150
// the buffer size is hardcoded here and value is taken from SSL_BUFFER_SIZE (user_config.h)
#define MBEDTLS_SSL_MAX_CONTENT_LEN SSL_BUFFER_SIZE /**< Maxium fragment length in bytes, determines the size of each of the two internal I/O buffers */
#endif
//#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME 86400 /**< Lifetime of session tickets (if enabled) */
//#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */
//#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */
//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 3 /**< Maximum number of intermediate CAs in a verification chain. */
//#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 /**< Maximum length of a path/filename string in bytes including the null terminator character ('\0'). */
......@@ -23,9 +23,12 @@
//#define LUA_USE_MODULES_AM2320
//#define LUA_USE_MODULES_APA102
#define LUA_USE_MODULES_BIT
//#define LUA_USE_MODULES_BLOOM
//#define LUA_USE_MODULES_BMP085
//#define LUA_USE_MODULES_BME280
//#define LUA_USE_MODULES_BME680
//#define LUA_USE_MODULES_COAP
//#define LUA_USE_MODULES_COLOR_UTILS
//#define LUA_USE_MODULES_CRON
//#define LUA_USE_MODULES_CRYPTO
#define LUA_USE_MODULES_DHT
......@@ -35,6 +38,7 @@
#define LUA_USE_MODULES_FILE
//#define LUA_USE_MODULES_GDBSTUB
#define LUA_USE_MODULES_GPIO
//#define LUA_USE_MODULES_GPIO_PULSE
//#define LUA_USE_MODULES_HDC1080
//#define LUA_USE_MODULES_HMC5883L
//#define LUA_USE_MODULES_HTTP
......@@ -62,6 +66,7 @@
//#define LUA_USE_MODULES_SNTP
//#define LUA_USE_MODULES_SOMFY
#define LUA_USE_MODULES_SPI
//#define LUA_USE_MODULES_SQLITE3
//#define LUA_USE_MODULES_STRUCT
//#define LUA_USE_MODULES_SWITEC
// #define LUA_USE_MODULES_TCS34725
......@@ -74,9 +79,11 @@
//#define LUA_USE_MODULES_UCG
//#define LUA_USE_MODULES_WEBSOCKET
#define LUA_USE_MODULES_WIFI
//#define LUA_USE_MODULES_WIFI_MONITOR
//#define LUA_USE_MODULES_WPS
//#define LUA_USE_MODULES_WS2801
//#define LUA_USE_MODULES_WS2812
//#define LUA_USE_MODULES_WS2812_EFFECTS
//#define LUA_USE_MODULES_XPT2046
#endif /* LUA_CROSS_COMPILER */
......
#ifndef __USER_VERSION_H__
#define __USER_VERSION_H__
#define NODE_VERSION_MAJOR 2U
#define NODE_VERSION_MINOR 1U
#define NODE_VERSION_REVISION 0U
#define NODE_VERSION_INTERNAL 0U
#include "version.h" /* ESP firmware header */
#define NODE_VERSION_MAJOR ESP_SDK_VERSION_MAJOR
#define NODE_VERSION_MINOR ESP_SDK_VERSION_MINOR
#define NODE_VERSION_REVISION ESP_SDK_VERSION_PATCH
#define NODE_VERSION_INTERNAL 0
#define NODE_VERSION_STR(x) #x
#define NODE_VERSION_XSTR(x) NODE_VERSION_STR(x)
#define NODE_VERSION "NodeMCU " ESP_SDK_VERSION_STRING "." NODE_VERSION_XSTR(NODE_VERSION_INTERNAL)
#define NODE_VERSION "NodeMCU 2.1.0"
#ifndef BUILD_DATE
#define BUILD_DATE "unspecified"
#endif
......
......@@ -144,8 +144,11 @@ static void correctstack (lua_State *L, TValue *oldstack) {
void luaD_reallocstack (lua_State *L, int newsize) {
TValue *oldstack = L->stack;
int realsize = newsize + 1 + EXTRA_STACK;
int block_status = is_block_gc(L);
lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
set_block_gc(L); /* The GC MUST be blocked during stack reallocaiton */
luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue);
if (!block_status) unset_block_gc(L); /* Honour the previous block status */
L->stacksize = realsize;
L->stack_last = L->stack+newsize;
correctstack(L, oldstack);
......
......@@ -468,8 +468,11 @@ int lua_main (int argc, char **argv) {
void lua_handle_input (bool force)
{
if (gLoad.L && (force || readline (&gLoad)))
while (gLoad.L && (force || readline (&gLoad)))
{
dojob (&gLoad);
force = false;
}
}
void donejob(lua_Load *load){
......@@ -599,11 +602,12 @@ static bool readline(lua_Load *load){
{
/* Get a empty line, then go to get a new line */
c_puts(load->prmt);
continue;
} else {
load->done = 1;
need_dojob = true;
break;
}
continue;
}
/* other control character or not an acsii character */
......
......@@ -441,6 +441,7 @@ sint16 ICACHE_FLASH_ATTR espconn_recv(struct espconn *espconn, void *mem, size_t
espconn_msg *pnode = NULL;
bool value = false;
int bytes_used = 0;
struct tcp_pcb *tpcb = NULL;
if (espconn == NULL || mem == NULL || len == 0)
return ESPCONN_ARG;
......@@ -454,13 +455,15 @@ sint16 ICACHE_FLASH_ATTR espconn_recv(struct espconn *espconn, void *mem, size_t
len = bytes_used;
}
ringbuf_memcpy_from(mem, pnode->readbuf, len);
espconn_recv_unhold(pnode->pespconn);
tpcb = pnode->pcommon.pcb;
if (tpcb && tpcb->state == ESTABLISHED)
tcp_recved(pnode->pcommon.pcb, len);
return len;
} else {
return ESPCONN_OK;
}
} else{
return ESPCONN_OK;
return ESPCONN_MEM;
}
} else{
return ESPCONN_ARG;
......
......@@ -231,6 +231,10 @@ void ICACHE_FLASH_ATTR espconn_tcp_memp_free(espconn_msg *pmemp)
if (pmemp == NULL)
return;
/*Enable block option for fetches the data proactive*/
if (espconn_manual_recv_disabled(pmemp))
espconn_list_delete(&plink_active, pmemp);
if (pmemp->espconn_mode == ESPCONN_TCPSERVER_MODE){
if (pmemp->pespconn != NULL && pmemp->pespconn->proto.tcp != NULL)
os_free(pmemp->pespconn->proto.tcp);
......@@ -431,10 +435,12 @@ espconn_Task(os_event_t *events)
case SIG_ESPCONN_ERRER:
/*remove the node from the client's active connection list*/
espconn_list_delete(&plink_active, task_msg);
espconn_tcp_reconnect(task_msg);
if (espconn_manual_recv_enabled(task_msg))
espconn_list_delete(&plink_active, task_msg);
break;
case SIG_ESPCONN_CLOSE:
/*remove the node from the client's active connection list*/
if (espconn_manual_recv_enabled(task_msg))
espconn_list_delete(&plink_active, task_msg);
espconn_tcp_disconnect_successful(task_msg);
break;
......@@ -538,6 +544,66 @@ void ICACHE_FLASH_ATTR espconn_tcp_disconnect(espconn_msg *pdiscon,u8 type)
}
}
/******************************************************************************
* FunctionName : espconn_tcp_recv
* Description : Data has been received on this pcb.
* Parameters : arg -- Additional argument to pass to the callback function
* pcb -- The connection pcb which received data
* p -- The received data (or NULL when the connection has been closed!)
* err -- An error code if there has been an error receiving
* Returns : ERR_ABRT: if you have called tcp_abort from within the function!
*******************************************************************************/
static err_t ICACHE_FLASH_ATTR
espconn_tcp_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err)
{
espconn_msg *precv_cb = arg;
struct pbuf *pthis = NULL;
uint8_t *ring = NULL;
size_t bytes_used = 0;
tcp_arg(pcb, arg);
if (precv_cb->readbuf == NULL) {
precv_cb->readbuf = ringbuf_new(TCP_WND);
if (precv_cb->readbuf == NULL)
return ESPCONN_MEM;
}
if (err == ERR_OK) {
precv_cb->pcommon.recv_check = 0;
if (p != NULL) {
/*store the data to the adapter for application fetches it proactive*/
for (pthis = p; pthis != NULL ; pthis = pthis->next) {
ring = ringbuf_memcpy_into(precv_cb->readbuf, pthis->payload, pthis->len);
if (ring)
pbuf_free(pthis);
else
break;
}
bytes_used = ringbuf_bytes_used(precv_cb->readbuf);
/*switch the state of espconn for application process*/
precv_cb->pespconn->state = ESPCONN_READ;
precv_cb->pcommon.pcb = pcb;
if (precv_cb->pespconn->recv_callback != NULL) {
precv_cb->pespconn->recv_callback(precv_cb->pespconn, NULL, bytes_used);
}
/*switch the state of espconn for next packet copy*/
if (pcb->state == ESTABLISHED)
precv_cb->pespconn->state = ESPCONN_CONNECT;
} else {
if (precv_cb->preverse) {
espconn_server_close(precv_cb, pcb, 0);
} else {
espconn_client_close(precv_cb, pcb, 0);
}
}
}
return ERR_OK;
}
///////////////////////////////client function/////////////////////////////////
/******************************************************************************
* FunctionName : espconn_client_close
......@@ -933,6 +999,10 @@ espconn_client_connect(void *arg, struct tcp_pcb *tpcb, err_t err)
pcon->pespconn->proto.tcp->connect_callback(pcon->pespconn);
}
/*Enable block option for fetches the data proactive*/
if (espconn_manual_recv_disabled(pcon))
tcp_recv(tpcb, espconn_tcp_recv);
/*Enable keep alive option*/
if (espconn_keepalive_disabled(pcon))
espconn_keepalive_enable(tpcb);
......@@ -1358,6 +1428,10 @@ espconn_tcp_accept(void *arg, struct tcp_pcb *pcb, err_t err)
paccept->pespconn->proto.tcp->connect_callback(paccept->pespconn);
}
/*Enable block option for fetches the data proactive*/
if (espconn_manual_recv_disabled(paccept))
tcp_recv(pcb, espconn_tcp_recv);
/*Enable keep alive option*/
if (espconn_keepalive_disabled(paccept))
espconn_keepalive_enable(pcb);
......
......@@ -237,9 +237,10 @@ espconn_udp_sendto(void *arg, uint8 *psent, uint16 length)
if(wifi_get_opmode() == ESPCONN_AP_STA && default_interface == ESPCONN_AP_STA && sta_netif != NULL && ap_netif != NULL)
{
if(netif_is_up(sta_netif) && netif_is_up(ap_netif) && \
ip_addr_isbroadcast(&upcb->remote_ip, sta_netif) && \
ip_addr_isbroadcast(&upcb->remote_ip, ap_netif)) {
if( netif_is_up(sta_netif) && \
netif_is_up(ap_netif) && \
ip_addr_isbroadcast(&dst_ip, sta_netif) && \
ip_addr_isbroadcast(&dst_ip, ap_netif)) {
p_temp = pbuf_alloc(PBUF_TRANSPORT, datalen, PBUF_RAM);
if (pbuf_copy (p_temp,p) != ERR_OK) {
......
/**
* @file
* SNTP client module
*
* This is simple "SNTP" client for the lwIP raw API.
* It is a minimal implementation of SNTPv4 as specified in RFC 4330.
*
* For a list of some public NTP servers, see this link :
* http://support.ntp.org/bin/view/Servers/NTPPoolServers
*
* @todo:
* - set/change servers at runtime
* - complete SNTP_CHECK_RESPONSE checks 3 and 4
* - support broadcast/multicast mode?
*/
/*
* 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 (lwIP raw API part)
*/
#include "lwip/sntp.h"
#include "osapi.h"
#include "os_type.h"
#include "lwip/opt.h"
#include "lwip/timers.h"
#include "lwip/udp.h"
#include "lwip/dns.h"
#include "lwip/ip_addr.h"
#include "lwip/pbuf.h"
#include "lwip/app/time.h"
//#include <string.h>
#if LWIP_UDP
/**
* SNTP_DEBUG: Enable debugging for SNTP.
*/
#ifndef SNTP_DEBUG
#define SNTP_DEBUG LWIP_DBG_ON
#endif
/** SNTP server port */
#ifndef SNTP_PORT
#define SNTP_PORT 123
#endif
/** Set this to 1 to allow config of SNTP server(s) by DNS name */
#ifndef SNTP_SERVER_DNS
#define SNTP_SERVER_DNS 0
#endif
/** Handle support for more than one server via NTP_MAX_SERVERS,
* but catch legacy style of setting SNTP_SUPPORT_MULTIPLE_SERVERS, probably outside of this file
*/
#ifndef SNTP_SUPPORT_MULTIPLE_SERVERS
#if SNTP_MAX_SERVERS > 1
#define SNTP_SUPPORT_MULTIPLE_SERVERS 1
#else /* NTP_MAX_SERVERS > 1 */
#define SNTP_SUPPORT_MULTIPLE_SERVERS 0
#endif /* NTP_MAX_SERVERS > 1 */
#else /* SNTP_SUPPORT_MULTIPLE_SERVERS */
/* The developer has defined SNTP_SUPPORT_MULTIPLE_SERVERS, probably from old code */
#if SNTP_MAX_SERVERS <= 1
#error "SNTP_MAX_SERVERS needs to be defined to the max amount of servers if SNTP_SUPPORT_MULTIPLE_SERVERS is defined"
#endif /* SNTP_MAX_SERVERS <= 1 */
#endif /* SNTP_SUPPORT_MULTIPLE_SERVERS */
/** Sanity check:
* Define this to
* - 0 to turn off sanity checks (default; smaller code)
* - >= 1 to check address and port of the response packet to ensure the
* response comes from the server we sent the request to.
* - >= 2 to check returned Originate Timestamp against Transmit Timestamp
* sent to the server (to ensure response to older request).
* - >= 3 @todo: discard reply if any of the LI, Stratum, or Transmit Timestamp
* fields is 0 or the Mode field is not 4 (unicast) or 5 (broadcast).
* - >= 4 @todo: to check that the Root Delay and Root Dispersion fields are each
* greater than or equal to 0 and less than infinity, where infinity is
* currently a cozy number like one second. This check avoids using a
* server whose synchronization source has expired for a very long time.
*/
#ifndef SNTP_CHECK_RESPONSE
#define SNTP_CHECK_RESPONSE 0
#endif
/** According to the RFC, this shall be a random delay
* between 1 and 5 minutes (in milliseconds) to prevent load peaks.
* This can be defined to a random generation function,
* which must return the delay in milliseconds as u32_t.
* Turned off by default.
*/
#ifndef SNTP_STARTUP_DELAY
#define SNTP_STARTUP_DELAY 0
#endif
/** If you want the startup delay to be a function, define this
* to a function (including the brackets) and define SNTP_STARTUP_DELAY to 1.
*/
#ifndef SNTP_STARTUP_DELAY_FUNC
#define SNTP_STARTUP_DELAY_FUNC SNTP_STARTUP_DELAY
#endif
/** SNTP receive timeout - in milliseconds
* Also used as retry timeout - this shouldn't be too low.
* Default is 3 seconds.
*/
#ifndef SNTP_RECV_TIMEOUT
#define SNTP_RECV_TIMEOUT 3000
#endif
/** SNTP update delay - in milliseconds
* Default is 1 hour.
*/
#ifndef SNTP_UPDATE_DELAY
#define SNTP_UPDATE_DELAY 3600000
#endif
#if (SNTP_UPDATE_DELAY < 15000) && !SNTP_SUPPRESS_DELAY_CHECK
#error "SNTPv4 RFC 4330 enforces a minimum update time of 15 seconds!"
#endif
/** SNTP macro to change system time and/or the update the RTC clock */
#ifndef SNTP_SET_SYSTEM_TIME
#define SNTP_SET_SYSTEM_TIME(sec) ((void)sec)
#endif
/** SNTP macro to change system time including microseconds */
uint8 sntp_receive_time_size = 1;
#define SNTP_RECEIVE_TIME_SIZE sntp_receive_time_size
#define SNTP_SET_SYSTEM_TIME_US(sec, us) sntp_update_rtc(sec, us)
//#ifdef SNTP_SET_SYSTEM_TIME_US
//#define SNTP_SET_SYSTEM_TIME_US(sec, us) sntp_update_rtc(sec, us)
//#define SNTP_CALC_TIME_US 1
//#define SNTP_RECEIVE_TIME_SIZE 2
//#else
//#define SNTP_SET_SYSTEM_TIME_US(sec, us)
//#define SNTP_CALC_TIME_US 0
//#define SNTP_RECEIVE_TIME_SIZE sntp_receive_time_size
//#endif
/** SNTP macro to get system time, used with SNTP_CHECK_RESPONSE >= 2
* to send in request and compare in response.
*/
#ifndef SNTP_GET_SYSTEM_TIME
#define SNTP_GET_SYSTEM_TIME(sec, us) do { (sec) = 0; (us) = 0; } while(0)
#endif
/** Default retry timeout (in milliseconds) if the response
* received is invalid.
* This is doubled with each retry until SNTP_RETRY_TIMEOUT_MAX is reached.
*/
#ifndef SNTP_RETRY_TIMEOUT
#define SNTP_RETRY_TIMEOUT SNTP_RECV_TIMEOUT
#endif
/** Maximum retry timeout (in milliseconds). */
#ifndef SNTP_RETRY_TIMEOUT_MAX
#define SNTP_RETRY_TIMEOUT_MAX (SNTP_RETRY_TIMEOUT * 10)
#endif
/** Increase retry timeout with every retry sent
* Default is on to conform to RFC.
*/
#ifndef SNTP_RETRY_TIMEOUT_EXP
#define SNTP_RETRY_TIMEOUT_EXP 1
#endif
/* the various debug levels for this file */
#define SNTP_DEBUG_TRACE (SNTP_DEBUG | LWIP_DBG_TRACE)
#define SNTP_DEBUG_STATE (SNTP_DEBUG | LWIP_DBG_STATE)
#define SNTP_DEBUG_WARN (SNTP_DEBUG | LWIP_DBG_LEVEL_WARNING)
#define SNTP_DEBUG_WARN_STATE (SNTP_DEBUG | LWIP_DBG_LEVEL_WARNING | LWIP_DBG_STATE)
#define SNTP_DEBUG_SERIOUS (SNTP_DEBUG | LWIP_DBG_LEVEL_SERIOUS)
#define SNTP_ERR_KOD 1
/* SNTP protocol defines */
#define SNTP_MSG_LEN 48
#define SNTP_OFFSET_LI_VN_MODE 0
#define SNTP_LI_MASK 0xC0
#define SNTP_LI_NO_WARNING 0x00
#define SNTP_LI_LAST_MINUTE_61_SEC 0x01
#define SNTP_LI_LAST_MINUTE_59_SEC 0x02
#define SNTP_LI_ALARM_CONDITION 0x03 /* (clock not synchronized) */
#define SNTP_VERSION_MASK 0x38
#define SNTP_VERSION (4/* NTP Version 4*/<<3)
#define SNTP_MODE_MASK 0x07
#define SNTP_MODE_CLIENT 0x03
#define SNTP_MODE_SERVER 0x04
#define SNTP_MODE_BROADCAST 0x05
#define SNTP_OFFSET_STRATUM 1
#define SNTP_STRATUM_KOD 0x00
#define SNTP_OFFSET_ORIGINATE_TIME 24
#define SNTP_OFFSET_RECEIVE_TIME 32
#define SNTP_OFFSET_TRANSMIT_TIME 40
/* number of seconds between 1900 and 1970 */
#define DIFF_SEC_1900_1970 (2208988800UL)
/**
* SNTP packet format (without optional fields)
* Timestamps are coded as 64 bits:
* - 32 bits seconds since Jan 01, 1970, 00:00
* - 32 bits seconds fraction (0-padded)
* For future use, if the MSB in the seconds part is set, seconds are based
* on Feb 07, 2036, 06:28:16.
*/
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
#define PACK_STRUCT_FLD_8 PACK_STRUCT_FIELD
struct sntp_msg {
PACK_STRUCT_FLD_8(u8_t li_vn_mode);
PACK_STRUCT_FLD_8(u8_t stratum);
PACK_STRUCT_FLD_8(u8_t poll);
PACK_STRUCT_FLD_8(u8_t precision);
PACK_STRUCT_FIELD(u32_t root_delay);
PACK_STRUCT_FIELD(u32_t root_dispersion);
PACK_STRUCT_FIELD(u32_t reference_identifier);
PACK_STRUCT_FIELD(u32_t reference_timestamp[2]);
PACK_STRUCT_FIELD(u32_t originate_timestamp[2]);
PACK_STRUCT_FIELD(u32_t receive_timestamp[2]);
PACK_STRUCT_FIELD(u32_t transmit_timestamp[2]);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/* function prototypes */
static void sntp_request(void *arg);
/** The UDP pcb used by the SNTP client */
static struct udp_pcb* sntp_pcb;
sint8 time_zone = 8;
/** Names/Addresses of servers */
struct sntp_server {
#if SNTP_SERVER_DNS
char* name;
#endif /* SNTP_SERVER_DNS */
ip_addr_t addr;
};
static struct sntp_server sntp_servers[SNTP_MAX_SERVERS];
static u8_t sntp_set_servers_from_dhcp;
#if SNTP_SUPPORT_MULTIPLE_SERVERS
/** The currently used server (initialized to 0) */
static u8_t sntp_current_server;
#else /* SNTP_SUPPORT_MULTIPLE_SERVERS */
#define sntp_current_server 0
#endif /* SNTP_SUPPORT_MULTIPLE_SERVERS */
#if SNTP_RETRY_TIMEOUT_EXP
#define SNTP_RESET_RETRY_TIMEOUT() sntp_retry_timeout = SNTP_RETRY_TIMEOUT
/** Retry time, initialized with SNTP_RETRY_TIMEOUT and doubled with each retry. */
static u32_t sntp_retry_timeout;
#else /* SNTP_RETRY_TIMEOUT_EXP */
#define SNTP_RESET_RETRY_TIMEOUT()
#define sntp_retry_timeout SNTP_RETRY_TIMEOUT
#endif /* SNTP_RETRY_TIMEOUT_EXP */
#if SNTP_CHECK_RESPONSE >= 1
/** Saves the last server address to compare with response */
static ip_addr_t sntp_last_server_address;
#endif /* SNTP_CHECK_RESPONSE >= 1 */
#if SNTP_CHECK_RESPONSE >= 2
/** Saves the last timestamp sent (which is sent back by the server)
* to compare against in response */
static u32_t sntp_last_timestamp_sent[2];
#endif /* SNTP_CHECK_RESPONSE >= 2 */
//uint32 current_stamp_1 = 0;
//uint32 current_stamp_2 = 0;
static bool sntp_time_flag = false;
static uint32 sntp_update_delay = SNTP_UPDATE_DELAY;
static uint32 realtime_stamp = 0;
LOCAL os_timer_t sntp_timer;
/*****************************************/
#define SECSPERMIN 60L
#define MINSPERHOUR 60L
#define HOURSPERDAY 24L
#define SECSPERHOUR (SECSPERMIN * MINSPERHOUR)
#define SECSPERDAY (SECSPERHOUR * HOURSPERDAY)
#define DAYSPERWEEK 7
#define MONSPERYEAR 12
#define YEAR_BASE 1900
#define EPOCH_YEAR 1970
#define EPOCH_WDAY 4
#define EPOCH_YEARS_SINCE_LEAP 2
#define EPOCH_YEARS_SINCE_CENTURY 70
#define EPOCH_YEARS_SINCE_LEAP_CENTURY 370
#define isleap(y) ((((y) % 4) == 0 && ((y) % 100) != 0) || ((y) % 400) == 0)
int __tznorth;
int __tzyear;
char reult[100];
static const int mon_lengths[2][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
} ;
static const int year_lengths[2] = {
365,
366
} ;
struct tm
{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
struct tm res_buf;
typedef struct __tzrule_struct
{
char ch;
int m;
int n;
int d;
int s;
time_t change;
int offset;
} __tzrule_type;
__tzrule_type sntp__tzrule[2];
struct tm * ICACHE_FLASH_ATTR
sntp_mktm_r(const time_t * tim_p ,struct tm *res ,int is_gmtime)
{
long days, rem;
time_t lcltime;
int i;
int y;
int yleap;
const int *ip;
/* base decision about std/dst time on current time */
lcltime = *tim_p;
days = ((long)lcltime) / SECSPERDAY;
rem = ((long)lcltime) % SECSPERDAY;
while (rem < 0)
{
rem += SECSPERDAY;
--days;
}
while (rem >= SECSPERDAY)
{
rem -= SECSPERDAY;
++days;
}
/* compute hour, min, and sec */
res->tm_hour = (int) (rem / SECSPERHOUR);
rem %= SECSPERHOUR;
res->tm_min = (int) (rem / SECSPERMIN);
res->tm_sec = (int) (rem % SECSPERMIN);
/* compute day of week */
if ((res->tm_wday = ((EPOCH_WDAY + days) % DAYSPERWEEK)) < 0)
res->tm_wday += DAYSPERWEEK;
/* compute year & day of year */
y = EPOCH_YEAR;
if (days >= 0)
{
for (;;)
{
yleap = isleap(y);
if (days < year_lengths[yleap])
break;
y++;
days -= year_lengths[yleap];
}
}
else
{
do
{
--y;
yleap = isleap(y);
days += year_lengths[yleap];
} while (days < 0);
}
res->tm_year = y - YEAR_BASE;
res->tm_yday = days;
ip = mon_lengths[yleap];
for (res->tm_mon = 0; days >= ip[res->tm_mon]; ++res->tm_mon)
days -= ip[res->tm_mon];
res->tm_mday = days + 1;
if (!is_gmtime)
{
int offset;
int hours, mins, secs;
// TZ_LOCK;
// if (_daylight)
// {
// if (y == __tzyear || __tzcalc_limits (y))
// res->tm_isdst = (__tznorth
// ? (*tim_p >= __tzrule[0].change && *tim_p < __tzrule[1].change)
// : (*tim_p >= __tzrule[0].change || *tim_p < __tzrule[1].change));
// else
// res->tm_isdst = -1;
// }
// else
res->tm_isdst = 0;
offset = (res->tm_isdst == 1 ? sntp__tzrule[1].offset : sntp__tzrule[0].offset);
hours = offset / SECSPERHOUR;
offset = offset % SECSPERHOUR;
mins = offset / SECSPERMIN;
secs = offset % SECSPERMIN;
res->tm_sec -= secs;
res->tm_min -= mins;
res->tm_hour -= hours;
if (res->tm_sec >= SECSPERMIN)
{
res->tm_min += 1;
res->tm_sec -= SECSPERMIN;
}
else if (res->tm_sec < 0)
{
res->tm_min -= 1;
res->tm_sec += SECSPERMIN;
}
if (res->tm_min >= MINSPERHOUR)
{
res->tm_hour += 1;
res->tm_min -= MINSPERHOUR;
}
else if (res->tm_min < 0)
{
res->tm_hour -= 1;
res->tm_min += MINSPERHOUR;
}
if (res->tm_hour >= HOURSPERDAY)
{
++res->tm_yday;
++res->tm_wday;
if (res->tm_wday > 6)
res->tm_wday = 0;
++res->tm_mday;
res->tm_hour -= HOURSPERDAY;
if (res->tm_mday > ip[res->tm_mon])
{
res->tm_mday -= ip[res->tm_mon];
res->tm_mon += 1;
if (res->tm_mon == 12)
{
res->tm_mon = 0;
res->tm_year += 1;
res->tm_yday = 0;
}
}
}
else if (res->tm_hour < 0)
{
res->tm_yday -= 1;
res->tm_wday -= 1;
if (res->tm_wday < 0)
res->tm_wday = 6;
res->tm_mday -= 1;
res->tm_hour += 24;
if (res->tm_mday == 0)
{
res->tm_mon -= 1;
if (res->tm_mon < 0)
{
res->tm_mon = 11;
res->tm_year -= 1;
res->tm_yday = 365 + isleap(res->tm_year);
}
res->tm_mday = ip[res->tm_mon];
}
}
// TZ_UNLOCK;
}
else
res->tm_isdst = 0;
// os_printf("res %d %d %d %d %d\n",res->tm_year,res->tm_mon,res->tm_mday,res->tm_yday,res->tm_hour);
return (res);
}
struct tm * ICACHE_FLASH_ATTR
sntp_localtime_r(const time_t * tim_p ,
struct tm *res)
{
return sntp_mktm_r (tim_p, res, 0);
}
struct tm * ICACHE_FLASH_ATTR
sntp_localtime(const time_t * tim_p)
{
return sntp_localtime_r (tim_p, &res_buf);
}
int ICACHE_FLASH_ATTR
sntp__tzcalc_limits(int year)
{
int days, year_days, years;
int i, j;
if (year < EPOCH_YEAR)
return 0;
__tzyear = year;
years = (year - EPOCH_YEAR);
year_days = years * 365 +
(years - 1 + EPOCH_YEARS_SINCE_LEAP) / 4 - (years - 1 + EPOCH_YEARS_SINCE_CENTURY) / 100 +
(years - 1 + EPOCH_YEARS_SINCE_LEAP_CENTURY) / 400;
for (i = 0; i < 2; ++i)
{
if (sntp__tzrule[i].ch == 'J')
days = year_days + sntp__tzrule[i].d + (isleap(year) && sntp__tzrule[i].d >= 60);
else if (sntp__tzrule[i].ch == 'D')
days = year_days + sntp__tzrule[i].d;
else
{
int yleap = isleap(year);
int m_day, m_wday, wday_diff;
const int *ip = mon_lengths[yleap];
days = year_days;
for (j = 1; j < sntp__tzrule[i].m; ++j)
days += ip[j-1];
m_wday = (EPOCH_WDAY + days) % DAYSPERWEEK;
wday_diff = sntp__tzrule[i].d - m_wday;
if (wday_diff < 0)
wday_diff += DAYSPERWEEK;
m_day = (sntp__tzrule[i].n - 1) * DAYSPERWEEK + wday_diff;
while (m_day >= ip[j-1])
m_day -= DAYSPERWEEK;
days += m_day;
}
/* store the change-over time in GMT form by adding offset */
sntp__tzrule[i].change = days * SECSPERDAY + sntp__tzrule[i].s + sntp__tzrule[i].offset;
}
__tznorth = (sntp__tzrule[0].change < sntp__tzrule[1].change);
return 1;
}
char * ICACHE_FLASH_ATTR
sntp_asctime_r(struct tm *tim_p ,char *result)
{
static const char day_name[7][4] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char mon_name[12][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
os_sprintf (result, "%s %s %02d %02d:%02d:%02d %02d\n",
day_name[tim_p->tm_wday],
mon_name[tim_p->tm_mon],
tim_p->tm_mday, tim_p->tm_hour, tim_p->tm_min,
tim_p->tm_sec, 1900 + tim_p->tm_year);
return result;
}
char *ICACHE_FLASH_ATTR
sntp_asctime(struct tm *tim_p)
{
return sntp_asctime_r (tim_p, reult);
}
uint32 sntp_get_current_timestamp()
{
if(realtime_stamp == 0){
os_printf("please start sntp first !\n");
return 0;
} else {
return realtime_stamp;
}
}
char* sntp_get_real_time(time_t t)
{
return sntp_asctime(sntp_localtime (&t));
}
/**
* SNTP get time_zone default GMT + 8
*/
sint8 ICACHE_FLASH_ATTR
sntp_get_timezone(void)
{
return time_zone;
}
/**
* SNTP set time_zone default GMT + 8
*/
bool ICACHE_FLASH_ATTR
sntp_set_timezone(sint8 timezone)
{
if(timezone >= -11 || timezone <= 13) {
if (sntp_get_timetype()){
RTC_TZ_SET(time_zone);
} else
time_zone = timezone;
return true;
} else {
return false;
}
}
void ICACHE_FLASH_ATTR sntp_set_daylight(int daylight)
{
if (sntp_get_timetype()){
RTC_DST_SET(daylight);
}
}
void ICACHE_FLASH_ATTR
sntp_time_inc(void)
{
realtime_stamp++;
}
/**
* SNTP processing of received timestamp
*/
static void ICACHE_FLASH_ATTR
sntp_process(u32_t *receive_timestamp)
{
/* convert SNTP time (1900-based) to unix GMT time (1970-based)
* @todo: if MSB is 1, SNTP time is 2036-based!
*/
time_t t = (ntohl(receive_timestamp[0]) - DIFF_SEC_1900_1970);
if (sntp_get_timetype()){
u32_t us = ntohl(receive_timestamp[1]) / 4295;
SNTP_SET_SYSTEM_TIME_US(t, us);
/* display local time from GMT time */
LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_process: %s, %"U32_F" us", ctime(&t), us));
} else{
/* change system time and/or the update the RTC clock */
SNTP_SET_SYSTEM_TIME(t);
/* display local time from GMT time */
t += time_zone * 60 * 60;// format GMT + time_zone TIME ZONE
realtime_stamp = t;
os_timer_disarm(&sntp_timer);
os_timer_setfn(&sntp_timer, (os_timer_func_t *)sntp_time_inc, NULL);
os_timer_arm(&sntp_timer, 1000, 1);
}
#if 0
#if SNTP_CALC_TIME_US
u32_t us = ntohl(receive_timestamp[1]) / 4295;
SNTP_SET_SYSTEM_TIME_US(t, us);
/* display local time from GMT time */
LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_process: %s, %"U32_F" us", ctime(&t), us));
#else /* SNTP_CALC_TIME_US */
/* change system time and/or the update the RTC clock */
SNTP_SET_SYSTEM_TIME(t);
/* display local time from GMT time */
t += time_zone * 60 * 60;// format GMT + time_zone TIME ZONE
realtime_stamp = t;
os_timer_disarm(&sntp_timer);
os_timer_setfn(&sntp_timer, (os_timer_func_t *)sntp_time_inc, NULL);
os_timer_arm(&sntp_timer, 1000, 1);
#endif /* SNTP_CALC_TIME_US */
#endif
}
/**
* Initialize request struct to be sent to server.
*/
static void ICACHE_FLASH_ATTR
sntp_initialize_request(struct sntp_msg *req)
{
os_memset(req, 0, SNTP_MSG_LEN);
req->li_vn_mode = SNTP_LI_NO_WARNING | SNTP_VERSION | SNTP_MODE_CLIENT;
#if SNTP_CHECK_RESPONSE >= 2
{
u32_t sntp_time_sec, sntp_time_us;
/* fill in transmit timestamp and save it in 'sntp_last_timestamp_sent' */
SNTP_GET_SYSTEM_TIME(sntp_time_sec, sntp_time_us);
sntp_last_timestamp_sent[0] = htonl(sntp_time_sec + DIFF_SEC_1900_1970);
req->transmit_timestamp[0] = sntp_last_timestamp_sent[0];
/* we send/save us instead of fraction to be faster... */
sntp_last_timestamp_sent[1] = htonl(sntp_time_us);
req->transmit_timestamp[1] = sntp_last_timestamp_sent[1];
}
#endif /* SNTP_CHECK_RESPONSE >= 2 */
}
/**
* Retry: send a new request (and increase retry timeout).
*
* @param arg is unused (only necessary to conform to sys_timeout)
*/
static void ICACHE_FLASH_ATTR
sntp_retry(void* arg)
{
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_retry: Next request will be sent in %"U32_F" ms\n",
sntp_retry_timeout));
/* set up a timer to send a retry and increase the retry delay */
sys_timeout(sntp_retry_timeout, sntp_request, NULL);
#if SNTP_RETRY_TIMEOUT_EXP
{
u32_t new_retry_timeout;
/* increase the timeout for next retry */
new_retry_timeout = sntp_retry_timeout << 1;
/* limit to maximum timeout and prevent overflow */
if ((new_retry_timeout <= SNTP_RETRY_TIMEOUT_MAX) &&
(new_retry_timeout > sntp_retry_timeout)) {
sntp_retry_timeout = new_retry_timeout;
}
}
#endif /* SNTP_RETRY_TIMEOUT_EXP */
}
#if SNTP_SUPPORT_MULTIPLE_SERVERS
/**
* If Kiss-of-Death is received (or another packet parsing error),
* try the next server or retry the current server and increase the retry
* timeout if only one server is available.
* (implicitly, SNTP_MAX_SERVERS > 1)
*
* @param arg is unused (only necessary to conform to sys_timeout)
*/
static void
sntp_try_next_server(void* arg)
{
u8_t old_server, i;
LWIP_UNUSED_ARG(arg);
old_server = sntp_current_server;
for (i = 0; i < SNTP_MAX_SERVERS - 1; i++) {
sntp_current_server++;
if (sntp_current_server >= SNTP_MAX_SERVERS) {
sntp_current_server = 0;
}
if (!ip_addr_isany(&sntp_servers[sntp_current_server].addr)
#if SNTP_SERVER_DNS
|| (sntp_servers[sntp_current_server].name != NULL)
#endif
) {
LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_try_next_server: Sending request to server %"U16_F"\n",
(u16_t)sntp_current_server));
/* new server: reset retry timeout */
SNTP_RESET_RETRY_TIMEOUT();
/* instantly send a request to the next server */
sntp_request(NULL);
return;
}
}
/* no other valid server found */
sntp_current_server = old_server;
sntp_retry(NULL);
}
#else /* SNTP_SUPPORT_MULTIPLE_SERVERS */
/* Always retry on error if only one server is supported */
#define sntp_try_next_server sntp_retry
#endif /* SNTP_SUPPORT_MULTIPLE_SERVERS */
/** UDP recv callback for the sntp pcb */
static void ICACHE_FLASH_ATTR
sntp_recv(void *arg, struct udp_pcb* pcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
{
u8_t mode;
u8_t stratum;
u32_t receive_timestamp[SNTP_RECEIVE_TIME_SIZE];
err_t err;
//os_printf("sntp_recv\n");
LWIP_UNUSED_ARG(arg);
LWIP_UNUSED_ARG(pcb);
/* packet received: stop retry timeout */
sys_untimeout(sntp_try_next_server, NULL);
sys_untimeout(sntp_request, NULL);
err = ERR_ARG;
#if SNTP_CHECK_RESPONSE >= 1
/* check server address and port */
if (ip_addr_cmp(addr, &sntp_last_server_address) &&
(port == SNTP_PORT))
#else /* SNTP_CHECK_RESPONSE >= 1 */
LWIP_UNUSED_ARG(addr);
LWIP_UNUSED_ARG(port);
#endif /* SNTP_CHECK_RESPONSE >= 1 */
{
/* process the response */
if (p->tot_len == SNTP_MSG_LEN) {
pbuf_copy_partial(p, &mode, 1, SNTP_OFFSET_LI_VN_MODE);
mode &= SNTP_MODE_MASK;
/* if this is a SNTP response... */
if ((mode == SNTP_MODE_SERVER) ||
(mode == SNTP_MODE_BROADCAST)) {
pbuf_copy_partial(p, &stratum, 1, SNTP_OFFSET_STRATUM);
if (stratum == SNTP_STRATUM_KOD) {
/* Kiss-of-death packet. Use another server or increase UPDATE_DELAY. */
err = SNTP_ERR_KOD;
LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_recv: Received Kiss-of-Death\n"));
} else {
#if SNTP_CHECK_RESPONSE >= 2
/* check originate_timetamp against sntp_last_timestamp_sent */
u32_t originate_timestamp[2];
pbuf_copy_partial(p, &originate_timestamp, 8, SNTP_OFFSET_ORIGINATE_TIME);
if ((originate_timestamp[0] != sntp_last_timestamp_sent[0]) ||
(originate_timestamp[1] != sntp_last_timestamp_sent[1]))
{
LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid originate timestamp in response\n"));
} else
#endif /* SNTP_CHECK_RESPONSE >= 2 */
/* @todo: add code for SNTP_CHECK_RESPONSE >= 3 and >= 4 here */
{
/* correct answer */
err = ERR_OK;
pbuf_copy_partial(p, &receive_timestamp, SNTP_RECEIVE_TIME_SIZE * 4, SNTP_OFFSET_RECEIVE_TIME);
}
}
} else {
LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid mode in response: %"U16_F"\n", (u16_t)mode));
}
} else {
LWIP_DEBUGF(SNTP_DEBUG_WARN, ("sntp_recv: Invalid packet length: %"U16_F"\n", p->tot_len));
}
}
pbuf_free(p);
if (err == ERR_OK) {
/* Correct response, reset retry timeout */
SNTP_RESET_RETRY_TIMEOUT();
sntp_process(receive_timestamp);
/* Set up timeout for next request */
sys_timeout((u32_t)sntp_update_delay, sntp_request, NULL);
LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_recv: Scheduled next time request: %"U32_F" ms\n",
(u32_t)sntp_update_delay));
} else if (err == SNTP_ERR_KOD) {
/* Kiss-of-death packet. Use another server or increase UPDATE_DELAY. */
sntp_try_next_server(NULL);
} else {
/* another error, try the same server again */
sntp_retry(NULL);
}
}
/** Actually send an sntp request to a server.
*
* @param server_addr resolved IP address of the SNTP server
*/
static void ICACHE_FLASH_ATTR
sntp_send_request(ip_addr_t *server_addr)
{
struct pbuf* p;
// os_printf("sntp_send_request\n");
p = pbuf_alloc(PBUF_TRANSPORT, SNTP_MSG_LEN, PBUF_RAM);
if (p != NULL) {
struct sntp_msg *sntpmsg = (struct sntp_msg *)p->payload;
LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_send_request: Sending request to server\n"));
/* initialize request message */
sntp_initialize_request(sntpmsg);
/* send request */
udp_sendto(sntp_pcb, p, server_addr, SNTP_PORT);
/* free the pbuf after sending it */
pbuf_free(p);
/* set up receive timeout: try next server or retry on timeout */
sys_timeout((u32_t)SNTP_RECV_TIMEOUT, sntp_try_next_server, NULL);
#if SNTP_CHECK_RESPONSE >= 1
/* save server address to verify it in sntp_recv */
ip_addr_set(&sntp_last_server_address, server_addr);
#endif /* SNTP_CHECK_RESPONSE >= 1 */
} else {
LWIP_DEBUGF(SNTP_DEBUG_SERIOUS, ("sntp_send_request: Out of memory, trying again in %"U32_F" ms\n",
(u32_t)SNTP_RETRY_TIMEOUT));
/* out of memory: set up a timer to send a retry */
sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_request, NULL);
}
}
#if SNTP_SERVER_DNS
/**
* DNS found callback when using DNS names as server address.
*/
static void
sntp_dns_found(const char* hostname, ip_addr_t *ipaddr, void *arg)
{
LWIP_UNUSED_ARG(hostname);
LWIP_UNUSED_ARG(arg);
if (ipaddr != NULL) {
/* Address resolved, send request */
LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_dns_found: Server address resolved, sending request\n"));
sntp_send_request(ipaddr);
} else {
/* DNS resolving failed -> try another server */
LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_dns_found: Failed to resolve server address resolved, trying next server\n"));
sntp_try_next_server(NULL);
}
}
#endif /* SNTP_SERVER_DNS */
/**
* Send out an sntp request.
*
* @param arg is unused (only necessary to conform to sys_timeout)
*/
static void ICACHE_FLASH_ATTR
sntp_request(void *arg)
{
ip_addr_t sntp_server_address;
err_t err;
LWIP_UNUSED_ARG(arg);
/* initialize SNTP server address */
#if SNTP_SERVER_DNS
if (sntp_servers[sntp_current_server].name) {
/* always resolve the name and rely on dns-internal caching & timeout */
ip_addr_set_any(&sntp_servers[sntp_current_server].addr);
err = dns_gethostbyname(sntp_servers[sntp_current_server].name, &sntp_server_address,
sntp_dns_found, NULL);
if (err == ERR_INPROGRESS) {
/* DNS request sent, wait for sntp_dns_found being called */
LWIP_DEBUGF(SNTP_DEBUG_STATE, ("sntp_request: Waiting for server address to be resolved.\n"));
return;
} else if (err == ERR_OK) {
sntp_servers[sntp_current_server].addr = sntp_server_address;
}
} else
#endif /* SNTP_SERVER_DNS */
{
sntp_server_address = sntp_servers[sntp_current_server].addr;
// os_printf("sntp_server_address ip %d\n",sntp_server_address.addr);
err = (ip_addr_isany(&sntp_server_address)) ? ERR_ARG : ERR_OK;
}
if (err == ERR_OK) {
LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp_request: current server address is %u.%u.%u.%u\n",
ip4_addr1(&sntp_server_address), ip4_addr2(&sntp_server_address), ip4_addr3(&sntp_server_address), ip4_addr4(&sntp_server_address)));
sntp_send_request(&sntp_server_address);
} else {
/* address conversion failed, try another server */
LWIP_DEBUGF(SNTP_DEBUG_WARN_STATE, ("sntp_request: Invalid server address, trying next server.\n"));
sys_timeout((u32_t)SNTP_RETRY_TIMEOUT, sntp_try_next_server, NULL);
}
}
/**
* Initialize this module.
* Send out request instantly or after SNTP_STARTUP_DELAY(_FUNC).
*/
void ICACHE_FLASH_ATTR
sntp_init(void)
{
#ifdef SNTP_SERVER_ADDRESS
#if SNTP_SERVER_DNS
sntp_setservername(0, SNTP_SERVER_ADDRESS);
#else
#error SNTP_SERVER_ADDRESS string not supported SNTP_SERVER_DNS==0
#endif
#endif /* SNTP_SERVER_ADDRESS */
if (sntp_pcb == NULL) {
SNTP_RESET_RETRY_TIMEOUT();
sntp_pcb = udp_new();
LWIP_ASSERT("Failed to allocate udp pcb for sntp client", sntp_pcb != NULL);
if (sntp_pcb != NULL) {
udp_recv(sntp_pcb, sntp_recv, NULL);
#if SNTP_STARTUP_DELAY
sys_timeout((u32_t)SNTP_STARTUP_DELAY_FUNC, sntp_request, NULL);
#else
sntp_request(NULL);
#endif
}
}
}
/**
* Stop this module.
*/
void ICACHE_FLASH_ATTR
sntp_stop(void)
{
if (sntp_pcb != NULL) {
sys_untimeout(sntp_request, NULL);
udp_remove(sntp_pcb);
sntp_pcb = NULL;
}
os_timer_disarm(&sntp_timer);
realtime_stamp = 0;
}
#if SNTP_GET_SERVERS_FROM_DHCP
/**
* Config SNTP server handling by IP address, name, or DHCP; clear table
* @param set_servers_from_dhcp enable or disable getting server addresses from dhcp
*/
void
sntp_servermode_dhcp(int set_servers_from_dhcp)
{
u8_t new_mode = set_servers_from_dhcp ? 1 : 0;
if (sntp_set_servers_from_dhcp != new_mode) {
sntp_set_servers_from_dhcp = new_mode;
}
}
#endif /* SNTP_GET_SERVERS_FROM_DHCP */
/**
* Initialize one of the NTP servers by IP address
*
* @param numdns the index of the NTP server to set must be < SNTP_MAX_SERVERS
* @param dnsserver IP address of the NTP server to set
*/
void ICACHE_FLASH_ATTR
sntp_setserver(u8_t idx, ip_addr_t *server)
{
if (idx < SNTP_MAX_SERVERS) {
if (server != NULL) {
sntp_servers[idx].addr = (*server);
// os_printf("server ip %d\n",server->addr);
} else {
ip_addr_set_any(&sntp_servers[idx].addr);
}
#if SNTP_SERVER_DNS
sntp_servers[idx].name = NULL;
#endif
}
}
#if LWIP_DHCP && SNTP_GET_SERVERS_FROM_DHCP
/**
* Initialize one of the NTP servers by IP address, required by DHCP
*
* @param numdns the index of the NTP server to set must be < SNTP_MAX_SERVERS
* @param dnsserver IP address of the NTP server to set
*/
void
dhcp_set_ntp_servers(u8_t num, ip_addr_t *server)
{
LWIP_DEBUGF(SNTP_DEBUG_TRACE, ("sntp: %s %u.%u.%u.%u as NTP server #%u via DHCP\n",
(sntp_set_servers_from_dhcp ? "Got" : "Rejected"),
ip4_addr1(server), ip4_addr2(server), ip4_addr3(server), ip4_addr4(server), num));
if (sntp_set_servers_from_dhcp && num) {
u8_t i;
for (i = 0; (i < num) && (i < SNTP_MAX_SERVERS); i++) {
sntp_setserver(i, &server[i]);
}
for (i = num; i < SNTP_MAX_SERVERS; i++) {
sntp_setserver(i, NULL);
}
}
}
#endif /* LWIP_DHCP && SNTP_GET_SERVERS_FROM_DHCP */
/**
* Obtain one of the currently configured by IP address (or DHCP) NTP servers
*
* @param numdns the index of the NTP server
* @return IP address of the indexed NTP server or "ip_addr_any" if the NTP
* server has not been configured by address (or at all).
*/
ip_addr_t ICACHE_FLASH_ATTR
sntp_getserver(u8_t idx)
{
if (idx < SNTP_MAX_SERVERS) {
return sntp_servers[idx].addr;
}
return *IP_ADDR_ANY;
}
#if SNTP_SERVER_DNS
/**
* Initialize one of the NTP servers by name
*
* @param numdns the index of the NTP server to set must be < SNTP_MAX_SERVERS
* @param dnsserver DNS name of the NTP server to set, to be resolved at contact time
*/
void ICACHE_FLASH_ATTR
sntp_setservername(u8_t idx, char *server)
{
if (idx < SNTP_MAX_SERVERS) {
sntp_servers[idx].name = server;
}
}
/**
* Obtain one of the currently configured by name NTP servers.
*
* @param numdns the index of the NTP server
* @return IP address of the indexed NTP server or NULL if the NTP
* server has not been configured by name (or at all)
*/
char * ICACHE_FLASH_ATTR
sntp_getservername(u8_t idx)
{
if (idx < SNTP_MAX_SERVERS) {
return sntp_servers[idx].name;
}
return NULL;
}
#endif /* SNTP_SERVER_DNS */
void ICACHE_FLASH_ATTR
sntp_set_update_delay(uint32 ms)
{
sntp_update_delay = ms > 15000?ms:15000;
}
void ICACHE_FLASH_ATTR
sntp_set_timetype(bool type)
{
sntp_time_flag = type;
}
bool sntp_get_timetype(void)
{
return sntp_time_flag;
}
void ICACHE_FLASH_ATTR
sntp_set_receive_time_size(void)
{
if (sntp_get_timetype()){
sntp_receive_time_size = 2;
} else{
sntp_receive_time_size = 1;
}
}
#endif /* LWIP_UDP */
......@@ -500,7 +500,7 @@ tcp_listen_input(struct tcp_pcb_listen *pcb)
/* For incoming segments with the ACK flag set, respond with a
RST. */
LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_listen_input: ACK in LISTEN, sending reset\n"));
tcp_rst(ackno + 1, seqno + tcplen,
tcp_rst(ackno, seqno + tcplen,
ip_current_dest_addr(), ip_current_src_addr(),
tcphdr->dest, tcphdr->src);
} else if (flags & TCP_SYN) {//�յ�SYN����
......
......@@ -461,6 +461,7 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
return ERR_MEM;
}
#if !LWIP_NETIF_TX_SINGLE_PBUF
/*
* Phase 2: Chain a new pbuf to the end of pcb->unsent.
*
......@@ -510,6 +511,7 @@ tcp_write(struct tcp_pcb *pcb, const void *arg, u16_t len, u8_t apiflags)
pos += seglen;
queuelen += pbuf_clen(concat_p);
}
#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
} else {
#if TCP_OVERSIZE
LWIP_ASSERT("unsent_oversize mismatch (pcb->unsent is NULL)",
......@@ -1336,6 +1338,12 @@ tcp_rexmit(struct tcp_pcb *pcb)
}
seg->next = *cur_seg;
*cur_seg = seg;
#if TCP_OVERSIZE
if (seg->next == NULL) {
/* the retransmitted segment is last in unsent, so reset unsent_oversize */
pcb->unsent_oversize = 0;
}
#endif /* TCP_OVERSIZE */
++pcb->nrtx;
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment