@@ -115,6 +115,10 @@ static void cdc_rx_callback(int itf, cdcacm_event_t *event)
115115 // Not our channel
116116 return ;
117117 }
118+ // Check if netif is still valid (not destroyed during shutdown)
119+ if (s_netif == NULL ) {
120+ return ;
121+ }
118122 esp_err_t ret = tinyusb_cdcacm_read (itf , buf , CONFIG_TINYUSB_CDC_RX_BUFSIZE , & rx_size );
119123 if (ret == ESP_OK ) {
120124 ESP_LOG_BUFFER_HEXDUMP (TAG , buf , rx_size , ESP_LOG_VERBOSE );
@@ -149,22 +153,29 @@ static void ppp_task(void *args)
149153 ESP_ERROR_CHECK (uart_set_rx_timeout (UART_NUM_1 , 1 ));
150154
151155 char * buffer = (char * )malloc (BUF_SIZE );
156+ if (buffer == NULL ) {
157+ ESP_LOGE (TAG , "Failed to allocate memory for UART buffer" );
158+ uart_driver_delete (UART_NUM_1 );
159+ vTaskDelete (NULL );
160+ return ;
161+ }
152162 uart_event_t event ;
153163 esp_event_handler_register (IP_EVENT , IP_EVENT_PPP_GOT_IP , esp_netif_action_connected , s_netif );
154164 esp_netif_action_start (s_netif , 0 , 0 , 0 );
155165 esp_netif_action_connected (s_netif , 0 , 0 , 0 );
156166 while (!s_stop_task ) {
157- xQueueReceive (event_queue , & event , pdMS_TO_TICKS (1000 ));
158- if (event .type == UART_DATA ) {
159- size_t len ;
160- uart_get_buffered_data_len (UART_NUM_1 , & len );
161- if (len ) {
162- len = uart_read_bytes (UART_NUM_1 , buffer , BUF_SIZE , 0 );
163- ESP_LOG_BUFFER_HEXDUMP (TAG , buffer , len , ESP_LOG_VERBOSE );
164- esp_netif_receive (s_netif , buffer , len , NULL );
167+ if (xQueueReceive (event_queue , & event , pdMS_TO_TICKS (1000 )) == pdTRUE ) {
168+ if (event .type == UART_DATA ) {
169+ size_t len ;
170+ uart_get_buffered_data_len (UART_NUM_1 , & len );
171+ if (len ) {
172+ len = uart_read_bytes (UART_NUM_1 , buffer , BUF_SIZE , 0 );
173+ ESP_LOG_BUFFER_HEXDUMP (TAG , buffer , len , ESP_LOG_VERBOSE );
174+ esp_netif_receive (s_netif , buffer , len , NULL );
175+ }
176+ } else {
177+ ESP_LOGW (TAG , "Received UART event: %d" , event .type );
165178 }
166- } else {
167- ESP_LOGW (TAG , "Received UART event: %d" , event .type );
168179 }
169180 }
170181 free (buffer );
@@ -243,7 +254,12 @@ esp_err_t net_connect_ppp_connect(void)
243254void net_connect_ppp_shutdown (void )
244255{
245256 ESP_ERROR_CHECK (esp_event_handler_unregister (IP_EVENT , ESP_EVENT_ANY_ID , on_ip_event ));
246- #if CONFIG_NET_CONNECT_PPP_DEVICE_UART
257+ #if CONFIG_NET_CONNECT_PPP_DEVICE_USB
258+ // Unregister CDC line state callback to prevent access to destroyed netif
259+ // Note: RX callback is set via config and cannot be unregistered, but cdc_rx_callback
260+ // has a NULL check to prevent crashes if called after shutdown
261+ tinyusb_cdcacm_register_callback (TINYUSB_CDC_ACM_0 , CDC_EVENT_LINE_STATE_CHANGED , NULL );
262+ #elif CONFIG_NET_CONNECT_PPP_DEVICE_UART
247263 s_stop_task = true;
248264 vTaskDelay (pdMS_TO_TICKS (1000 )); // wait for the ppp task to stop
249265#endif
0 commit comments