From dfd7c244b6c2fc81cb5206ef2c4afba875523be3 Mon Sep 17 00:00:00 2001 From: Sean DuBois Date: Sat, 31 Aug 2024 23:28:34 -0400 Subject: [PATCH] Add .clang-format to project Also add to GitHub Actions --- .clang-format | 2 + .github/workflows/clang-format-check.yml | 19 ++ examples/esp32/main/app_main.c | 68 +++--- examples/esp32/main/audio.c | 54 ++--- examples/esp32/main/camera.c | 53 ++--- examples/generic/main.c | 54 ++--- examples/generic/reader.c | 54 ++--- examples/generic/reader.h | 7 +- examples/raspberrypi/main.c | 111 ++++------ src/address.c | 32 ++- src/address.h | 18 +- src/agent.c | 146 +++++-------- src/agent.h | 44 ++-- src/base64.c | 107 +++++----- src/base64.h | 6 +- src/buffer.c | 40 ++-- src/buffer.h | 19 +- src/config.h | 8 +- src/dtls_srtp.c | 176 ++++++---------- src/dtls_srtp.h | 49 +++-- src/ice.c | 54 +++-- src/ice.h | 19 +- src/mdns.c | 39 ++-- src/mdns.h | 4 +- src/peer.c | 10 +- src/peer.h | 3 +- src/peer_connection.c | 252 ++++++++++------------- src/peer_connection.h | 79 ++++--- src/peer_signaling.c | 134 +++++------- src/peer_signaling.h | 40 ++-- src/ports.c | 58 +++--- src/ports.h | 8 +- src/rtcp.c | 41 ++-- src/rtcp.h | 35 ++-- src/rtp.c | 97 ++++----- src/rtp.h | 55 +++-- src/sctp.c | 252 ++++++++++------------- src/sctp.h | 62 +++--- src/sdp.c | 27 +-- src/sdp.h | 19 +- src/socket.c | 88 ++++---- src/socket.h | 24 +-- src/ssl_transport.c | 56 +++-- src/ssl_transport.h | 22 +- src/stun.c | 221 +++++++++----------- src/stun.h | 36 ++-- src/utils.c | 27 ++- src/utils.h | 14 +- tests/test_agent.c | 12 +- tests/test_dtls.c | 7 +- tests/test_peer_connection.c | 5 +- tests/test_rb.c | 31 +-- tests/test_sdp.c | 8 +- tests/test_stun.c | 4 +- 54 files changed, 1233 insertions(+), 1677 deletions(-) create mode 100644 .clang-format create mode 100644 .github/workflows/clang-format-check.yml diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..758ea97 --- /dev/null +++ b/.clang-format @@ -0,0 +1,2 @@ +BasedOnStyle: Chromium +ColumnLimit: 0 diff --git a/.github/workflows/clang-format-check.yml b/.github/workflows/clang-format-check.yml new file mode 100644 index 0000000..c224db3 --- /dev/null +++ b/.github/workflows/clang-format-check.yml @@ -0,0 +1,19 @@ +name: clang-format Check +on: [push, pull_request] +jobs: + formatting-check: + name: Formatting Check + runs-on: ubuntu-latest + strategy: + matrix: + path: + - 'examples' + - 'src' + - 'tests' + steps: + - uses: actions/checkout@v4 + - name: Run clang-format style check for C/C++/Protobuf programs. + uses: jidicula/clang-format-action@v4.13.0 + with: + clang-format-version: '17' + check-path: ${{ matrix.path }} diff --git a/examples/esp32/main/app_main.c b/examples/esp32/main/app_main.c index 6dfd2d0..f73549d 100644 --- a/examples/esp32/main/app_main.c +++ b/examples/esp32/main/app_main.c @@ -1,25 +1,25 @@ -#include -#include #include +#include +#include #include -#include #include -#include "esp_system.h" -#include "esp_partition.h" -#include "nvs_flash.h" +#include #include "esp_event.h" -#include "esp_netif.h" -#include "esp_mac.h" -#include "mdns.h" #include "esp_log.h" -#include "esp_tls.h" +#include "esp_mac.h" +#include "esp_netif.h" #include "esp_ota_ops.h" +#include "esp_partition.h" +#include "esp_system.h" +#include "esp_tls.h" #include "freertos/FreeRTOS.h" +#include "mdns.h" +#include "nvs_flash.h" #include "protocol_examples_common.h" #include "peer.h" -static const char *TAG = "webrtc"; +static const char* TAG = "webrtc"; static TaskHandle_t xPcTaskHandle = NULL; static TaskHandle_t xPsTaskHandle = NULL; @@ -28,24 +28,22 @@ static TaskHandle_t xAudioTaskHandle = NULL; extern esp_err_t camera_init(); extern esp_err_t audio_init(); -extern void camera_task(void *pvParameters); -extern void audio_task(void *pvParameters); +extern void camera_task(void* pvParameters); +extern void audio_task(void* pvParameters); SemaphoreHandle_t xSemaphore = NULL; -PeerConnection *g_pc; +PeerConnection* g_pc; PeerConnectionState eState = PEER_CONNECTION_CLOSED; int gDataChannelOpened = 0; int64_t get_timestamp() { - struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000LL + (tv.tv_usec / 1000LL)); } -static void oniceconnectionstatechange(PeerConnectionState state, void *user_data) { - +static void oniceconnectionstatechange(PeerConnectionState state, void* user_data) { ESP_LOGI(TAG, "PeerConnectionState: %d", state); eState = state; // not support datachannel close event @@ -54,43 +52,35 @@ static void oniceconnectionstatechange(PeerConnectionState state, void *user_dat } } -static void onmessage(char *msg, size_t len, void *userdata, uint16_t sid) { - +static void onmessage(char* msg, size_t len, void* userdata, uint16_t sid) { ESP_LOGI(TAG, "Datachannel message: %.*s", len, msg); } -void onopen(void *userdata) { - +void onopen(void* userdata) { ESP_LOGI(TAG, "Datachannel opened"); gDataChannelOpened = 1; } -static void onclose(void *userdata) { - +static void onclose(void* userdata) { } -void peer_signaling_task(void *arg) { - +void peer_signaling_task(void* arg) { ESP_LOGI(TAG, "peer_signaling_task started"); - for(;;) { - + for (;;) { peer_signaling_loop(); vTaskDelay(pdMS_TO_TICKS(10)); } - } -void peer_connection_task(void *arg) { - +void peer_connection_task(void* arg) { ESP_LOGI(TAG, "peer_connection_task started"); - for(;;) { - + for (;;) { if (xSemaphoreTake(xSemaphore, portMAX_DELAY)) { - peer_connection_loop(g_pc); - xSemaphoreGive(xSemaphore); + peer_connection_loop(g_pc); + xSemaphoreGive(xSemaphore); } vTaskDelay(pdMS_TO_TICKS(1)); @@ -98,16 +88,14 @@ void peer_connection_task(void *arg) { } void app_main(void) { - static char deviceid[32] = {0}; uint8_t mac[8] = {0}; PeerConfiguration config = { - .ice_servers = { - { .urls = "stun:stun.l.google.com:19302" } - }, - .audio_codec = CODEC_PCMA, - .datachannel = DATA_CHANNEL_BINARY, + .ice_servers = { + {.urls = "stun:stun.l.google.com:19302"}}, + .audio_codec = CODEC_PCMA, + .datachannel = DATA_CHANNEL_BINARY, }; ESP_LOGI(TAG, "[APP] Startup.."); diff --git a/examples/esp32/main/audio.c b/examples/esp32/main/audio.c index 612766c..bea78a7 100644 --- a/examples/esp32/main/audio.c +++ b/examples/esp32/main/audio.c @@ -1,36 +1,35 @@ +#include "driver/i2s_pdm.h" +#include "esp_log.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" -#include "esp_log.h" -#include "driver/i2s_pdm.h" +#include "esp_audio_enc.h" #include "esp_audio_enc_default.h" #include "esp_audio_enc_reg.h" #include "esp_g711_enc.h" -#include "esp_audio_enc.h" #include "peer_connection.h" #define I2S_CLK_GPIO 42 #define I2S_DATA_GPIO 41 -static const char *TAG = "AUDIO"; +static const char* TAG = "AUDIO"; -extern PeerConnection *g_pc; +extern PeerConnection* g_pc; extern PeerConnectionState eState; extern int get_timestamp(); i2s_chan_handle_t rx_handle = NULL; esp_audio_enc_handle_t enc_handle = NULL; -esp_audio_enc_in_frame_t aenc_in_frame = { 0 }; -esp_audio_enc_out_frame_t aenc_out_frame = { 0 }; +esp_audio_enc_in_frame_t aenc_in_frame = {0}; +esp_audio_enc_out_frame_t aenc_out_frame = {0}; esp_g711_enc_config_t g711_cfg; esp_audio_enc_config_t enc_cfg; esp_err_t audio_codec_init() { - - uint8_t *read_buf = NULL; - uint8_t *write_buf = NULL; + uint8_t* read_buf = NULL; + uint8_t* write_buf = NULL; int read_size = 0; int out_size = 0; @@ -77,20 +76,19 @@ esp_err_t audio_codec_init() { } esp_err_t audio_init(void) { - i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, NULL, &rx_handle)); i2s_pdm_rx_config_t pdm_rx_cfg = { - .clk_cfg = I2S_PDM_RX_CLK_DEFAULT_CONFIG(8000), - .slot_cfg = I2S_PDM_RX_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO), - .gpio_cfg = { - .clk = I2S_CLK_GPIO, - .din = I2S_DATA_GPIO, - .invert_flags = { - .clk_inv = false, - }, - }, + .clk_cfg = I2S_PDM_RX_CLK_DEFAULT_CONFIG(8000), + .slot_cfg = I2S_PDM_RX_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO), + .gpio_cfg = { + .clk = I2S_CLK_GPIO, + .din = I2S_DATA_GPIO, + .invert_flags = { + .clk_inv = false, + }, + }, }; ESP_ERROR_CHECK(i2s_channel_init_pdm_rx_mode(rx_handle, &pdm_rx_cfg)); @@ -100,24 +98,21 @@ esp_err_t audio_init(void) { } void audio_deinit(void) { - ESP_ERROR_CHECK(i2s_channel_disable(rx_handle)); ESP_ERROR_CHECK(i2s_del_channel(rx_handle)); } -int32_t audio_get_samples(uint8_t *buf, size_t size) { - +int32_t audio_get_samples(uint8_t* buf, size_t size) { size_t bytes_read; - if (i2s_channel_read(rx_handle, (char *)buf, size, &bytes_read, 1000) != ESP_OK) { + if (i2s_channel_read(rx_handle, (char*)buf, size, &bytes_read, 1000) != ESP_OK) { ESP_LOGE(TAG, "i2s read error"); } return bytes_read; } -void audio_task(void *arg) { - +void audio_task(void* arg) { int ret; static int64_t last_time; int64_t curr_time; @@ -127,20 +122,15 @@ void audio_task(void *arg) { ESP_LOGI(TAG, "audio task started"); for (;;) { - if (eState == PEER_CONNECTION_COMPLETED) { - ret = audio_get_samples(aenc_in_frame.buffer, aenc_in_frame.len); if (ret == aenc_in_frame.len) { - if (esp_audio_enc_process(enc_handle, &aenc_in_frame, &aenc_out_frame) == ESP_AUDIO_ERR_OK) { - peer_connection_send_audio(g_pc, aenc_out_frame.buffer, aenc_out_frame.encoded_bytes); bytes += aenc_out_frame.encoded_bytes; if (bytes > 50000) { - curr_time = get_timestamp(); ESP_LOGI(TAG, "audio bitrate: %.1f bps", 1000.0 * (bytes * 8.0 / (float)(curr_time - last_time))); last_time = curr_time; @@ -151,9 +141,7 @@ void audio_task(void *arg) { vTaskDelay(pdMS_TO_TICKS(5)); } else { - vTaskDelay(pdMS_TO_TICKS(100)); } } } - diff --git a/examples/esp32/main/camera.c b/examples/esp32/main/camera.c index edec5f3..0d58448 100644 --- a/examples/esp32/main/camera.c +++ b/examples/esp32/main/camera.c @@ -1,22 +1,22 @@ -#include -#include #include +#include +#include #include +#include "esp_log.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" -#include "esp_log.h" #include "esp_camera.h" #include "esp_timer.h" #include "peer_connection.h" -extern PeerConnection *g_pc; +extern PeerConnection* g_pc; extern int gDataChannelOpened; extern PeerConnectionState eState; extern SemaphoreHandle_t xSemaphore; extern int get_timestamp(); -static const char *TAG = "Camera"; +static const char* TAG = "Camera"; #if defined(CONFIG_ESP32S3_XIAO_SENSE) #define CAM_PIN_PWDN -1 @@ -52,7 +52,7 @@ static const char *TAG = "Camera"; #define CAM_PIN_VSYNC 25 #define CAM_PIN_HREF 26 #define CAM_PIN_PCLK 21 -#else // ESP32-EYE +#else // ESP32-EYE #define CAM_PIN_PWDN -1 #define CAM_PIN_RESET -1 #define CAM_PIN_XCLK 4 @@ -89,52 +89,46 @@ static camera_config_t camera_config = { .pin_href = CAM_PIN_HREF, .pin_sccb_sda = CAM_PIN_SIOD, .pin_sccb_scl = CAM_PIN_SIOC, - .pin_pwdn = CAM_PIN_PWDN, + .pin_pwdn = CAM_PIN_PWDN, .pin_reset = CAM_PIN_RESET, .xclk_freq_hz = 20000000, .pixel_format = PIXFORMAT_JPEG, .frame_size = FRAMESIZE_VGA, .jpeg_quality = 10, .fb_count = 2, - .grab_mode = CAMERA_GRAB_WHEN_EMPTY -}; - -esp_err_t camera_init(){ - - //initialize the camera - esp_err_t err = esp_camera_init(&camera_config); - if (err != ESP_OK) { - ESP_LOGE(TAG, "Camera Init Failed"); - return err; - } + .grab_mode = CAMERA_GRAB_WHEN_EMPTY}; + +esp_err_t camera_init() { + // initialize the camera + esp_err_t err = esp_camera_init(&camera_config); + if (err != ESP_OK) { + ESP_LOGE(TAG, "Camera Init Failed"); + return err; + } - return ESP_OK; + return ESP_OK; } -void camera_task(void *pvParameters) { - +void camera_task(void* pvParameters) { static int fps = 0; static int64_t last_time; int64_t curr_time; - camera_fb_t * fb = NULL; + camera_fb_t* fb = NULL; ESP_LOGI(TAG, "Camera Task Started"); last_time = get_timestamp(); - for(;;) { - + for (;;) { if ((eState == PEER_CONNECTION_COMPLETED) && gDataChannelOpened) { - fb = esp_camera_fb_get(); if (!fb) { - ESP_LOGE(TAG, "Camera capture failed"); } - //ESP_LOGI(TAG, "Camera captured. size=%zu, timestamp=%llu", fb->len, fb->timestamp); + // ESP_LOGI(TAG, "Camera captured. size=%zu, timestamp=%llu", fb->len, fb->timestamp); if (xSemaphoreTake(xSemaphore, portMAX_DELAY)) { peer_connection_datachannel_send(g_pc, (char*)fb->buf, fb->len); xSemaphoreGive(xSemaphore); @@ -143,7 +137,6 @@ void camera_task(void *pvParameters) { fps++; if ((fps % 100) == 0) { - curr_time = get_timestamp(); ESP_LOGI(TAG, "Camera FPS=%.2f", 1000.0f / (float)(curr_time - last_time) * 100.0f); last_time = curr_time; @@ -152,8 +145,6 @@ void camera_task(void *pvParameters) { esp_camera_fb_return(fb); } - vTaskDelay(pdMS_TO_TICKS(1000/20)); + vTaskDelay(pdMS_TO_TICKS(1000 / 20)); } - } - diff --git a/examples/generic/main.c b/examples/generic/main.c index ca703b0..a49d57e 100644 --- a/examples/generic/main.c +++ b/examples/generic/main.c @@ -1,33 +1,29 @@ +#include +#include #include #include -#include -#include #include -#include +#include -#include "reader.h" #include "peer.h" +#include "reader.h" int g_interrupted = 0; -PeerConnection *g_pc = NULL; +PeerConnection* g_pc = NULL; PeerConnectionState g_state; -static void onconnectionstatechange(PeerConnectionState state, void *data) { - +static void onconnectionstatechange(PeerConnectionState state, void* data) { printf("state is changed: %s\n", peer_connection_state_to_string(state)); g_state = state; } -static void onopen(void *user_data) { - +static void onopen(void* user_data) { } -static void onclose(void *user_data) { - +static void onclose(void* user_data) { } -static void onmessage(char *msg, size_t len, void *user_data, uint16_t sid) { - +static void onmessage(char* msg, size_t len, void* user_data, uint16_t sid) { printf("on message: %d %s", sid, msg); if (strncmp(msg, "ping", 4) == 0) { @@ -37,14 +33,11 @@ static void onmessage(char *msg, size_t len, void *user_data, uint16_t sid) { } static void signal_handler(int signal) { - g_interrupted = 1; } -static void* peer_singaling_task(void *data) { - +static void* peer_singaling_task(void* data) { while (!g_interrupted) { - peer_signaling_loop(); usleep(1000); } @@ -52,26 +45,22 @@ static void* peer_singaling_task(void *data) { pthread_exit(NULL); } -static void* peer_connection_task(void *data) { - +static void* peer_connection_task(void* data) { while (!g_interrupted) { - peer_connection_loop(g_pc); - usleep(1000); + usleep(1000); } - pthread_exit(NULL); + pthread_exit(NULL); } static uint64_t get_timestamp() { - struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } -int main(int argc, char *argv[]) { - +int main(int argc, char* argv[]) { uint64_t curr_time, video_time, audio_time; uint8_t buf[102400]; int size; @@ -87,13 +76,12 @@ int main(int argc, char *argv[]) { signal(SIGINT, signal_handler); PeerConfiguration config = { - .ice_servers = { - { .urls = "stun:stun.l.google.com:19302" }, - }, - .datachannel = DATA_CHANNEL_STRING, - .video_codec = CODEC_H264, - .audio_codec = CODEC_PCMA - }; + .ice_servers = { + {.urls = "stun:stun.l.google.com:19302"}, + }, + .datachannel = DATA_CHANNEL_STRING, + .video_codec = CODEC_H264, + .audio_codec = CODEC_PCMA}; ServiceConfiguration service_config = SERVICE_CONFIG_DEFAULT(); @@ -115,9 +103,7 @@ int main(int argc, char *argv[]) { reader_init(); while (!g_interrupted) { - if (g_state == PEER_CONNECTION_COMPLETED) { - curr_time = get_timestamp(); // FPS 25 diff --git a/examples/generic/reader.c b/examples/generic/reader.c index 6779cb5..65d3ce1 100644 --- a/examples/generic/reader.c +++ b/examples/generic/reader.c @@ -1,25 +1,23 @@ +#include #include #include #include -#include #include static int g_video_size = 0; static int g_audio_size = 0; -static uint8_t *g_video_buf = NULL; -static uint8_t *g_audio_buf = NULL; +static uint8_t* g_video_buf = NULL; +static uint8_t* g_audio_buf = NULL; int reader_init() { - - FILE *video_fp = NULL; - FILE *audio_fp = NULL; + FILE* video_fp = NULL; + FILE* audio_fp = NULL; char videofile[] = "test.264"; char audiofile[] = "alaw08m.wav"; video_fp = fopen(videofile, "rb"); if (video_fp == NULL) { - printf("open file %s failed\n", videofile); return -1; } @@ -27,14 +25,13 @@ int reader_init() { fseek(video_fp, 0, SEEK_END); g_video_size = ftell(video_fp); fseek(video_fp, 0, SEEK_SET); - g_video_buf = (uint8_t *)calloc(1, g_video_size); + g_video_buf = (uint8_t*)calloc(1, g_video_size); fread(g_video_buf, g_video_size, 1, video_fp); fclose(video_fp); audio_fp = fopen(audiofile, "rb"); if (audio_fp == NULL) { - printf("open file %s failed\n", audiofile); return -1; } @@ -42,22 +39,19 @@ int reader_init() { fseek(audio_fp, 0, SEEK_END); g_audio_size = ftell(audio_fp); fseek(audio_fp, 0, SEEK_SET); - g_audio_buf = (uint8_t *)calloc(1, g_audio_size); + g_audio_buf = (uint8_t*)calloc(1, g_audio_size); fread(g_audio_buf, 1, g_audio_size, audio_fp); fclose(audio_fp); return 0; } -uint8_t* reader_h264_find_nalu(uint8_t *buf_start, uint8_t *buf_end) { - +uint8_t* reader_h264_find_nalu(uint8_t* buf_start, uint8_t* buf_end) { static const uint32_t nalu_start_code = 0x01000000; - uint8_t *p = buf_start; - - while((p + 4) < buf_end) { + uint8_t* p = buf_start; + while ((p + 4) < buf_end) { if (memcmp(p, &nalu_start_code, 4) == 0) { - return p; } @@ -67,25 +61,24 @@ uint8_t* reader_h264_find_nalu(uint8_t *buf_start, uint8_t *buf_end) { return buf_end; } -int reader_get_video_frame(uint8_t *buf, int *size) { - - int ret = -1; +int reader_get_video_frame(uint8_t* buf, int* size) { + int ret = -1; static uint8_t pps_frame[128]; static uint8_t sps_frame[128]; static int pps_size = 0; static int sps_size = 0; - uint8_t *buf_end = g_video_buf + g_video_size; + uint8_t* buf_end = g_video_buf + g_video_size; - static uint8_t *pstart = NULL; - static uint8_t *pend = NULL; + static uint8_t* pstart = NULL; + static uint8_t* pend = NULL; size_t nalu_size; - if (!pstart) pstart = g_video_buf; + if (!pstart) + pstart = g_video_buf; pend = reader_h264_find_nalu(pstart + 1, buf_end); if (pend == buf_end) { - pstart = NULL; return -1; } @@ -93,17 +86,14 @@ int reader_get_video_frame(uint8_t *buf, int *size) { nalu_size = pend - pstart; if ((pstart[4] & 0x1f) == 0x07) { - sps_size = nalu_size; memcpy(sps_frame, pstart, nalu_size); } else if ((pstart[4] & 0x1f) == 0x08) { - pps_size = nalu_size; memcpy(pps_frame, pstart, nalu_size); } else if ((pstart[4] & 0x1f) == 0x05) { - *size = sps_size + pps_size + nalu_size; memcpy(buf, sps_frame, sps_size); memcpy(buf + sps_size, pps_frame, pps_size); @@ -111,19 +101,17 @@ int reader_get_video_frame(uint8_t *buf, int *size) { ret = 0; } else { - *size = nalu_size; memcpy(buf, pstart, nalu_size); ret = 0; } - - pstart = pend; + + pstart = pend; return ret; } -int reader_get_audio_frame(uint8_t *buf, int *size) { - +int reader_get_audio_frame(uint8_t* buf, int* size) { // sample-rate=8000 channels=1 format=S16LE duration=20ms alaw-size=160 static int pos = 0; *size = 160; @@ -138,7 +126,6 @@ int reader_get_audio_frame(uint8_t *buf, int *size) { } void reader_deinit() { - if (g_video_buf != NULL) { free(g_video_buf); g_video_buf = NULL; @@ -149,4 +136,3 @@ void reader_deinit() { g_audio_buf = NULL; } } - diff --git a/examples/generic/reader.h b/examples/generic/reader.h index 2f3d58f..623af27 100644 --- a/examples/generic/reader.h +++ b/examples/generic/reader.h @@ -1,13 +1,12 @@ +#include #include #include #include -#include int reader_init(); -int reader_get_video_frame(uint8_t *buf, int *size); +int reader_get_video_frame(uint8_t* buf, int* size); -int reader_get_audio_frame(uint8_t *buf, int *size); +int reader_get_audio_frame(uint8_t* buf, int* size); void reader_deinit(); - diff --git a/examples/raspberrypi/main.c b/examples/raspberrypi/main.c index fee9e61..76f49b2 100644 --- a/examples/raspberrypi/main.c +++ b/examples/raspberrypi/main.c @@ -1,16 +1,16 @@ -#include -#include -#include -#include -#include +#include +#include #include #include -#include -#include +#include +#include #include +#include +#include +#include +#include #include -#include -#include +#include #include "peer.h" @@ -21,49 +21,44 @@ const char MIC_PIPELINE[] = "alsasrc latency-time=20000 device=plughw:seeed2micv const char SPK_PIPELINE[] = "appsrc name=spk-src format=time ! alawdec ! audio/x-raw,format=S16LE,rate=8000,channels=1 ! alsasink sync=false device=plughw:seeed2micvoicec,0"; int g_interrupted = 0; -PeerConnection *g_pc = NULL; +PeerConnection* g_pc = NULL; PeerConnectionState g_state; typedef struct Media { - // Camera elements - GstElement *camera_pipeline; - GstElement *camera_sink; + GstElement* camera_pipeline; + GstElement* camera_sink; // Microphone elements - GstElement *mic_pipeline; - GstElement *mic_sink; + GstElement* mic_pipeline; + GstElement* mic_sink; // Speaker elements - GstElement *spk_pipeline; - GstElement *spk_src; + GstElement* spk_pipeline; + GstElement* spk_src; } Media; Media g_media; -static void onconnectionstatechange(PeerConnectionState state, void *data) { - +static void onconnectionstatechange(PeerConnectionState state, void* data) { printf("state is changed: %d\n", state); g_state = state; if (g_state == PEER_CONNECTION_COMPLETED) { - gst_element_set_state(g_media.camera_pipeline, GST_STATE_PLAYING); gst_element_set_state(g_media.mic_pipeline, GST_STATE_PLAYING); gst_element_set_state(g_media.spk_pipeline, GST_STATE_PLAYING); } } -static GstFlowReturn on_video_data(GstElement *sink, void *data) { - - GstSample *sample; - GstBuffer *buffer; +static GstFlowReturn on_video_data(GstElement* sink, void* data) { + GstSample* sample; + GstBuffer* buffer; GstMapInfo info; g_signal_emit_by_name(sink, "pull-sample", &sample); - if(sample) { - + if (sample) { buffer = gst_sample_get_buffer(sample); gst_buffer_map(buffer, &info, GST_MAP_READ); peer_connection_send_video(g_pc, info.data, info.size); @@ -77,16 +72,14 @@ static GstFlowReturn on_video_data(GstElement *sink, void *data) { return GST_FLOW_ERROR; } -static GstFlowReturn on_audio_data(GstElement *sink, void *data) { - - GstSample *sample; - GstBuffer *buffer; +static GstFlowReturn on_audio_data(GstElement* sink, void* data) { + GstSample* sample; + GstBuffer* buffer; GstMapInfo info; g_signal_emit_by_name(sink, "pull-sample", &sample); - if(sample) { - + if (sample) { buffer = gst_sample_get_buffer(sample); gst_buffer_map(buffer, &info, GST_MAP_READ); peer_connection_send_audio(g_pc, info.data, info.size); @@ -99,17 +92,13 @@ static GstFlowReturn on_audio_data(GstElement *sink, void *data) { return GST_FLOW_ERROR; } - -static void onopen(void *user_data) { - +static void onopen(void* user_data) { } -static void onclose(void *user_data) { - +static void onclose(void* user_data) { } -static void onmessasge(char *msg, size_t len, void *user_data) { - +static void onmessasge(char* msg, size_t len, void* user_data) { printf("on message: %s", msg); if (strncmp(msg, "ping", 4) == 0) { @@ -118,20 +107,16 @@ static void onmessasge(char *msg, size_t len, void *user_data) { } } -static void on_request_keyframe(void *data) { - +static void on_request_keyframe(void* data) { printf("request keyframe\n"); } static void signal_handler(int signal) { - g_interrupted = 1; } -static void* peer_singaling_task(void *data) { - +static void* peer_singaling_task(void* data) { while (!g_interrupted) { - peer_signaling_loop(); usleep(1000); } @@ -139,27 +124,24 @@ static void* peer_singaling_task(void *data) { pthread_exit(NULL); } -static void* peer_connection_task(void *data) { - +static void* peer_connection_task(void* data) { while (!g_interrupted) { - peer_connection_loop(g_pc); - usleep(1000); + usleep(1000); } - pthread_exit(NULL); + pthread_exit(NULL); } -void get_hwaddr(char *buf, size_t size) { - - uint8_t *ptr; +void get_hwaddr(char* buf, size_t size) { + uint8_t* ptr; int fd; struct ifreq ifr; memset(buf, 0, size); fd = socket(AF_INET, SOCK_DGRAM, 0); - if(fd < 0) + if (fd < 0) return; ifr.ifr_addr.sa_family = AF_INET; @@ -169,15 +151,12 @@ void get_hwaddr(char *buf, size_t size) { if (ioctl(fd, SIOCGIFHWADDR, &ifr) == 0) { ptr = (uint8_t*)&ifr.ifr_ifru.ifru_hwaddr.sa_data[0]; snprintf(buf, size, "%02x%02x%02x%02x%02x%02x", *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3), *(ptr + 4), *(ptr + 5)); - } close(fd); } - -int main(int argc, char *argv[]) { - +int main(int argc, char* argv[]) { char device_id[64]; pthread_t peer_singaling_thread; pthread_t peer_connection_thread; @@ -185,14 +164,13 @@ int main(int argc, char *argv[]) { signal(SIGINT, signal_handler); PeerConfiguration config = { - .ice_servers = { - { .urls = "stun:stun.l.google.com:19302" }, - }, - .datachannel = DATA_CHANNEL_STRING, - .video_codec = CODEC_H264, - .audio_codec = CODEC_PCMA, - .on_request_keyframe = on_request_keyframe - }; + .ice_servers = { + {.urls = "stun:stun.l.google.com:19302"}, + }, + .datachannel = DATA_CHANNEL_STRING, + .video_codec = CODEC_H264, + .audio_codec = CODEC_PCMA, + .on_request_keyframe = on_request_keyframe}; strcpy(device_id, "rpi-"); get_hwaddr(device_id + 4, sizeof(device_id) - 4); @@ -226,7 +204,6 @@ int main(int argc, char *argv[]) { pthread_create(&peer_singaling_thread, NULL, peer_singaling_task, NULL); while (!g_interrupted) { - sleep(1); } diff --git a/src/address.c b/src/address.c index 541538c..34db93d 100644 --- a/src/address.c +++ b/src/address.c @@ -1,15 +1,15 @@ -#include +#include +#include #include #include -#include -#include -#include +#include #include +#include -#include "utils.h" #include "address.h" +#include "utils.h" -void addr_set_family(Address *addr, int family) { +void addr_set_family(Address* addr, int family) { switch (family) { case AF_INET6: addr->family = AF_INET6; @@ -21,7 +21,7 @@ void addr_set_family(Address *addr, int family) { } } -void addr_set_port(Address *addr, uint16_t port) { +void addr_set_port(Address* addr, uint16_t port) { addr->port = port; switch (addr->family) { case AF_INET6: @@ -34,8 +34,7 @@ void addr_set_port(Address *addr, uint16_t port) { } } - -int addr_from_string(const char *buf, Address *addr) { +int addr_from_string(const char* buf, Address* addr) { if (inet_pton(AF_INET, buf, &(addr->sin.sin_addr)) == 1) { addr_set_family(addr, AF_INET); return 1; @@ -46,20 +45,19 @@ int addr_from_string(const char *buf, Address *addr) { return 0; } -int addr_to_string(const Address *addr, char *buf, size_t len) { - +int addr_to_string(const Address* addr, char* buf, size_t len) { memset(buf, 0, sizeof(len)); switch (addr->family) { - case AF_INET6: - return inet_ntop(AF_INET6, &addr->sin6.sin6_addr, buf, len) != NULL; - case AF_INET: - default: - return inet_ntop(AF_INET, &addr->sin.sin_addr, buf, len) != NULL; + case AF_INET6: + return inet_ntop(AF_INET6, &addr->sin6.sin6_addr, buf, len) != NULL; + case AF_INET: + default: + return inet_ntop(AF_INET, &addr->sin.sin_addr, buf, len) != NULL; } return 0; } -int addr_equal(const Address *a, const Address *b) { +int addr_equal(const Address* a, const Address* b) { // TODO return 1; } diff --git a/src/address.h b/src/address.h index a036144..8dbbbf8 100644 --- a/src/address.h +++ b/src/address.h @@ -2,8 +2,8 @@ #define ADDRESS_H_ #include -#include #include +#include #define ADDRSTRLEN INET6_ADDRSTRLEN @@ -14,18 +14,18 @@ typedef struct Address { uint16_t port; } Address; -void addr_set_family(Address *addr, int family); +void addr_set_family(Address* addr, int family); -void addr_set_port(Address *addr, uint16_t port); +void addr_set_port(Address* addr, uint16_t port); -int addr_inet6_validate(const char *ipv6, size_t len, Address *addr); +int addr_inet6_validate(const char* ipv6, size_t len, Address* addr); -int addr_inet_validate(const char *ipv4, size_t len, Address *addr); +int addr_inet_validate(const char* ipv4, size_t len, Address* addr); -int addr_to_string(const Address *addr, char *buf, size_t len); +int addr_to_string(const Address* addr, char* buf, size_t len); -int addr_from_string(const char *str, Address *addr); +int addr_from_string(const char* str, Address* addr); -int addr_equal(const Address *a, const Address *b); +int addr_equal(const Address* a, const Address* b); -#endif // ADDRESS_H_ +#endif // ADDRESS_H_ diff --git a/src/agent.c b/src/agent.c index e9134eb..4811eac 100644 --- a/src/agent.c +++ b/src/agent.c @@ -1,26 +1,25 @@ +#include #include #include #include -#include -#include -#include #include +#include +#include #include -#include "socket.h" -#include "utils.h" -#include "stun.h" -#include "ice.h" -#include "base64.h" #include "agent.h" +#include "base64.h" +#include "ice.h" #include "ports.h" +#include "socket.h" +#include "stun.h" +#include "utils.h" #define AGENT_POLL_TIMEOUT 1 #define AGENT_CONNCHECK_MAX 300 #define AGENT_CONNCHECK_PERIOD 100 -static int agent_create_sockets(Agent *agent) { - +static int agent_create_sockets(Agent* agent) { int ret; if ((ret = udp_socket_open(&agent->udp_sockets[0], AF_INET, 0)) < 0) { LOGE("Failed to create UDP socket."); @@ -38,8 +37,7 @@ static int agent_create_sockets(Agent *agent) { return 0; } -static int agent_socket_recv(Agent *agent, Address *addr, uint8_t *buf, int len) { - +static int agent_socket_recv(Agent* agent, Address* addr, uint8_t* buf, int len) { int ret = -1; int i = 0; int maxfd = 0; @@ -75,8 +73,7 @@ static int agent_socket_recv(Agent *agent, Address *addr, uint8_t *buf, int len) return ret; } -static int agent_socket_send(Agent *agent, Address *addr, const uint8_t *buf, int len) { - +static int agent_socket_send(Agent* agent, Address* addr, const uint8_t* buf, int len) { switch (addr->family) { case AF_INET6: return udp_socket_sendto(&agent->udp_sockets[1], addr, buf, len); @@ -87,30 +84,28 @@ static int agent_socket_send(Agent *agent, Address *addr, const uint8_t *buf, in return -1; } -static int agent_create_host_addr(Agent *agent) { - - UdpSocket *udp_socket; +static int agent_create_host_addr(Agent* agent) { + UdpSocket* udp_socket; udp_socket = &agent->udp_sockets[0]; if (ports_get_host_addr(&udp_socket->bind_addr)) { - //LOGD("addr: %d.%d.%d.%d", udp_socket->bind_addr.ipv4[0], udp_socket->bind_addr.ipv4[1], udp_socket->bind_addr.ipv4[2], udp_socket->bind_addr.ipv4[3]); - IceCandidate *ice_candidate = agent->local_candidates + agent->local_candidates_count++; + // LOGD("addr: %d.%d.%d.%d", udp_socket->bind_addr.ipv4[0], udp_socket->bind_addr.ipv4[1], udp_socket->bind_addr.ipv4[2], udp_socket->bind_addr.ipv4[3]); + IceCandidate* ice_candidate = agent->local_candidates + agent->local_candidates_count++; ice_candidate_create(ice_candidate, agent->local_candidates_count, ICE_CANDIDATE_TYPE_HOST, &udp_socket->bind_addr); } #if CONFIG_IPV6 udp_socket = &agent->udp_sockets[1]; if (ports_get_host_addr(&udp_socket->bind_addr)) { - //LOGD("addr: %x:%x:%x:%x:%x:%x:%x:%x", udp_socket->bind_addr.ipv6[0], udp_socket->bind_addr.ipv6[1], udp_socket->bind_addr.ipv6[2], udp_socket->bind_addr.ipv6[3], udp_socket->bind_addr.ipv6[4], udp_socket->bind_addr.ipv6[5], udp_socket->bind_addr.ipv6[6], udp_socket->bind_addr.ipv6[7]); - IceCandidate *ice_candidate = agent->local_candidates + agent->local_candidates_count++; + // LOGD("addr: %x:%x:%x:%x:%x:%x:%x:%x", udp_socket->bind_addr.ipv6[0], udp_socket->bind_addr.ipv6[1], udp_socket->bind_addr.ipv6[2], udp_socket->bind_addr.ipv6[3], udp_socket->bind_addr.ipv6[4], udp_socket->bind_addr.ipv6[5], udp_socket->bind_addr.ipv6[6], udp_socket->bind_addr.ipv6[7]); + IceCandidate* ice_candidate = agent->local_candidates + agent->local_candidates_count++; ice_candidate_create(ice_candidate, agent->local_candidates_count, ICE_CANDIDATE_TYPE_HOST, &udp_socket->bind_addr); } #endif return 0; } -static int agent_create_bind_addr(Agent *agent, Address *serv_addr) { - +static int agent_create_bind_addr(Agent* agent, Address* serv_addr) { int ret = -1; int retry = 0; Address bind_addr; @@ -143,13 +138,12 @@ static int agent_create_bind_addr(Agent *agent, Address *serv_addr) { stun_parse_msg_buf(&recv_msg); memcpy(&bind_addr, &recv_msg.mapped_addr, sizeof(Address)); - IceCandidate *ice_candidate = agent->local_candidates + agent->local_candidates_count++; + IceCandidate* ice_candidate = agent->local_candidates + agent->local_candidates_count++; ice_candidate_create(ice_candidate, agent->local_candidates_count, ICE_CANDIDATE_TYPE_SRFLX, &bind_addr); return ret; } -static int agent_create_turn_addr(Agent *agent, Address *serv_addr, const char *username, const char *credential) { - +static int agent_create_turn_addr(Agent* agent, Address* serv_addr, const char* username, const char* credential) { int ret = -1; uint32_t attr = ntohl(0x11000000); int retry = 0; @@ -159,7 +153,7 @@ static int agent_create_turn_addr(Agent *agent, Address *serv_addr, const char * memset(&recv_msg, 0, sizeof(recv_msg)); memset(&send_msg, 0, sizeof(send_msg)); stun_msg_create(&send_msg, STUN_METHOD_ALLOCATE); - stun_msg_write_attr(&send_msg, STUN_ATTR_TYPE_REQUESTED_TRANSPORT, sizeof(attr), (char*)&attr); // UDP + stun_msg_write_attr(&send_msg, STUN_ATTR_TYPE_REQUESTED_TRANSPORT, sizeof(attr), (char*)&attr); // UDP stun_msg_write_attr(&send_msg, STUN_ATTR_TYPE_USERNAME, strlen(username), (char*)username); ret = agent_socket_send(agent, serv_addr, send_msg.buf, send_msg.size); @@ -184,10 +178,9 @@ static int agent_create_turn_addr(Agent *agent, Address *serv_addr, const char * stun_parse_msg_buf(&recv_msg); if (recv_msg.stunclass == STUN_CLASS_ERROR && recv_msg.stunmethod == STUN_METHOD_ALLOCATE) { - memset(&send_msg, 0, sizeof(send_msg)); stun_msg_create(&send_msg, STUN_METHOD_ALLOCATE); - stun_msg_write_attr(&send_msg, STUN_ATTR_TYPE_REQUESTED_TRANSPORT, sizeof(attr), (char*)&attr); // UDP + stun_msg_write_attr(&send_msg, STUN_ATTR_TYPE_REQUESTED_TRANSPORT, sizeof(attr), (char*)&attr); // UDP stun_msg_write_attr(&send_msg, STUN_ATTR_TYPE_USERNAME, strlen(username), (char*)username); stun_msg_write_attr(&send_msg, STUN_ATTR_TYPE_NONCE, strlen(recv_msg.nonce), recv_msg.nonce); stun_msg_write_attr(&send_msg, STUN_ATTR_TYPE_REALM, strlen(recv_msg.realm), recv_msg.realm); @@ -212,17 +205,16 @@ static int agent_create_turn_addr(Agent *agent, Address *serv_addr, const char * stun_parse_msg_buf(&recv_msg); memcpy(&turn_addr, &recv_msg.relayed_addr, sizeof(Address)); - IceCandidate *ice_candidate = agent->local_candidates + agent->local_candidates_count++; + IceCandidate* ice_candidate = agent->local_candidates + agent->local_candidates_count++; ice_candidate_create(ice_candidate, agent->local_candidates_count, ICE_CANDIDATE_TYPE_RELAY, &turn_addr); return ret; } -void agent_init(Agent *agent) { +void agent_init(Agent* agent) { agent->local_candidates_count = 0; } -void agent_deinit(Agent *agent) { - +void agent_deinit(Agent* agent) { udp_socket_close(&agent->udp_socket); memset(agent, 0, sizeof(Agent)); } @@ -233,14 +225,13 @@ void agent_deinit(Agent *agent) { * create host candidate * create server-reflexive candidate or relay candidate */ -void agent_gather_candidate(Agent *agent, const char *urls, const char *username, const char *credential) { - - char *pos; +void agent_gather_candidate(Agent* agent, const char* urls, const char* username, const char* credential) { + char* pos; int port; char hostname[64]; char addr_string[ADDRSTRLEN]; int i; - int addr_type[1] = {AF_INET}; // ipv6 no need stun + int addr_type[1] = {AF_INET}; // ipv6 no need stun Address resolved_addr; memset(hostname, 0, sizeof(hostname)); memset(agent, 0, sizeof(Agent)); @@ -249,7 +240,6 @@ void agent_gather_candidate(Agent *agent, const char *urls, const char *username agent_create_host_addr(agent); do { - if ((pos = strstr(urls + 5, ":")) == NULL) { break; } @@ -263,7 +253,6 @@ void agent_gather_candidate(Agent *agent, const char *urls, const char *username snprintf(hostname, pos - urls - 5 + 1, "%s", urls + 5); for (i = 0; i < sizeof(addr_type) / sizeof(addr_type[0]); i++) { - if (ports_resolve_addr(hostname, &resolved_addr) != 0) { continue; } @@ -282,11 +271,9 @@ void agent_gather_candidate(Agent *agent, const char *urls, const char *username } } while (0); - } -void agent_get_local_description(Agent *agent, char *description, int length) { - +void agent_get_local_description(Agent* agent, char* description, int length) { int ncandidates = 0; memset(description, 0, length); @@ -308,18 +295,16 @@ void agent_get_local_description(Agent *agent, char *description, int length) { LOGD("local description:\n%s", description); } -int agent_send(Agent *agent, const uint8_t *buf, int len) { - +int agent_send(Agent* agent, const uint8_t* buf, int len) { return agent_socket_send(agent, &agent->nominated_pair->remote->addr, buf, len); } -static void agent_create_binding_response(Agent *agent, StunMessage *msg, Address *addr) { - +static void agent_create_binding_response(Agent* agent, StunMessage* msg, Address* addr) { char username[584]; char mapped_address[8]; - StunHeader *header; + StunHeader* header; stun_msg_create(msg, STUN_CLASS_RESPONSE | STUN_METHOD_BINDING); - header = (StunHeader *)msg->buf; + header = (StunHeader*)msg->buf; memcpy(header->transaction_id, agent->transaction_id, sizeof(header->transaction_id)); snprintf(username, sizeof(username), "%s:%s", agent->local_ufrag, agent->remote_ufrag); // TODO: XOR-MAPPED-ADDRESS @@ -329,29 +314,27 @@ static void agent_create_binding_response(Agent *agent, StunMessage *msg, Addres stun_msg_finish(msg, STUN_CREDENTIAL_SHORT_TERM, agent->local_upwd, strlen(agent->local_upwd)); } -static void agent_create_binding_request(Agent *agent, StunMessage *msg) { - - uint64_t tie_breaker = 0; // always be controlled +static void agent_create_binding_request(Agent* agent, StunMessage* msg) { + uint64_t tie_breaker = 0; // always be controlled // send binding request stun_msg_create(msg, STUN_CLASS_REQUEST | STUN_METHOD_BINDING); char username[584]; memset(username, 0, sizeof(username)); snprintf(username, sizeof(username), "%s:%s", agent->remote_ufrag, agent->local_ufrag); stun_msg_write_attr(msg, STUN_ATTR_TYPE_USERNAME, strlen(username), username); - stun_msg_write_attr(msg, STUN_ATTR_TYPE_PRIORITY, 4, (char *)&agent->nominated_pair->priority); + stun_msg_write_attr(msg, STUN_ATTR_TYPE_PRIORITY, 4, (char*)&agent->nominated_pair->priority); stun_msg_write_attr(msg, STUN_ATTR_TYPE_USE_CANDIDATE, 0, NULL); - stun_msg_write_attr(msg, STUN_ATTR_TYPE_ICE_CONTROLLED, 8, (char *)&tie_breaker); + stun_msg_write_attr(msg, STUN_ATTR_TYPE_ICE_CONTROLLED, 8, (char*)&tie_breaker); stun_msg_finish(msg, STUN_CREDENTIAL_SHORT_TERM, agent->remote_upwd, strlen(agent->remote_upwd)); } -void agent_process_stun_request(Agent *agent, StunMessage *stun_msg, Address *addr) { - +void agent_process_stun_request(Agent* agent, StunMessage* stun_msg, Address* addr) { StunMessage msg; - StunHeader *header; + StunHeader* header; switch (stun_msg->stunmethod) { case STUN_METHOD_BINDING: if (stun_msg_is_valid(stun_msg->buf, stun_msg->size, agent->local_upwd) == 0) { - header = (StunHeader *)stun_msg->buf; + header = (StunHeader*)stun_msg->buf; memcpy(agent->transaction_id, header->transaction_id, sizeof(header->transaction_id)); agent_create_binding_response(agent, &msg, addr); agent_socket_send(agent, addr, msg.buf, msg.size); @@ -363,8 +346,7 @@ void agent_process_stun_request(Agent *agent, StunMessage *stun_msg, Address *ad } } -void agent_process_stun_response(Agent *agent, StunMessage *stun_msg) { - +void agent_process_stun_response(Agent* agent, StunMessage* stun_msg) { switch (stun_msg->stunmethod) { case STUN_METHOD_BINDING: if (stun_msg_is_valid(stun_msg->buf, stun_msg->size, agent->remote_upwd) == 0) { @@ -376,14 +358,11 @@ void agent_process_stun_response(Agent *agent, StunMessage *stun_msg) { } } - -int agent_recv(Agent *agent, uint8_t *buf, int len) { - +int agent_recv(Agent* agent, uint8_t* buf, int len) { int ret = -1; StunMessage stun_msg; Address addr; if ((ret = agent_socket_recv(agent, &addr, buf, len)) > 0 && stun_probe(buf, len) == 0) { - memcpy(stun_msg.buf, buf, ret); stun_msg.size = ret; stun_parse_msg_buf(&stun_msg); @@ -404,32 +383,27 @@ int agent_recv(Agent *agent, uint8_t *buf, int len) { return ret; } -void agent_set_remote_description(Agent *agent, char *description) { - -/* -a=ice-ufrag:Iexb -a=ice-pwd:IexbSoY7JulyMbjKwISsG9 -a=candidate:1 1 UDP 1 36.231.28.50 38143 typ srflx -*/ +void agent_set_remote_description(Agent* agent, char* description) { + /* + a=ice-ufrag:Iexb + a=ice-pwd:IexbSoY7JulyMbjKwISsG9 + a=candidate:1 1 UDP 1 36.231.28.50 38143 typ srflx + */ int i, j; LOGD("Set remote description:\n%s", description); - char *line_start = description; - char *line_end = NULL; + char* line_start = description; + char* line_end = NULL; while ((line_end = strstr(line_start, "\r\n")) != NULL) { - if (strncmp(line_start, "a=ice-ufrag:", strlen("a=ice-ufrag:")) == 0) { - strncpy(agent->remote_ufrag, line_start + strlen("a=ice-ufrag:"), line_end - line_start - strlen("a=ice-ufrag:")); } else if (strncmp(line_start, "a=ice-pwd:", strlen("a=ice-pwd:")) == 0) { - strncpy(agent->remote_upwd, line_start + strlen("a=ice-pwd:"), line_end - line_start - strlen("a=ice-pwd:")); } else if (strncmp(line_start, "a=candidate:", strlen("a=candidate:")) == 0) { - if (ice_candidate_from_description(&agent->remote_candidates[agent->remote_candidates_count], line_start, line_end) == 0) { agent->remote_candidates_count++; } @@ -445,20 +419,18 @@ a=candidate:1 1 UDP 1 36.231.28.50 38143 typ srflx for (i = 0; i < agent->local_candidates_count; i++) { for (j = 0; j < agent->remote_candidates_count; j++) { if (agent->local_candidates[i].addr.family == agent->remote_candidates[j].addr.family) { - agent->candidate_pairs[agent->candidate_pairs_num].local = &agent->local_candidates[i]; - agent->candidate_pairs[agent->candidate_pairs_num].remote = &agent->remote_candidates[j]; - agent->candidate_pairs[agent->candidate_pairs_num].priority = agent->local_candidates[i].priority + agent->remote_candidates[j].priority; - agent->candidate_pairs[agent->candidate_pairs_num].state = ICE_CANDIDATE_STATE_FROZEN; - agent->candidate_pairs_num++; + agent->candidate_pairs[agent->candidate_pairs_num].local = &agent->local_candidates[i]; + agent->candidate_pairs[agent->candidate_pairs_num].remote = &agent->remote_candidates[j]; + agent->candidate_pairs[agent->candidate_pairs_num].priority = agent->local_candidates[i].priority + agent->remote_candidates[j].priority; + agent->candidate_pairs[agent->candidate_pairs_num].state = ICE_CANDIDATE_STATE_FROZEN; + agent->candidate_pairs_num++; } } } LOGD("candidate pairs num: %d", agent->candidate_pairs_num); } - -int agent_connectivity_check(Agent *agent) { - +int agent_connectivity_check(Agent* agent) { char addr_string[ADDRSTRLEN]; uint8_t buf[1400]; StunMessage msg; @@ -471,7 +443,6 @@ int agent_connectivity_check(Agent *agent) { memset(&msg, 0, sizeof(msg)); if (agent->nominated_pair->conncheck % AGENT_CONNCHECK_PERIOD == 0) { - addr_to_string(&agent->nominated_pair->remote->addr, addr_string, sizeof(addr_string)); LOGD("send binding request to remote ip: %s, port: %d", addr_string, agent->nominated_pair->remote->addr.port); agent_create_binding_request(agent, &msg); @@ -489,11 +460,9 @@ int agent_connectivity_check(Agent *agent) { return -1; } -int agent_select_candidate_pair(Agent *agent) { - +int agent_select_candidate_pair(Agent* agent) { int i; for (i = 0; i < agent->candidate_pairs_num; i++) { - if (agent->candidate_pairs[i].state == ICE_CANDIDATE_STATE_FROZEN) { // nominate this pair agent->nominated_pair = &agent->candidate_pairs[i]; @@ -507,7 +476,6 @@ int agent_select_candidate_pair(Agent *agent) { } agent->candidate_pairs[i].state = ICE_CANDIDATE_STATE_FAILED; } else if (agent->candidate_pairs[i].state == ICE_CANDIDATE_STATE_FAILED) { - } else if (agent->candidate_pairs[i].state == ICE_CANDIDATE_STATE_SUCCEEDED) { agent->selected_pair = &agent->candidate_pairs[i]; return 0; diff --git a/src/agent.h b/src/agent.h index 73a1fc5..9214303 100644 --- a/src/agent.h +++ b/src/agent.h @@ -1,20 +1,20 @@ #ifndef AGENT_H_ #define AGENT_H_ +#include #include #include #include -#include -#include #include +#include #include +#include "base64.h" +#include "ice.h" #include "socket.h" -#include "utils.h" #include "stun.h" -#include "ice.h" -#include "base64.h" +#include "utils.h" #ifndef AGENT_MAX_DESCRIPTION #define AGENT_MAX_DESCRIPTION 40960 @@ -46,7 +46,6 @@ typedef enum AgentMode { typedef struct Agent Agent; struct Agent { - char remote_ufrag[ICE_UFRAG_LENGTH + 1]; char remote_upwd[ICE_UPWD_LENGTH + 1]; @@ -71,8 +70,8 @@ struct Agent { AgentMode mode; IceCandidatePair candidate_pairs[AGENT_MAX_CANDIDATE_PAIRS]; - IceCandidatePair *selected_pair; - IceCandidatePair *nominated_pair; + IceCandidatePair* selected_pair; + IceCandidatePair* nominated_pair; int candidate_pairs_num; @@ -81,31 +80,30 @@ struct Agent { uint32_t transaction_id[3]; }; -void agent_gather_candidate(Agent *agent, const char *urls, const char *username, const char *credential); - -void agent_get_local_description(Agent *agent, char *description, int length); +void agent_gather_candidate(Agent* agent, const char* urls, const char* username, const char* credential); -int agent_loop(Agent *agent); +void agent_get_local_description(Agent* agent, char* description, int length); -int agent_send(Agent *agent, const uint8_t *buf, int len); +int agent_loop(Agent* agent); -int agent_recv(Agent *agent, uint8_t *buf, int len); +int agent_send(Agent* agent, const uint8_t* buf, int len); -void agent_set_remote_description(Agent *agent, char *description); +int agent_recv(Agent* agent, uint8_t* buf, int len); -void *agent_thread(void *arg); +void agent_set_remote_description(Agent* agent, char* description); -int agent_select_candidate_pair(Agent *agent); +void* agent_thread(void* arg); -void agent_attach_recv_cb(Agent *agent, void (*data_recv_cb)(char *buf, int len, void *user_data)); +int agent_select_candidate_pair(Agent* agent); -void agent_set_host_address(Agent *agent, Address *addr); +void agent_attach_recv_cb(Agent* agent, void (*data_recv_cb)(char* buf, int len, void* user_data)); -int agent_connectivity_check(Agent *agent); +void agent_set_host_address(Agent* agent, Address* addr); -void agent_init(Agent *agent); +int agent_connectivity_check(Agent* agent); -void agent_deinit(Agent *agent); +void agent_init(Agent* agent); -#endif // AGENT_H_ +void agent_deinit(Agent* agent); +#endif // AGENT_H_ diff --git a/src/base64.c b/src/base64.c index 61a47f5..d367c33 100644 --- a/src/base64.c +++ b/src/base64.c @@ -4,40 +4,37 @@ static const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -void base64_encode(const unsigned char *input, int input_len, char *output, int output_len) { - +void base64_encode(const unsigned char* input, int input_len, char* output, int output_len) { int i, j; - unsigned char buf[3]; - int buf_len; - int output_index = 0; - - for (i = 0; i < input_len; i += 3) { - buf_len = 0; - for (j = 0; j < 3; j++) { - if (i + j < input_len) { - buf[j] = input[i + j]; - buf_len++; - } else { - buf[j] = 0; - } - } - - if (output_index + 4 > output_len) { - return; - } - - output[output_index++] = base64_table[(buf[0] & 0xFC) >> 2]; - output[output_index++] = base64_table[((buf[0] & 0x03) << 4) | ((buf[1] & 0xF0) >> 4)]; - output[output_index++] = (buf_len > 1) ? base64_table[((buf[1] & 0x0F) << 2) | ((buf[2] & 0xC0) >> 6)] : '='; - output[output_index++] = (buf_len > 2) ? base64_table[buf[2] & 0x3F] : '='; - } - - output[output_index] = '\0'; + unsigned char buf[3]; + int buf_len; + int output_index = 0; + for (i = 0; i < input_len; i += 3) { + buf_len = 0; + for (j = 0; j < 3; j++) { + if (i + j < input_len) { + buf[j] = input[i + j]; + buf_len++; + } else { + buf[j] = 0; + } + } + + if (output_index + 4 > output_len) { + return; + } + + output[output_index++] = base64_table[(buf[0] & 0xFC) >> 2]; + output[output_index++] = base64_table[((buf[0] & 0x03) << 4) | ((buf[1] & 0xF0) >> 4)]; + output[output_index++] = (buf_len > 1) ? base64_table[((buf[1] & 0x0F) << 2) | ((buf[2] & 0xC0) >> 6)] : '='; + output[output_index++] = (buf_len > 2) ? base64_table[buf[2] & 0x3F] : '='; + } + + output[output_index] = '\0'; } -int base64_decode(const char *input, int input_len, unsigned char *output, int output_len) { - +int base64_decode(const char* input, int input_len, unsigned char* output, int output_len) { int i, j; unsigned char buf[4]; int buf_len; @@ -46,30 +43,28 @@ int base64_decode(const char *input, int input_len, unsigned char *output, int o for (i = 0; i < input_len; i += 4) { buf_len = 0; for (j = 0; j < 4; j++) { - if (i + j < input_len) { - if (input[i + j] != '=') { - buf[j] = strchr(base64_table, input[i + j]) - base64_table; - buf_len++; - } else { - buf[j] = 0; - } - } - } - - if (output_index + buf_len > output_len) { - return -1; - } - - output[output_index++] = (buf[0] << 2) | ((buf[1] & 0x30) >> 4); - if (buf_len > 2) { - output[output_index++] = ((buf[1] & 0x0F) << 4) | ((buf[2] & 0x3C) >> 2); - } - if (buf_len > 3) { - output[output_index++] = ((buf[2] & 0x03) << 6) | buf[3]; - } - } - - return output_index; - + if (i + j < input_len) { + if (input[i + j] != '=') { + buf[j] = strchr(base64_table, input[i + j]) - base64_table; + buf_len++; + } else { + buf[j] = 0; + } + } + } + + if (output_index + buf_len > output_len) { + return -1; + } + + output[output_index++] = (buf[0] << 2) | ((buf[1] & 0x30) >> 4); + if (buf_len > 2) { + output[output_index++] = ((buf[1] & 0x0F) << 4) | ((buf[2] & 0x3C) >> 2); + } + if (buf_len > 3) { + output[output_index++] = ((buf[2] & 0x03) << 6) | buf[3]; + } + } + + return output_index; } - diff --git a/src/base64.h b/src/base64.h index 4d45fde..950d68c 100644 --- a/src/base64.h +++ b/src/base64.h @@ -1,7 +1,5 @@ #include -void base64_encode(const unsigned char *input, int input_len, char *output, int output_len); - -int base64_decode(const char *input, int input_len, unsigned char *output, int output_len); - +void base64_encode(const unsigned char* input, int input_len, char* output, int output_len); +int base64_decode(const char* input, int input_len, unsigned char* output, int output_len); diff --git a/src/buffer.c b/src/buffer.c index a0bf938..ac3a47c 100644 --- a/src/buffer.c +++ b/src/buffer.c @@ -1,14 +1,13 @@ +#include #include #include -#include #include -#include "utils.h" #include "buffer.h" +#include "utils.h" Buffer* buffer_new(int size) { - - Buffer *rb; + Buffer* rb; rb = (Buffer*)calloc(1, sizeof(Buffer)); rb->data = (uint8_t*)calloc(1, size); @@ -19,24 +18,20 @@ Buffer* buffer_new(int size) { return rb; } -void buffer_clear(Buffer *rb) { - +void buffer_clear(Buffer* rb) { rb->head = 0; rb->tail = 0; } -void buffer_free(Buffer *rb) { - +void buffer_free(Buffer* rb) { if (rb) { - free(rb->data); rb->data = NULL; rb = NULL; } } -int buffer_push_tail(Buffer *rb, const uint8_t *data, int size) { - +int buffer_push_tail(Buffer* rb, const uint8_t* data, int size) { int free_space = (rb->size + rb->head - rb->tail - 1) % rb->size; int align_size = ALIGN32(size + 4); @@ -49,21 +44,18 @@ int buffer_push_tail(Buffer *rb, const uint8_t *data, int size) { int tail_end = (rb->tail + align_size) % rb->size; if (tail_end < rb->tail) { - if (rb->head < align_size) { - LOGE("no enough space"); return -1; } - int *p = (int*)(rb->data + rb->tail); + int* p = (int*)(rb->data + rb->tail); *p = size; - memcpy(rb->data, data, size); + memcpy(rb->data, data, size); rb->tail = size; } else { - - int *p = (int*)(rb->data + rb->tail); + int* p = (int*)(rb->data + rb->tail); *p = size; memcpy(rb->data + rb->tail + 4, data, size); rb->tail = tail_end; @@ -72,10 +64,8 @@ int buffer_push_tail(Buffer *rb, const uint8_t *data, int size) { return size; } -uint8_t* buffer_peak_head(Buffer *rb, int *size) { - +uint8_t* buffer_peak_head(Buffer* rb, int* size) { if (!rb || rb->head == rb->tail) { - return NULL; } @@ -86,34 +76,28 @@ uint8_t* buffer_peak_head(Buffer *rb, int *size) { int head_end = (rb->head + align_size) % rb->size; if (head_end < rb->head) { - return rb->data; } else { - return rb->data + (rb->head + 4); } } -void buffer_pop_head(Buffer *rb) { - +void buffer_pop_head(Buffer* rb) { if (!rb || rb->head == rb->tail) { return; } - int *size = (int*)(rb->data + rb->head); + int* size = (int*)(rb->data + rb->head); int align_size = ALIGN32(*size + 4); int head_end = (rb->head + align_size) % rb->size; if (head_end < rb->head) { - rb->head = *size; } else { - rb->head = rb->head + align_size; } } - diff --git a/src/buffer.h b/src/buffer.h index 9d7583a..2e8b95d 100644 --- a/src/buffer.h +++ b/src/buffer.h @@ -1,13 +1,12 @@ #ifndef BUFFER_H_ #define BUFFER_H_ +#include #include #include -#include typedef struct Buffer { - - uint8_t *data; + uint8_t* data; int size; int head; int tail; @@ -16,14 +15,14 @@ typedef struct Buffer { Buffer* buffer_new(int size); -void buffer_free(Buffer *rb); +void buffer_free(Buffer* rb); + +uint8_t* buffer_peak_head(Buffer* rb, int* size); -uint8_t* buffer_peak_head(Buffer *rb, int *size); +int buffer_push_tail(Buffer* rb, const uint8_t* data, int size); -int buffer_push_tail(Buffer *rb, const uint8_t *data, int size); - -void buffer_pop_head(Buffer *rb); +void buffer_pop_head(Buffer* rb); -void buffer_clear(Buffer *rb); +void buffer_clear(Buffer* rb); -#endif // BUFFER_H_ +#endif // BUFFER_H_ diff --git a/src/config.h b/src/config.h index 1c6a0c2..bbfaeae 100644 --- a/src/config.h +++ b/src/config.h @@ -16,13 +16,13 @@ #define DATA_RB_DATA_LENGTH (SCTP_MTU * 128) #endif -#define AUDIO_LATENCY 20 // ms +#define AUDIO_LATENCY 20 // ms #define KEEPALIVE_CONNCHECK 10000 #define CONFIG_IPV6 0 // default use wifi interface #define IFR_NAME "w" -//#define LOG_LEVEL LEVEL_DEBUG -#define LOG_REDIRECT 0 +// #define LOG_LEVEL LEVEL_DEBUG +#define LOG_REDIRECT 0 -#endif // CONFIG_H_ +#endif // CONFIG_H_ diff --git a/src/dtls_srtp.c b/src/dtls_srtp.c index 79e412f..e1dc388 100644 --- a/src/dtls_srtp.c +++ b/src/dtls_srtp.c @@ -1,20 +1,19 @@ +#include #include #include #include #include -#include -#include "mbedtls/ssl.h" -#include "dtls_srtp.h" #include "address.h" -#include "socket.h" #include "config.h" +#include "dtls_srtp.h" +#include "mbedtls/ssl.h" +#include "socket.h" #include "utils.h" typedef struct DtlsHeader DtlsHeader; struct DtlsHeader { - uint8_t content_type; uint16_t version; uint16_t epoch; @@ -22,13 +21,11 @@ struct DtlsHeader { uint16_t seqnum_hi; uint16_t length; -}__attribute__((packed)); - +} __attribute__((packed)); -int dtls_srtp_udp_send(void *ctx, const uint8_t *buf, size_t len) { - - DtlsSrtp *dtls_srtp = (DtlsSrtp *) ctx; - UdpSocket *udp_socket = (UdpSocket*)dtls_srtp->user_data; +int dtls_srtp_udp_send(void* ctx, const uint8_t* buf, size_t len) { + DtlsSrtp* dtls_srtp = (DtlsSrtp*)ctx; + UdpSocket* udp_socket = (UdpSocket*)dtls_srtp->user_data; int ret = udp_socket_sendto(udp_socket, dtls_srtp->remote_addr, buf, len); @@ -37,15 +34,13 @@ int dtls_srtp_udp_send(void *ctx, const uint8_t *buf, size_t len) { return ret; } -int dtls_srtp_udp_recv(void *ctx, uint8_t *buf, size_t len) { - - DtlsSrtp *dtls_srtp = (DtlsSrtp *) ctx; - UdpSocket *udp_socket = (UdpSocket*)dtls_srtp->user_data; +int dtls_srtp_udp_recv(void* ctx, uint8_t* buf, size_t len) { + DtlsSrtp* dtls_srtp = (DtlsSrtp*)ctx; + UdpSocket* udp_socket = (UdpSocket*)dtls_srtp->user_data; int ret; while ((ret = udp_socket_recvfrom(udp_socket, &udp_socket->bind_addr, buf, len)) <= 0) { - usleep(1000); } @@ -54,8 +49,7 @@ int dtls_srtp_udp_recv(void *ctx, uint8_t *buf, size_t len) { return ret; } -static void dtls_srtp_x509_digest(const mbedtls_x509_crt *crt, char *buf) { - +static void dtls_srtp_x509_digest(const mbedtls_x509_crt* crt, char* buf) { int i; unsigned char digest[32]; @@ -63,11 +57,10 @@ static void dtls_srtp_x509_digest(const mbedtls_x509_crt *crt, char *buf) { mbedtls_sha256_init(&sha256_ctx); mbedtls_sha256_starts(&sha256_ctx, 0); mbedtls_sha256_update(&sha256_ctx, crt->raw.p, crt->raw.len); - mbedtls_sha256_finish(&sha256_ctx, (unsigned char *) digest); + mbedtls_sha256_finish(&sha256_ctx, (unsigned char*)digest); mbedtls_sha256_free(&sha256_ctx); - for(i = 0; i < 32; i++) { - + for (i = 0; i < 32; i++) { snprintf(buf, 4, "%.2X:", digest[i]); buf += 3; } @@ -76,33 +69,30 @@ static void dtls_srtp_x509_digest(const mbedtls_x509_crt *crt, char *buf) { } // Do not verify CA -static int dtls_srtp_cert_verify(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags) { - +static int dtls_srtp_cert_verify(void* data, mbedtls_x509_crt* crt, int depth, uint32_t* flags) { *flags &= ~(MBEDTLS_X509_BADCERT_NOT_TRUSTED | MBEDTLS_X509_BADCERT_CN_MISMATCH); return 0; } -static int dtls_srtp_selfsign_cert(DtlsSrtp *dtls_srtp) { - +static int dtls_srtp_selfsign_cert(DtlsSrtp* dtls_srtp) { int ret; mbedtls_x509write_cert crt; - unsigned char *cert_buf = NULL; - const char *serial = "peer"; - const char *pers = "dtls_srtp"; + unsigned char* cert_buf = NULL; + const char* serial = "peer"; + const char* pers = "dtls_srtp"; - cert_buf = (unsigned char *)malloc(RSA_KEY_LENGTH * 2); + cert_buf = (unsigned char*)malloc(RSA_KEY_LENGTH * 2); if (cert_buf == NULL) { - LOGE("malloc failed"); return -1; } - mbedtls_ctr_drbg_seed(&dtls_srtp->ctr_drbg, mbedtls_entropy_func, &dtls_srtp->entropy, (const unsigned char *) pers, strlen(pers)); + mbedtls_ctr_drbg_seed(&dtls_srtp->ctr_drbg, mbedtls_entropy_func, &dtls_srtp->entropy, (const unsigned char*)pers, strlen(pers)); mbedtls_pk_setup(&dtls_srtp->pkey, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)); - + mbedtls_rsa_gen_key(mbedtls_pk_rsa(dtls_srtp->pkey), mbedtls_ctr_drbg_random, &dtls_srtp->ctr_drbg, RSA_KEY_LENGTH, 65537); mbedtls_x509write_crt_init(&crt); @@ -125,14 +115,13 @@ static int dtls_srtp_selfsign_cert(DtlsSrtp *dtls_srtp) { mbedtls_x509write_crt_set_validity(&crt, "20180101000000", "20280101000000"); - ret = mbedtls_x509write_crt_pem(&crt, cert_buf, 2*RSA_KEY_LENGTH, mbedtls_ctr_drbg_random, &dtls_srtp->ctr_drbg); + ret = mbedtls_x509write_crt_pem(&crt, cert_buf, 2 * RSA_KEY_LENGTH, mbedtls_ctr_drbg_random, &dtls_srtp->ctr_drbg); if (ret < 0) { - LOGE("mbedtls_x509write_crt_pem failed"); } - mbedtls_x509_crt_parse(&dtls_srtp->cert, cert_buf, 2*RSA_KEY_LENGTH); + mbedtls_x509_crt_parse(&dtls_srtp->cert, cert_buf, 2 * RSA_KEY_LENGTH); mbedtls_x509write_crt_free(&crt); @@ -141,15 +130,13 @@ static int dtls_srtp_selfsign_cert(DtlsSrtp *dtls_srtp) { return ret; } -int dtls_srtp_init(DtlsSrtp *dtls_srtp, DtlsSrtpRole role, void *user_data) { - +int dtls_srtp_init(DtlsSrtp* dtls_srtp, DtlsSrtpRole role, void* user_data) { static const mbedtls_ssl_srtp_profile default_profiles[] = { - MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80, - MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32, - MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80, - MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32, - MBEDTLS_TLS_SRTP_UNSET - }; + MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80, + MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32, + MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80, + MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32, + MBEDTLS_TLS_SRTP_UNSET}; dtls_srtp->role = role; dtls_srtp->state = DTLS_SRTP_STATE_INIT; @@ -183,11 +170,10 @@ int dtls_srtp_init(DtlsSrtp *dtls_srtp, DtlsSrtpRole role, void *user_data) { mbedtls_ssl_conf_read_timeout(&dtls_srtp->conf, 1000); if (dtls_srtp->role == DTLS_SRTP_ROLE_SERVER) { - mbedtls_ssl_config_defaults(&dtls_srtp->conf, - MBEDTLS_SSL_IS_SERVER, - MBEDTLS_SSL_TRANSPORT_DATAGRAM, - MBEDTLS_SSL_PRESET_DEFAULT); + MBEDTLS_SSL_IS_SERVER, + MBEDTLS_SSL_TRANSPORT_DATAGRAM, + MBEDTLS_SSL_PRESET_DEFAULT); mbedtls_ssl_cookie_init(&dtls_srtp->cookie_ctx); @@ -196,11 +182,10 @@ int dtls_srtp_init(DtlsSrtp *dtls_srtp, DtlsSrtpRole role, void *user_data) { mbedtls_ssl_conf_dtls_cookies(&dtls_srtp->conf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check, &dtls_srtp->cookie_ctx); } else { - mbedtls_ssl_config_defaults(&dtls_srtp->conf, - MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_DATAGRAM, - MBEDTLS_SSL_PRESET_DEFAULT); + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_DATAGRAM, + MBEDTLS_SSL_PRESET_DEFAULT); } dtls_srtp_x509_digest(&dtls_srtp->cert, dtls_srtp->local_fingerprint); @@ -216,8 +201,7 @@ int dtls_srtp_init(DtlsSrtp *dtls_srtp, DtlsSrtpRole role, void *user_data) { return 0; } -void dtls_srtp_deinit(DtlsSrtp *dtls_srtp) { - +void dtls_srtp_deinit(DtlsSrtp* dtls_srtp) { mbedtls_ssl_free(&dtls_srtp->ssl); mbedtls_ssl_config_free(&dtls_srtp->conf); @@ -227,28 +211,21 @@ void dtls_srtp_deinit(DtlsSrtp *dtls_srtp) { mbedtls_ctr_drbg_free(&dtls_srtp->ctr_drbg); if (dtls_srtp->role == DTLS_SRTP_ROLE_SERVER) { - mbedtls_ssl_cookie_free(&dtls_srtp->cookie_ctx); } if (dtls_srtp->state == DTLS_SRTP_STATE_CONNECTED) { - srtp_dealloc(dtls_srtp->srtp_in); srtp_dealloc(dtls_srtp->srtp_out); } } -static void dtls_srtp_key_derivation(void *context, mbedtls_ssl_key_export_type secret_type, - const unsigned char *secret, size_t secret_len, - const unsigned char client_random[32], - const unsigned char server_random[32], - mbedtls_tls_prf_types tls_prf_type) { - - DtlsSrtp *dtls_srtp = (DtlsSrtp *) context; +static void dtls_srtp_key_derivation(void* context, mbedtls_ssl_key_export_type secret_type, const unsigned char* secret, size_t secret_len, const unsigned char client_random[32], const unsigned char server_random[32], mbedtls_tls_prf_types tls_prf_type) { + DtlsSrtp* dtls_srtp = (DtlsSrtp*)context; int ret; - const char *dtls_srtp_label = "EXTRACTOR-dtls_srtp"; + const char* dtls_srtp_label = "EXTRACTOR-dtls_srtp"; unsigned char randbytes[64]; @@ -259,8 +236,7 @@ static void dtls_srtp_key_derivation(void *context, mbedtls_ssl_key_export_type // Export keying material if ((ret = mbedtls_ssl_tls_prf(tls_prf_type, secret, secret_len, dtls_srtp_label, - randbytes, sizeof(randbytes), key_material, sizeof(key_material))) != 0) { - + randbytes, sizeof(randbytes), key_material, sizeof(key_material))) != 0) { LOGE("mbedtls_ssl_tls_prf failed(%d)", ret); return; } @@ -291,7 +267,7 @@ static void dtls_srtp_key_derivation(void *context, mbedtls_ssl_key_export_type memset(&dtls_srtp->remote_policy, 0, sizeof(dtls_srtp->remote_policy)); - srtp_crypto_policy_set_rtp_default(&dtls_srtp->remote_policy.rtp); + srtp_crypto_policy_set_rtp_default(&dtls_srtp->remote_policy.rtp); srtp_crypto_policy_set_rtcp_default(&dtls_srtp->remote_policy.rtcp); memcpy(dtls_srtp->remote_policy_key, key_material, SRTP_MASTER_KEY_LENGTH); @@ -302,7 +278,6 @@ static void dtls_srtp_key_derivation(void *context, mbedtls_ssl_key_export_type dtls_srtp->remote_policy.next = NULL; if (srtp_create(&dtls_srtp->srtp_in, &dtls_srtp->remote_policy) != srtp_err_status_ok) { - LOGD("Error creating inbound SRTP session for component"); return; } @@ -323,7 +298,6 @@ static void dtls_srtp_key_derivation(void *context, mbedtls_ssl_key_export_type dtls_srtp->local_policy.next = NULL; if (srtp_create(&dtls_srtp->srtp_out, &dtls_srtp->local_policy) != srtp_err_status_ok) { - LOGE("Error creating outbound SRTP session"); return; } @@ -332,20 +306,18 @@ static void dtls_srtp_key_derivation(void *context, mbedtls_ssl_key_export_type dtls_srtp->state = DTLS_SRTP_STATE_CONNECTED; } -static int dtls_srtp_do_handshake(DtlsSrtp *dtls_srtp) { - +static int dtls_srtp_do_handshake(DtlsSrtp* dtls_srtp) { int ret; - - static mbedtls_timing_delay_context timer; + + static mbedtls_timing_delay_context timer; mbedtls_ssl_set_timer_cb(&dtls_srtp->ssl, &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); mbedtls_ssl_set_export_keys_cb(&dtls_srtp->ssl, dtls_srtp_key_derivation, dtls_srtp); mbedtls_ssl_set_bio(&dtls_srtp->ssl, dtls_srtp, dtls_srtp->udp_send, dtls_srtp->udp_recv, NULL); - - do { + do { ret = mbedtls_ssl_handshake(&dtls_srtp->ssl); } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); @@ -353,32 +325,27 @@ static int dtls_srtp_do_handshake(DtlsSrtp *dtls_srtp) { return ret; } -static int dtls_srtp_handshake_server(DtlsSrtp *dtls_srtp) { - +static int dtls_srtp_handshake_server(DtlsSrtp* dtls_srtp) { int ret; while (1) { - unsigned char client_ip[] = "test"; mbedtls_ssl_session_reset(&dtls_srtp->ssl); - mbedtls_ssl_set_client_transport_id(&dtls_srtp->ssl, client_ip, sizeof(client_ip)); + mbedtls_ssl_set_client_transport_id(&dtls_srtp->ssl, client_ip, sizeof(client_ip)); ret = dtls_srtp_do_handshake(dtls_srtp); if (ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) { - LOGD("DTLS hello verification requested"); } else if (ret != 0) { - - LOGE("failed! mbedtls_ssl_handshake returned -0x%.4x", (unsigned int) -ret); + LOGE("failed! mbedtls_ssl_handshake returned -0x%.4x", (unsigned int)-ret); break; } else { - break; } } @@ -388,15 +355,13 @@ static int dtls_srtp_handshake_server(DtlsSrtp *dtls_srtp) { return ret; } -static int dtls_srtp_handshake_client(DtlsSrtp *dtls_srtp) { - +static int dtls_srtp_handshake_client(DtlsSrtp* dtls_srtp) { int ret; ret = dtls_srtp_do_handshake(dtls_srtp); if (ret != 0) { - - LOGE("failed! mbedtls_ssl_handshake returned -0x%.4x\n\n", (unsigned int) -ret); + LOGE("failed! mbedtls_ssl_handshake returned -0x%.4x\n\n", (unsigned int)-ret); } int flags; @@ -420,21 +385,16 @@ static int dtls_srtp_handshake_client(DtlsSrtp *dtls_srtp) { return ret; } - -int dtls_srtp_handshake(DtlsSrtp *dtls_srtp, Address *addr) { - +int dtls_srtp_handshake(DtlsSrtp* dtls_srtp, Address* addr) { int ret; dtls_srtp->remote_addr = addr; if (dtls_srtp->role == DTLS_SRTP_ROLE_SERVER) { - ret = dtls_srtp_handshake_server(dtls_srtp); } else { - ret = dtls_srtp_handshake_client(dtls_srtp); - } // XXX: Not sure if this is needed @@ -458,10 +418,8 @@ int dtls_srtp_handshake(DtlsSrtp *dtls_srtp, Address *addr) { return ret; } -void dtls_srtp_reset_session(DtlsSrtp *dtls_srtp) { - +void dtls_srtp_reset_session(DtlsSrtp* dtls_srtp) { if (dtls_srtp->state == DTLS_SRTP_STATE_CONNECTED) { - srtp_dealloc(dtls_srtp->srtp_in); srtp_dealloc(dtls_srtp->srtp_out); mbedtls_ssl_session_reset(&dtls_srtp->ssl); @@ -470,26 +428,22 @@ void dtls_srtp_reset_session(DtlsSrtp *dtls_srtp) { dtls_srtp->state = DTLS_SRTP_STATE_INIT; } -int dtls_srtp_write(DtlsSrtp *dtls_srtp, const unsigned char *buf, size_t len) { - +int dtls_srtp_write(DtlsSrtp* dtls_srtp, const unsigned char* buf, size_t len) { int ret; do { - ret = mbedtls_ssl_write(&dtls_srtp->ssl, buf, len); } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); return ret; } -int dtls_srtp_read(DtlsSrtp *dtls_srtp, unsigned char *buf, size_t len) { - +int dtls_srtp_read(DtlsSrtp* dtls_srtp, unsigned char* buf, size_t len) { int ret; memset(buf, 0, len); do { - ret = mbedtls_ssl_read(&dtls_srtp->ssl, buf, len); } while (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE); @@ -497,33 +451,27 @@ int dtls_srtp_read(DtlsSrtp *dtls_srtp, unsigned char *buf, size_t len) { return ret; } -int dtls_srtp_probe(uint8_t *buf) { - - if(buf == NULL) +int dtls_srtp_probe(uint8_t* buf) { + if (buf == NULL) return 0; - //LOGD("DTLS content type: %d, version: %d, epoch: %d, sequence: %d, length: %d (%.4x)", header->content_type, header->version, header->epoch, ntohs(header->seqnum_hi), ntohs(header->length), header->length); + // LOGD("DTLS content type: %d, version: %d, epoch: %d, sequence: %d, length: %d (%.4x)", header->content_type, header->version, header->epoch, ntohs(header->seqnum_hi), ntohs(header->length), header->length); return ((*buf >= 20) && (*buf <= 64)); } -void dtls_srtp_decrypt_rtp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes) { - +void dtls_srtp_decrypt_rtp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes) { srtp_unprotect(dtls_srtp->srtp_in, packet, bytes); } -void dtls_srtp_decrypt_rtcp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes) { - +void dtls_srtp_decrypt_rtcp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes) { srtp_unprotect_rtcp(dtls_srtp->srtp_in, packet, bytes); } -void dtls_srtp_encrypt_rtp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes) { - +void dtls_srtp_encrypt_rtp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes) { srtp_protect(dtls_srtp->srtp_out, packet, bytes); } -void dtls_srtp_encrypt_rctp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes) { - +void dtls_srtp_encrypt_rctp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes) { srtp_protect_rtcp(dtls_srtp->srtp_out, packet, bytes); } - diff --git a/src/dtls_srtp.h b/src/dtls_srtp.h index c9322a6..43eae97 100644 --- a/src/dtls_srtp.h +++ b/src/dtls_srtp.h @@ -4,20 +4,20 @@ #include #include -#include #include +#include +#include #include #include -#include +#include #include #include -#include #include #include "address.h" -#define SRTP_MASTER_KEY_LENGTH 16 +#define SRTP_MASTER_KEY_LENGTH 16 #define SRTP_MASTER_SALT_LENGTH 14 #define DTLS_SRTP_KEY_MATERIAL_LENGTH 60 #define DTLS_SRTP_FINGERPRINT_LENGTH 160 @@ -38,7 +38,6 @@ typedef enum DtlsSrtpState { } DtlsSrtpState; typedef struct DtlsSrtp { - // MbedTLS mbedtls_ssl_context ssl; mbedtls_ssl_config conf; @@ -56,11 +55,10 @@ typedef struct DtlsSrtp { unsigned char remote_policy_key[SRTP_MASTER_KEY_LENGTH + SRTP_MASTER_SALT_LENGTH]; unsigned char local_policy_key[SRTP_MASTER_KEY_LENGTH + SRTP_MASTER_SALT_LENGTH]; + int (*udp_send)(void* ctx, const unsigned char* buf, size_t len); + int (*udp_recv)(void* ctx, unsigned char* buf, size_t len); - int (*udp_send)(void *ctx, const unsigned char *buf, size_t len); - int (*udp_recv)(void *ctx, unsigned char *buf, size_t len); - - Address *remote_addr; + Address* remote_addr; DtlsSrtpRole role; DtlsSrtpState state; @@ -68,37 +66,36 @@ typedef struct DtlsSrtp { char local_fingerprint[DTLS_SRTP_FINGERPRINT_LENGTH]; char remote_fingerprint[DTLS_SRTP_FINGERPRINT_LENGTH]; - void *user_data; + void* user_data; } DtlsSrtp; -int dtls_srtp_init(DtlsSrtp *dtls_srtp, DtlsSrtpRole role, void *user_data); +int dtls_srtp_init(DtlsSrtp* dtls_srtp, DtlsSrtpRole role, void* user_data); -void dtls_srtp_deinit(DtlsSrtp *dtls_srtp); +void dtls_srtp_deinit(DtlsSrtp* dtls_srtp); -int dtls_srtp_create_cert(DtlsSrtp *dtls_srtp); +int dtls_srtp_create_cert(DtlsSrtp* dtls_srtp); -int dtls_srtp_handshake(DtlsSrtp *dtls_srtp, Address *addr); +int dtls_srtp_handshake(DtlsSrtp* dtls_srtp, Address* addr); -void dtls_srtp_reset_session(DtlsSrtp *dtls_srtp); +void dtls_srtp_reset_session(DtlsSrtp* dtls_srtp); -int dtls_srtp_write(DtlsSrtp *dtls_srtp, const uint8_t *buf, size_t len); - -int dtls_srtp_read(DtlsSrtp *dtls_srtp, uint8_t *buf, size_t len); +int dtls_srtp_write(DtlsSrtp* dtls_srtp, const uint8_t* buf, size_t len); -void dtls_srtp_encrypt_rtp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes); +int dtls_srtp_read(DtlsSrtp* dtls_srtp, uint8_t* buf, size_t len); -void dtls_srtp_sctp_to_dtls(DtlsSrtp *dtls_srtp, uint8_t *packet, int bytes); +void dtls_srtp_encrypt_rtp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes); -int dtls_srtp_probe(uint8_t *buf); +void dtls_srtp_sctp_to_dtls(DtlsSrtp* dtls_srtp, uint8_t* packet, int bytes); -void dtls_srtp_decrypt_rtp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes); +int dtls_srtp_probe(uint8_t* buf); -void dtls_srtp_decrypt_rtcp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes); +void dtls_srtp_decrypt_rtp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes); -void dtls_srtp_encrypt_rtp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes); +void dtls_srtp_decrypt_rtcp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes); -void dtls_srtp_encrypt_rctp_packet(DtlsSrtp *dtls_srtp, uint8_t *packet, int *bytes); +void dtls_srtp_encrypt_rtp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes); -#endif // DTLS_SRTP_H_ +void dtls_srtp_encrypt_rctp_packet(DtlsSrtp* dtls_srtp, uint8_t* packet, int* bytes); +#endif // DTLS_SRTP_H_ diff --git a/src/ice.c b/src/ice.c index 7caf716..77dfcde 100644 --- a/src/ice.c +++ b/src/ice.c @@ -1,20 +1,19 @@ -#include -#include +#include +#include #include #include -#include -#include -#include +#include +#include #include +#include +#include "ice.h" #include "mdns.h" #include "ports.h" #include "socket.h" #include "utils.h" -#include "ice.h" static uint8_t ice_candidate_type_preference(IceCandidateType type) { - switch (type) { case ICE_CANDIDATE_TYPE_HOST: return 126; @@ -27,19 +26,16 @@ static uint8_t ice_candidate_type_preference(IceCandidateType type) { } } -static uint16_t ice_candidate_local_preference(IceCandidate *candidate) { - +static uint16_t ice_candidate_local_preference(IceCandidate* candidate) { return candidate->addr.port; } -static void ice_candidate_priority(IceCandidate *candidate) { - +static void ice_candidate_priority(IceCandidate* candidate) { // priority = (2^24)*(type preference) + (2^8)*(local preference) + (256 - component ID) candidate->priority = (1 << 24) * ice_candidate_type_preference(candidate->type) + (1 << 8) * ice_candidate_local_preference(candidate) + (256 - candidate->component); } -void ice_candidate_create(IceCandidate *candidate, int foundation, IceCandidateType type, Address *addr) { - +void ice_candidate_create(IceCandidate* candidate, int foundation, IceCandidateType type, Address* addr) { memcpy(&candidate->addr, addr, sizeof(Address)); candidate->type = type; candidate->foundation = foundation; @@ -51,8 +47,7 @@ void ice_candidate_create(IceCandidate *candidate, int foundation, IceCandidateT snprintf(candidate->transport, sizeof(candidate->transport), "%s", "UDP"); } -void ice_candidate_to_description(IceCandidate *candidate, char *description, int length) { - +void ice_candidate_to_description(IceCandidate* candidate, char* description, int length) { char addr_string[ADDRSTRLEN]; char typ_raddr[128]; @@ -74,25 +69,23 @@ void ice_candidate_to_description(IceCandidate *candidate, char *description, in addr_to_string(&candidate->addr, addr_string, sizeof(addr_string)); snprintf(description, length, "a=candidate:%d %d %s %" PRIu32 " %s %d typ %s\r\n", - candidate->foundation, - candidate->component, - candidate->transport, - candidate->priority, - addr_string, - candidate->addr.port, - typ_raddr); + candidate->foundation, + candidate->component, + candidate->transport, + candidate->priority, + addr_string, + candidate->addr.port, + typ_raddr); } -int ice_candidate_from_description(IceCandidate *candidate, char *description, char *end) { - - char *split_start = description + strlen("a=candidate:"); - char *split_end = NULL; +int ice_candidate_from_description(IceCandidate* candidate, char* description, char* end) { + char* split_start = description + strlen("a=candidate:"); + char* split_end = NULL; int index = 0; char buf[64]; // a=candidate:448736988 1 udp 2122260223 172.17.0.1 49250 typ host generation 0 network-id 1 network-cost 50 // a=candidate:udpcandidate 1 udp 120 192.168.1.102 8000 typ host while ((split_end = strstr(split_start, " ")) != NULL && split_start < end) { - memset(buf, 0, sizeof(buf)); strncpy(buf, split_start, split_end - split_start); switch (index) { @@ -118,11 +111,11 @@ int ice_candidate_from_description(IceCandidate *candidate, char *description, c return -1; } } else if (addr_from_string(buf, &candidate->addr) == 0) { - return -1; - } + return -1; + } break; case 5: - addr_set_port(&candidate->addr, atoi(buf)); + addr_set_port(&candidate->addr, atoi(buf)); break; case 7: @@ -148,4 +141,3 @@ int ice_candidate_from_description(IceCandidate *candidate, char *description, c return 0; } - diff --git a/src/ice.h b/src/ice.h index add35ab..7e8350e 100644 --- a/src/ice.h +++ b/src/ice.h @@ -32,13 +32,12 @@ typedef enum IceCandidateType { typedef struct IceCandidate IceCandidate; struct IceCandidate { - int foundation; int component; uint32_t priority; - + char transport[32 + 1]; IceCandidateType type; @@ -48,26 +47,24 @@ struct IceCandidate { Address addr; Address raddr; - }; typedef struct IceCandidatePair IceCandidatePair; struct IceCandidatePair { - IceCandidateState state; - IceCandidate *local; - IceCandidate *remote; + IceCandidate* local; + IceCandidate* remote; int conncheck; uint64_t priority; }; -void ice_candidate_create(IceCandidate *ice_candidate, int foundation, IceCandidateType type, Address *addr); +void ice_candidate_create(IceCandidate* ice_candidate, int foundation, IceCandidateType type, Address* addr); -void ice_candidate_to_description(IceCandidate *candidate, char *description, int length); +void ice_candidate_to_description(IceCandidate* candidate, char* description, int length); -int ice_candidate_from_description(IceCandidate *candidate, char *description, char *end); +int ice_candidate_from_description(IceCandidate* candidate, char* description, char* end); -int ice_candidate_get_local_address(IceCandidate *candidate, Address *address); +int ice_candidate_get_local_address(IceCandidate* candidate, Address* address); -#endif // ICE_H_ +#endif // ICE_H_ diff --git a/src/mdns.c b/src/mdns.c index a6aedba..fd019a2 100644 --- a/src/mdns.c +++ b/src/mdns.c @@ -1,15 +1,15 @@ +#include +#include +#include #include #include #include -#include -#include -#include #include -#include -#include -#include "utils.h" +#include +#include #include "address.h" #include "socket.h" +#include "utils.h" #define MDNS_GROUP "224.0.0.251" #define MDNS_PORT 5353 @@ -36,19 +36,18 @@ typedef struct DnsQuery { uint16_t class; } DnsQuery; -static int mdns_parse_answer(uint8_t *buf, int size, Address *addr) { - - char *pos; +static int mdns_parse_answer(uint8_t* buf, int size, Address* addr) { + char* pos; int flags_qr; - DnsHeader *header; - DnsAnswer *answer; + DnsHeader* header; + DnsAnswer* answer; if (size < sizeof(DnsHeader)) { LOGE("response too short"); return -1; } - header = (DnsHeader *)buf; + header = (DnsHeader*)buf; flags_qr = ntohs(header->flags) >> 15; if (flags_qr != 1) { LOGD("flag is not a DNS response"); @@ -62,10 +61,9 @@ static int mdns_parse_answer(uint8_t *buf, int size, Address *addr) { return -1; } - pos += 6; - answer = (DnsAnswer *)pos; - LOGD("type: %"PRIu16", class: %"PRIu16", ttl: %"PRIu32", length: %"PRIu16"", ntohs(answer->type), ntohs(answer->class), ntohl(answer->ttl), ntohs(answer->length)); + answer = (DnsAnswer*)pos; + LOGD("type: %" PRIu16 ", class: %" PRIu16 ", ttl: %" PRIu32 ", length: %" PRIu16 "", ntohs(answer->type), ntohs(answer->class), ntohl(answer->ttl), ntohs(answer->length)); if (ntohs(answer->length) != 4) { LOGI("invalid length"); return -1; @@ -75,12 +73,11 @@ static int mdns_parse_answer(uint8_t *buf, int size, Address *addr) { return 0; } -static int mdns_build_query(const char *hostname, uint8_t *buf, int size) { - +static int mdns_build_query(const char* hostname, uint8_t* buf, int size) { int total_size, len, offset; const char *label, *dot; - DnsHeader *dns_header; - DnsQuery *dns_query; + DnsHeader* dns_header; + DnsQuery* dns_query; total_size = sizeof(DnsHeader) + strlen(hostname) + sizeof(DnsQuery) + 2; if (size < total_size) { @@ -109,13 +106,13 @@ static int mdns_build_query(const char *hostname, uint8_t *buf, int size) { buf[offset++] = 0x00; - dns_query = (DnsQuery*) (buf + offset); + dns_query = (DnsQuery*)(buf + offset); dns_query->type = 0x0100; dns_query->class = 0x0100; return total_size; } -int mdns_resolve_addr(const char *hostname, Address *addr) { +int mdns_resolve_addr(const char* hostname, Address* addr) { Address mcast_addr = {0}; UdpSocket udp_socket; uint8_t buf[256]; diff --git a/src/mdns.h b/src/mdns.h index a2c73a1..aa84466 100644 --- a/src/mdns.h +++ b/src/mdns.h @@ -4,6 +4,6 @@ #include #include "address.h" -int mdns_resolve_addr(const char *hostname, Address *addr); +int mdns_resolve_addr(const char* hostname, Address* addr); -#endif // MDNS_H_ +#endif // MDNS_H_ diff --git a/src/peer.c b/src/peer.c index 800a4f0..1595d73 100644 --- a/src/peer.c +++ b/src/peer.c @@ -1,15 +1,13 @@ +#include #include #include #include -#include -#include "utils.h" #include "peer.h" +#include "utils.h" int peer_init() { - - if(srtp_init() != srtp_err_status_ok) { - + if (srtp_init() != srtp_err_status_ok) { LOGE("libsrtp init failed"); } @@ -17,7 +15,5 @@ int peer_init() { } void peer_deinit() { - srtp_shutdown(); } - diff --git a/src/peer.h b/src/peer.h index e10169d..993b658 100644 --- a/src/peer.h +++ b/src/peer.h @@ -16,5 +16,4 @@ void peer_deinit(); } #endif -#endif // PEER_H_ - +#endif // PEER_H_ diff --git a/src/peer_connection.c b/src/peer_connection.c index aec22d6..144812b 100644 --- a/src/peer_connection.c +++ b/src/peer_connection.c @@ -1,23 +1,26 @@ +#include #include #include #include -#include -#include "sctp.h" #include "agent.h" -#include "dtls_srtp.h" -#include "sdp.h" -#include "config.h" -#include "rtp.h" -#include "rtcp.h" #include "buffer.h" -#include "ports.h" +#include "config.h" +#include "dtls_srtp.h" #include "peer_connection.h" +#include "ports.h" +#include "rtcp.h" +#include "rtp.h" +#include "sctp.h" +#include "sdp.h" -#define STATE_CHANGED(pc, curr_state) if(pc->oniceconnectionstatechange && pc->state != curr_state) { pc->oniceconnectionstatechange(curr_state, pc->config.user_data); pc->state = curr_state; } +#define STATE_CHANGED(pc, curr_state) \ + if (pc->oniceconnectionstatechange && pc->state != curr_state) { \ + pc->oniceconnectionstatechange(curr_state, pc->config.user_data); \ + pc->state = curr_state; \ + } struct PeerConnection { - PeerConfiguration config; PeerConnectionState state; Agent agent; @@ -27,19 +30,19 @@ struct PeerConnection { Sdp local_sdp; Sdp remote_sdp; - void (*onicecandidate)(char *sdp, void *user_data); - void (*oniceconnectionstatechange)(PeerConnectionState state, void *user_data); - void (*on_connected)(void *userdata); - void (*on_receiver_packet_loss)(float fraction_loss, uint32_t total_loss, void *user_data); + void (*onicecandidate)(char* sdp, void* user_data); + void (*oniceconnectionstatechange)(PeerConnectionState state, void* user_data); + void (*on_connected)(void* userdata); + void (*on_receiver_packet_loss)(float fraction_loss, uint32_t total_loss, void* user_data); uint8_t temp_buf[CONFIG_MTU]; uint8_t agent_buf[CONFIG_MTU]; int agent_ret; int b_offer_created; - Buffer *audio_rb; - Buffer *video_rb; - Buffer *data_rb; + Buffer* audio_rb; + Buffer* video_rb; + Buffer* data_rb; RtpEncoder artp_encoder; RtpEncoder vrtp_encoder; @@ -48,32 +51,27 @@ struct PeerConnection { uint32_t remote_assrc; uint32_t remote_vssrc; - }; -static void peer_connection_outgoing_rtp_packet(uint8_t *data, size_t size, void *user_data) { - - PeerConnection *pc = (PeerConnection *) user_data; +static void peer_connection_outgoing_rtp_packet(uint8_t* data, size_t size, void* user_data) { + PeerConnection* pc = (PeerConnection*)user_data; dtls_srtp_encrypt_rtp_packet(&pc->dtls_srtp, data, (int*)&size); agent_send(&pc->agent, data, size); } -static int peer_connection_dtls_srtp_recv(void *ctx, unsigned char *buf, size_t len) { - +static int peer_connection_dtls_srtp_recv(void* ctx, unsigned char* buf, size_t len) { static const int MAX_RECV = 200; - int recv_max = 0; - int ret; - DtlsSrtp *dtls_srtp = (DtlsSrtp *) ctx; - PeerConnection *pc = (PeerConnection *) dtls_srtp->user_data; + int recv_max = 0; + int ret; + DtlsSrtp* dtls_srtp = (DtlsSrtp*)ctx; + PeerConnection* pc = (PeerConnection*)dtls_srtp->user_data; if (pc->agent_ret > 0 && pc->agent_ret <= len) { - memcpy(buf, pc->agent_buf, pc->agent_ret); return pc->agent_ret; } while (recv_max < MAX_RECV) { - ret = agent_recv(&pc->agent, buf, len); if (ret > 0) { @@ -81,34 +79,29 @@ static int peer_connection_dtls_srtp_recv(void *ctx, unsigned char *buf, size_t } recv_max++; - } - return ret; + return ret; } -static int peer_connection_dtls_srtp_send(void *ctx, const uint8_t *buf, size_t len) { - - DtlsSrtp *dtls_srtp = (DtlsSrtp *) ctx; - PeerConnection *pc = (PeerConnection *) dtls_srtp->user_data; +static int peer_connection_dtls_srtp_send(void* ctx, const uint8_t* buf, size_t len) { + DtlsSrtp* dtls_srtp = (DtlsSrtp*)ctx; + PeerConnection* pc = (PeerConnection*)dtls_srtp->user_data; - //LOGD("send %.4x %.4x, %ld", *(uint16_t*)buf, *(uint16_t*)(buf + 2), len); + // LOGD("send %.4x %.4x, %ld", *(uint16_t*)buf, *(uint16_t*)(buf + 2), len); return agent_send(&pc->agent, buf, len); - } -static void peer_connection_incoming_rtcp(PeerConnection *pc, uint8_t *buf, size_t len) { - - RtcpHeader *rtcp_header; +static void peer_connection_incoming_rtcp(PeerConnection* pc, uint8_t* buf, size_t len) { + RtcpHeader* rtcp_header; size_t pos = 0; while (pos < len) { - rtcp_header = (RtcpHeader*)(buf + pos); - switch(rtcp_header->type) { + switch (rtcp_header->type) { case RTCP_RR: LOGD("RTCP_PR"); - if(rtcp_header->rc > 0) { + if (rtcp_header->rc > 0) { // TODO: REMB, GCC ...etc #if 0 RtcpRr rtcp_rr = rtcp_parse_rr(buf); @@ -126,20 +119,19 @@ static void peer_connection_incoming_rtcp(PeerConnection *pc, uint8_t *buf, size LOGD("RTCP_PSFB %d", fmt); // PLI and FIR if ((fmt == 1 || fmt == 4) && pc->config.on_request_keyframe) { - pc->config.on_request_keyframe(pc->config.user_data); - } + pc->config.on_request_keyframe(pc->config.user_data); + } } default: break; } - pos += 4*ntohs(rtcp_header->length) + 4; + pos += 4 * ntohs(rtcp_header->length) + 4; } } const char* peer_connection_state_to_string(PeerConnectionState state) { - - switch(state) { + switch (state) { case PEER_CONNECTION_NEW: return "new"; case PEER_CONNECTION_CHECKING: @@ -159,19 +151,16 @@ const char* peer_connection_state_to_string(PeerConnectionState state) { } } -PeerConnectionState peer_connection_get_state(PeerConnection *pc) { - +PeerConnectionState peer_connection_get_state(PeerConnection* pc) { return pc->state; } -void* peer_connection_get_sctp(PeerConnection *pc) { - +void* peer_connection_get_sctp(PeerConnection* pc) { return &pc->sctp; } -PeerConnection* peer_connection_create(PeerConfiguration *config) { - - PeerConnection *pc = calloc(1, sizeof(PeerConnection)); +PeerConnection* peer_connection_create(PeerConfiguration* config) { + PeerConnection* pc = calloc(1, sizeof(PeerConnection)); if (!pc) { return NULL; } @@ -196,10 +185,10 @@ PeerConnection* peer_connection_create(PeerConfiguration *config) { pc->audio_rb = buffer_new(AUDIO_RB_DATA_LENGTH); rtp_encoder_init(&pc->artp_encoder, pc->config.audio_codec, - peer_connection_outgoing_rtp_packet, (void*)pc); + peer_connection_outgoing_rtp_packet, (void*)pc); rtp_decoder_init(&pc->artp_decoder, pc->config.audio_codec, - pc->config.onaudiotrack, pc->config.user_data); + pc->config.onaudiotrack, pc->config.user_data); } if (pc->config.video_codec) { @@ -207,19 +196,17 @@ PeerConnection* peer_connection_create(PeerConfiguration *config) { pc->video_rb = buffer_new(VIDEO_RB_DATA_LENGTH); rtp_encoder_init(&pc->vrtp_encoder, pc->config.video_codec, - peer_connection_outgoing_rtp_packet, (void*)pc); + peer_connection_outgoing_rtp_packet, (void*)pc); rtp_decoder_init(&pc->vrtp_decoder, pc->config.video_codec, - pc->config.onvideotrack, pc->config.user_data); + pc->config.onvideotrack, pc->config.user_data); } return pc; } -void peer_connection_destroy(PeerConnection *pc) { - +void peer_connection_destroy(PeerConnection* pc) { if (pc) { - buffer_free(pc->data_rb); buffer_free(pc->audio_rb); buffer_free(pc->video_rb); @@ -229,38 +216,34 @@ void peer_connection_destroy(PeerConnection *pc) { } } -void peer_connection_close(PeerConnection *pc) { - +void peer_connection_close(PeerConnection* pc) { pc->state = PEER_CONNECTION_CLOSED; } -int peer_connection_send_audio(PeerConnection *pc, const uint8_t *buf, size_t len) { - +int peer_connection_send_audio(PeerConnection* pc, const uint8_t* buf, size_t len) { if (pc->state != PEER_CONNECTION_COMPLETED) { - //LOGE("dtls_srtp not connected"); + // LOGE("dtls_srtp not connected"); return -1; } return buffer_push_tail(pc->audio_rb, buf, len); } -int peer_connection_send_video(PeerConnection *pc, const uint8_t *buf, size_t len) { - +int peer_connection_send_video(PeerConnection* pc, const uint8_t* buf, size_t len) { if (pc->state != PEER_CONNECTION_COMPLETED) { - //LOGE("dtls_srtp not connected"); + // LOGE("dtls_srtp not connected"); return -1; } return buffer_push_tail(pc->video_rb, buf, len); } -int peer_connection_datachannel_send(PeerConnection *pc, char *message, size_t len) { +int peer_connection_datachannel_send(PeerConnection* pc, char* message, size_t len) { return peer_connection_datachannel_send_sid(pc, message, len, 0); } -int peer_connection_datachannel_send_sid(PeerConnection *pc, char *message, size_t len, uint16_t sid) { - - if(!sctp_is_connected(&pc->sctp)) { +int peer_connection_datachannel_send_sid(PeerConnection* pc, char* message, size_t len, uint16_t sid) { + if (!sctp_is_connected(&pc->sctp)) { LOGE("sctp not connected"); return -1; } @@ -271,9 +254,8 @@ int peer_connection_datachannel_send_sid(PeerConnection *pc, char *message, size return sctp_outgoing_data(&pc->sctp, message, len, PPID_BINARY, sid); } -static void peer_connection_state_new(PeerConnection *pc) { - - char *description = (char*)pc->temp_buf; +static void peer_connection_state_new(PeerConnection* pc) { + char* description = (char*)pc->temp_buf; memset(pc->temp_buf, 0, sizeof(pc->temp_buf)); @@ -283,8 +265,7 @@ static void peer_connection_state_new(PeerConnection *pc) { pc->sctp.connected = 0; - for (int i = 0; i < sizeof(pc->config.ice_servers)/sizeof(pc->config.ice_servers[0]); ++i) { - + for (int i = 0; i < sizeof(pc->config.ice_servers) / sizeof(pc->config.ice_servers[0]); ++i) { if (pc->config.ice_servers[i].urls) { LOGI("ice_servers: %s", pc->config.ice_servers[i].urls); agent_gather_candidate(&pc->agent, pc->config.ice_servers[i].urls, pc->config.ice_servers[i].username, pc->config.ice_servers[i].credential); @@ -296,22 +277,18 @@ static void peer_connection_state_new(PeerConnection *pc) { memset(&pc->local_sdp, 0, sizeof(pc->local_sdp)); // TODO: check if we have video or audio codecs sdp_create(&pc->local_sdp, - pc->config.video_codec != CODEC_NONE, - pc->config.audio_codec != CODEC_NONE, - pc->config.datachannel); - + pc->config.video_codec != CODEC_NONE, + pc->config.audio_codec != CODEC_NONE, + pc->config.datachannel); if (pc->config.video_codec == CODEC_H264) { - sdp_append_h264(&pc->local_sdp); sdp_append(&pc->local_sdp, "a=fingerprint:sha-256 %s", pc->dtls_srtp.local_fingerprint); sdp_append(&pc->local_sdp, "a=setup:passive"); strcat(pc->local_sdp.content, description); } - switch (pc->config.audio_codec) { - case CODEC_PCMA: sdp_append_pcma(&pc->local_sdp); @@ -352,10 +329,9 @@ static void peer_connection_state_new(PeerConnection *pc) { } } -int peer_connection_loop(PeerConnection *pc) { - +int peer_connection_loop(PeerConnection* pc) { int bytes; - uint8_t *data = NULL; + uint8_t* data = NULL; uint32_t ssrc = 0; memset(pc->agent_buf, 0, sizeof(pc->agent_buf)); pc->agent_ret = -1; @@ -380,7 +356,6 @@ int peer_connection_loop(PeerConnection *pc) { case PEER_CONNECTION_CONNECTED: if (dtls_srtp_handshake(&pc->dtls_srtp, NULL) == 0) { - LOGD("DTLS-SRTP handshake done"); if (pc->config.datachannel) { @@ -408,12 +383,11 @@ int peer_connection_loop(PeerConnection *pc) { data = buffer_peak_head(pc->data_rb, &bytes); if (data) { - - if (pc->config.datachannel == DATA_CHANNEL_STRING) - sctp_outgoing_data(&pc->sctp, (char*)data, bytes, PPID_STRING, 0); - else - sctp_outgoing_data(&pc->sctp, (char*)data, bytes, PPID_BINARY, 0); - buffer_pop_head(pc->data_rb); + if (pc->config.datachannel == DATA_CHANNEL_STRING) + sctp_outgoing_data(&pc->sctp, (char*)data, bytes, PPID_STRING, 0); + else + sctp_outgoing_data(&pc->sctp, (char*)data, bytes, PPID_BINARY, 0); + buffer_pop_head(pc->data_rb); } if ((pc->agent_ret = agent_recv(&pc->agent, pc->agent_buf, sizeof(pc->agent_buf))) > 0) { @@ -425,7 +399,6 @@ int peer_connection_loop(PeerConnection *pc) { peer_connection_incoming_rtcp(pc, pc->agent_buf, pc->agent_ret); } else if (dtls_srtp_probe(pc->agent_buf)) { - int ret = dtls_srtp_read(&pc->dtls_srtp, pc->temp_buf, sizeof(pc->temp_buf)); LOGD("Got DTLS data %d", ret); @@ -448,11 +421,9 @@ int peer_connection_loop(PeerConnection *pc) { } else { LOGW("Unknown data"); } - } if (KEEPALIVE_CONNCHECK > 0 && (ports_get_epoch_time() - pc->agent.binding_request_time) > KEEPALIVE_CONNCHECK) { - LOGI("binding request timeout"); STATE_CHANGED(pc, PEER_CONNECTION_CLOSED); } @@ -471,16 +442,14 @@ int peer_connection_loop(PeerConnection *pc) { return 0; } -void peer_connection_set_remote_description(PeerConnection *pc, const char *sdp_text) { - - char *start = (char*)sdp_text; - char *line = NULL; +void peer_connection_set_remote_description(PeerConnection* pc, const char* sdp_text) { + char* start = (char*)sdp_text; + char* line = NULL; char buf[256]; - char *ssrc_start = NULL; - uint32_t *ssrc = NULL; + char* ssrc_start = NULL; + uint32_t* ssrc = NULL; while ((line = strstr(start, "\r\n"))) { - line = strstr(start, "\r\n"); strncpy(buf, start, line - start); buf[line - start] = '\0'; @@ -493,7 +462,7 @@ void peer_connection_set_remote_description(PeerConnection *pc, const char *sdp_ if ((ssrc_start = strstr(buf, "a=ssrc:")) && ssrc) { *ssrc = strtoul(ssrc_start + 7, NULL, 10); - LOGD("SSRC: %"PRIu32, *ssrc); + LOGD("SSRC: %" PRIu32, *ssrc); } start = line + 2; @@ -503,78 +472,69 @@ void peer_connection_set_remote_description(PeerConnection *pc, const char *sdp_ STATE_CHANGED(pc, PEER_CONNECTION_CHECKING); } -void peer_connection_create_offer(PeerConnection *pc) { - +void peer_connection_create_offer(PeerConnection* pc) { STATE_CHANGED(pc, PEER_CONNECTION_NEW); pc->b_offer_created = 0; } -int peer_connection_send_rtcp_pil(PeerConnection *pc, uint32_t ssrc) { - +int peer_connection_send_rtcp_pil(PeerConnection* pc, uint32_t ssrc) { int ret = -1; uint8_t plibuf[128]; rtcp_get_pli(plibuf, 12, ssrc); - - //TODO: encrypt rtcp packet - //guint size = 12; - //dtls_transport_encrypt_rctp_packet(pc->dtls_transport, plibuf, &size); - //ret = nice_agent_send(pc->nice_agent, pc->stream_id, pc->component_id, size, (gchar*)plibuf); + + // TODO: encrypt rtcp packet + // guint size = 12; + // dtls_transport_encrypt_rctp_packet(pc->dtls_transport, plibuf, &size); + // ret = nice_agent_send(pc->nice_agent, pc->stream_id, pc->component_id, size, (gchar*)plibuf); return ret; } // callbacks -void peer_connection_on_connected(PeerConnection *pc, void (*on_connected)(void *userdata)) { - +void peer_connection_on_connected(PeerConnection* pc, void (*on_connected)(void* userdata)) { pc->on_connected = on_connected; } -void peer_connection_on_receiver_packet_loss(PeerConnection *pc, - void (*on_receiver_packet_loss)(float fraction_loss, uint32_t total_loss, void *userdata)) { - +void peer_connection_on_receiver_packet_loss(PeerConnection* pc, + void (*on_receiver_packet_loss)(float fraction_loss, uint32_t total_loss, void* userdata)) { pc->on_receiver_packet_loss = on_receiver_packet_loss; } -void peer_connection_onicecandidate(PeerConnection *pc, void (*onicecandidate)(char *sdp_text, void *userdata)) { - +void peer_connection_onicecandidate(PeerConnection* pc, void (*onicecandidate)(char* sdp_text, void* userdata)) { pc->onicecandidate = onicecandidate; } -void peer_connection_oniceconnectionstatechange(PeerConnection *pc, - void (*oniceconnectionstatechange)(PeerConnectionState state, void *userdata)) { - +void peer_connection_oniceconnectionstatechange(PeerConnection* pc, + void (*oniceconnectionstatechange)(PeerConnectionState state, void* userdata)) { pc->oniceconnectionstatechange = oniceconnectionstatechange; } -void peer_connection_ondatachannel(PeerConnection *pc, - void (*onmessage)(char *msg, size_t len, void *userdata, uint16_t sid), - void (*onopen)(void *userdata), - void (*onclose)(void *userdata)) { - +void peer_connection_ondatachannel(PeerConnection* pc, + void (*onmessage)(char* msg, size_t len, void* userdata, uint16_t sid), + void (*onopen)(void* userdata), + void (*onclose)(void* userdata)) { if (pc) { - sctp_onopen(&pc->sctp, onopen); sctp_onclose(&pc->sctp, onclose); sctp_onmessage(&pc->sctp, onmessage); } } -int peer_connection_lookup_sid(PeerConnection *pc, const char *label, uint16_t *sid) { - for (int i = 0; i < pc->sctp.stream_count; i++) { - if (strncmp(pc->sctp.stream_table[i].label, label, sizeof(pc->sctp.stream_table[i].label)) == 0) { - *sid = pc->sctp.stream_table[i].sid; - return 0; - } +int peer_connection_lookup_sid(PeerConnection* pc, const char* label, uint16_t* sid) { + for (int i = 0; i < pc->sctp.stream_count; i++) { + if (strncmp(pc->sctp.stream_table[i].label, label, sizeof(pc->sctp.stream_table[i].label)) == 0) { + *sid = pc->sctp.stream_table[i].sid; + return 0; } - return -1; // Not found + } + return -1; // Not found } -char *peer_connection_lookup_sid_label(PeerConnection *pc, uint16_t sid) { - for (int i = 0; i < pc->sctp.stream_count; i++) { - if (pc->sctp.stream_table[i].sid == sid) { - return pc->sctp.stream_table[i].label; - } +char* peer_connection_lookup_sid_label(PeerConnection* pc, uint16_t sid) { + for (int i = 0; i < pc->sctp.stream_count; i++) { + if (pc->sctp.stream_table[i].sid == sid) { + return pc->sctp.stream_table[i].label; } - return NULL; // Not found + } + return NULL; // Not found } - diff --git a/src/peer_connection.h b/src/peer_connection.h index 0caca91..ad0446c 100644 --- a/src/peer_connection.h +++ b/src/peer_connection.h @@ -5,8 +5,8 @@ #ifndef PEER_CONNECTION_H_ #define PEER_CONNECTION_H_ -#include #include +#include #ifdef __cplusplus extern "C" { @@ -26,7 +26,7 @@ typedef enum PeerConnectionState { typedef enum DataChannelType { - DATA_CHANNEL_NONE = 0, + DATA_CHANNEL_NONE = 0, DATA_CHANNEL_STRING, DATA_CHANNEL_BINARY, @@ -38,36 +38,34 @@ typedef enum MediaCodec { /* Video */ CODEC_H264, - CODEC_VP8, // not implemented yet - CODEC_MJPEG, // not implemented yet + CODEC_VP8, // not implemented yet + CODEC_MJPEG, // not implemented yet /* Audio */ - CODEC_OPUS, // not implemented yet + CODEC_OPUS, // not implemented yet CODEC_PCMA, CODEC_PCMU, } MediaCodec; typedef struct IceServer { - - const char *urls; - const char *username; - const char *credential; + const char* urls; + const char* username; + const char* credential; } IceServer; typedef struct PeerConfiguration { - IceServer ice_servers[5]; MediaCodec audio_codec; MediaCodec video_codec; DataChannelType datachannel; - void (*onaudiotrack)(uint8_t *data, size_t size, void *userdata); - void (*onvideotrack)(uint8_t *data, size_t size, void *userdata); - void (*on_request_keyframe)(void *userdata); - void *user_data; + void (*onaudiotrack)(uint8_t* data, size_t size, void* userdata); + void (*onvideotrack)(uint8_t* data, size_t size, void* userdata); + void (*on_request_keyframe)(void* userdata); + void* user_data; } PeerConfiguration; @@ -75,34 +73,34 @@ typedef struct PeerConnection PeerConnection; const char* peer_connection_state_to_string(PeerConnectionState state); -PeerConnectionState peer_connection_get_state(PeerConnection *pc); +PeerConnectionState peer_connection_get_state(PeerConnection* pc); -void* peer_connection_get_sctp(PeerConnection *pc); +void* peer_connection_get_sctp(PeerConnection* pc); -PeerConnection* peer_connection_create(PeerConfiguration *config); +PeerConnection* peer_connection_create(PeerConfiguration* config); -void peer_connection_destroy(PeerConnection *pc); +void peer_connection_destroy(PeerConnection* pc); -void peer_connection_close(PeerConnection *pc); +void peer_connection_close(PeerConnection* pc); -int peer_connection_loop(PeerConnection *pc); +int peer_connection_loop(PeerConnection* pc); /** * @brief send message to data channel * @param[in] peer connection * @param[in] message buffer * @param[in] length of message */ -int peer_connection_datachannel_send(PeerConnection *pc, char *message, size_t len); +int peer_connection_datachannel_send(PeerConnection* pc, char* message, size_t len); -int peer_connection_datachannel_send_sid(PeerConnection *pc, char *message, size_t len, uint16_t sid); +int peer_connection_datachannel_send_sid(PeerConnection* pc, char* message, size_t len, uint16_t sid); -int peer_connection_send_audio(PeerConnection *pc, const uint8_t *packet, size_t bytes); +int peer_connection_send_audio(PeerConnection* pc, const uint8_t* packet, size_t bytes); -int peer_connection_send_video(PeerConnection *pc, const uint8_t *packet, size_t bytes); +int peer_connection_send_video(PeerConnection* pc, const uint8_t* packet, size_t bytes); -void peer_connection_set_remote_description(PeerConnection *pc, const char *sdp); +void peer_connection_set_remote_description(PeerConnection* pc, const char* sdp); -void peer_connection_create_offer(PeerConnection *pc); +void peer_connection_create_offer(PeerConnection* pc); /** * @brief register callback function to handle packet loss from RTCP receiver report @@ -110,25 +108,25 @@ void peer_connection_create_offer(PeerConnection *pc); * @param[in] callback function void (*cb)(float fraction_loss, uint32_t total_loss, void *userdata) * @param[in] userdata for callback function */ -void peer_connection_on_receiver_packet_loss(PeerConnection *pc, - void (*on_receiver_packet_loss)(float fraction_loss, uint32_t total_loss, void *userdata)); +void peer_connection_on_receiver_packet_loss(PeerConnection* pc, + void (*on_receiver_packet_loss)(float fraction_loss, uint32_t total_loss, void* userdata)); /** * @brief Set the callback function to handle onicecandidate event. * @param A PeerConnection. * @param A callback function to handle onicecandidate event. - * @param A userdata which is pass to callback function. + * @param A userdata which is pass to callback function. */ -void peer_connection_onicecandidate(PeerConnection *pc, void (*onicecandidate)(char *sdp_text, void *userdata)); +void peer_connection_onicecandidate(PeerConnection* pc, void (*onicecandidate)(char* sdp_text, void* userdata)); /** * @brief Set the callback function to handle oniceconnectionstatechange event. * @param A PeerConnection. * @param A callback function to handle oniceconnectionstatechange event. - * @param A userdata which is pass to callback function. + * @param A userdata which is pass to callback function. */ -void peer_connection_oniceconnectionstatechange(PeerConnection *pc, - void (*oniceconnectionstatechange)(PeerConnectionState state, void *userdata)); +void peer_connection_oniceconnectionstatechange(PeerConnection* pc, + void (*oniceconnectionstatechange)(PeerConnectionState state, void* userdata)); /** * @brief register callback function to handle event of datachannel @@ -137,18 +135,17 @@ void peer_connection_oniceconnectionstatechange(PeerConnection *pc, * @param[in] callback function when connection is opened * @param[in] callback function when connection is closed */ -void peer_connection_ondatachannel(PeerConnection *pc, - void (*onmessage)(char *msg, size_t len, void *userdata, uint16_t sid), - void (*onopen)(void *userdata), - void (*onclose)(void *userdata)); +void peer_connection_ondatachannel(PeerConnection* pc, + void (*onmessage)(char* msg, size_t len, void* userdata, uint16_t sid), + void (*onopen)(void* userdata), + void (*onclose)(void* userdata)); -int peer_connection_lookup_sid(PeerConnection *pc, const char *label, uint16_t *sid); +int peer_connection_lookup_sid(PeerConnection* pc, const char* label, uint16_t* sid); -char *peer_connection_lookup_sid_label(PeerConnection *pc, uint16_t sid); +char* peer_connection_lookup_sid_label(PeerConnection* pc, uint16_t sid); #ifdef __cplusplus } #endif -#endif // PEER_CONNECTION_H_ - +#endif // PEER_CONNECTION_H_ diff --git a/src/peer_signaling.c b/src/peer_signaling.c index 8a7f661..3f4852e 100644 --- a/src/peer_signaling.c +++ b/src/peer_signaling.c @@ -1,18 +1,18 @@ -#include -#include #include -#include #include +#include +#include +#include -#include #include +#include -#include "config.h" #include "base64.h" -#include "utils.h" +#include "config.h" +#include "peer_signaling.h" #include "ports.h" #include "ssl_transport.h" -#include "peer_signaling.h" +#include "utils.h" #define KEEP_ALIVE_TIMEOUT_SECONDS 60 #define CONNACK_RECV_TIMEOUT_MS 1000 @@ -40,7 +40,6 @@ #define RPC_ERROR_INTERNAL_ERROR "{\"code\":-32603,\"message\":\"Internal error\"}" typedef struct PeerSignaling { - MQTTContext_t mqtt_ctx; MQTTFixedBuffer_t mqtt_fixed_buf; @@ -64,14 +63,13 @@ typedef struct PeerSignaling { char username[CRED_LEN]; char password[CRED_LEN]; char client_id[CRED_LEN]; - PeerConnection *pc; + PeerConnection* pc; } PeerSignaling; static PeerSignaling g_ps; -static void peer_signaling_mqtt_publish(MQTTContext_t *mqtt_ctx, const char *message) { - +static void peer_signaling_mqtt_publish(MQTTContext_t* mqtt_ctx, const char* message) { MQTTStatus_t status; MQTTPublishInfo_t pub_info; @@ -86,26 +84,21 @@ static void peer_signaling_mqtt_publish(MQTTContext_t *mqtt_ctx, const char *mes status = MQTT_Publish(mqtt_ctx, &pub_info, MQTT_GetPacketId(mqtt_ctx)); if (status != MQTTSuccess) { - LOGE("MQTT_Publish failed: Status=%s.", MQTT_Status_strerror(status)); } else { - LOGD("MQTT_Publish succeeded."); } } - -static void peer_signaling_on_pub_event(const char *msg, size_t size) { - +static void peer_signaling_on_pub_event(const char* msg, size_t size) { cJSON *req, *res, *item, *result, *error; int id = -1; - char *payload = NULL; + char* payload = NULL; PeerConnectionState state; req = res = item = result = error = NULL; state = peer_connection_get_state(g_ps.pc); do { - req = cJSON_Parse(msg); if (!req) { error = cJSON_CreateRaw(RPC_ERROR_PARSE_ERROR); @@ -113,7 +106,6 @@ static void peer_signaling_on_pub_event(const char *msg, size_t size) { break; } - item = cJSON_GetObjectItem(req, "id"); if (!item && !cJSON_IsNumber(item)) { error = cJSON_CreateRaw(RPC_ERROR_INVALID_REQUEST); @@ -144,12 +136,11 @@ static void peer_signaling_on_pub_event(const char *msg, size_t size) { } break; } } else if (strcmp(item->valuestring, RPC_METHOD_ANSWER) == 0) { - item = cJSON_GetObjectItem(req, "params"); if (!item && !cJSON_IsString(item)) { error = cJSON_CreateRaw(RPC_ERROR_INVALID_PARAMS); - LOGW("Cannot find params"); - break; + LOGW("Cannot find params"); + break; } if (state == PEER_CONNECTION_NEW) { @@ -158,11 +149,9 @@ static void peer_signaling_on_pub_event(const char *msg, size_t size) { } } else if (strcmp(item->valuestring, RPC_METHOD_STATE) == 0) { - result = cJSON_CreateString(peer_connection_state_to_string(state)); } else if (strcmp(item->valuestring, RPC_METHOD_CLOSE) == 0) { - peer_connection_close(g_ps.pc); result = cJSON_CreateString(""); @@ -174,7 +163,6 @@ static void peer_signaling_on_pub_event(const char *msg, size_t size) { } while (0); if (result || error) { - res = cJSON_CreateObject(); cJSON_AddStringToObject(res, "jsonrpc", RPC_VERSION); cJSON_AddNumberToObject(res, "id", id); @@ -199,13 +187,17 @@ static void peer_signaling_on_pub_event(const char *msg, size_t size) { } } -HTTPResponse_t peer_signaling_http_request(const TransportInterface_t *transport_interface, - const char *method, size_t method_len, - const char *host, size_t host_len, - const char *path, size_t path_len, - const char *auth, size_t auth_len, - const char *body, size_t body_len) { - +HTTPResponse_t peer_signaling_http_request(const TransportInterface_t* transport_interface, + const char* method, + size_t method_len, + const char* host, + size_t host_len, + const char* path, + size_t path_len, + const char* auth, + size_t auth_len, + const char* body, + size_t body_len) { HTTPStatus_t status = HTTPSuccess; HTTPRequestInfo_t request_info = {0}; HTTPResponse_t response = {0}; @@ -225,32 +217,28 @@ HTTPResponse_t peer_signaling_http_request(const TransportInterface_t *transport status = HTTPClient_InitializeRequestHeaders(&request_headers, &request_info); if (status == HTTPSuccess) { - HTTPClient_AddHeader(&request_headers, - "Content-Type", strlen("Content-Type"), "application/sdp", strlen("application/sdp")); + "Content-Type", strlen("Content-Type"), "application/sdp", strlen("application/sdp")); if (auth_len > 0) { HTTPClient_AddHeader(&request_headers, - "Authorization", strlen("Authorization"), auth, auth_len); + "Authorization", strlen("Authorization"), auth, auth_len); } response.pBuffer = g_ps.http_buf; response.bufferLen = sizeof(g_ps.http_buf); status = HTTPClient_Send(transport_interface, - &request_headers, (uint8_t*)body, body ? body_len : 0, &response, 0); + &request_headers, (uint8_t*)body, body ? body_len : 0, &response, 0); } else { - LOGE("Failed to initialize HTTP request headers: Error=%s.", HTTPClient_strerror(status)); } return response; } -static int peer_signaling_http_post(const char *hostname, const char *path, int port, - const char *auth, const char *body) { - +static int peer_signaling_http_post(const char* hostname, const char* path, int port, const char* auth, const char* body) { int ret = 0; TransportInterface_t trans_if = {0}; NetworkContext_t net_ctx; @@ -273,42 +261,42 @@ static int peer_signaling_http_post(const char *hostname, const char *path, int } res = peer_signaling_http_request(&trans_if, "POST", 4, hostname, strlen(hostname), path, - strlen(path), auth, strlen(auth), body, strlen(body)); + strlen(path), auth, strlen(auth), body, strlen(body)); ssl_transport_disconnect(&net_ctx); if (res.pHeaders == NULL) { - LOGE("Response headers are NULL"); - return -1; + LOGE("Response headers are NULL"); + return -1; } if (res.pBody == NULL) { - LOGE("Response body is NULL"); - return -1; + LOGE("Response body is NULL"); + return -1; } - LOGI("Received HTTP response from %s%s\n" - "Response Headers: %s\nResponse Status: %u\nResponse Body: %s\n", - hostname, path, res.pHeaders, res.statusCode, res.pBody); + LOGI( + "Received HTTP response from %s%s\n" + "Response Headers: %s\nResponse Status: %u\nResponse Body: %s\n", + hostname, path, res.pHeaders, res.statusCode, res.pBody); if (res.statusCode == 201) { - peer_connection_set_remote_description(g_ps.pc, (const char*)res.pBody); + peer_connection_set_remote_description(g_ps.pc, (const char*)res.pBody); } return 0; } -static void peer_signaling_mqtt_event_cb(MQTTContext_t *mqtt_ctx, - MQTTPacketInfo_t *packet_info, MQTTDeserializedInfo_t *deserialized_info) { - +static void peer_signaling_mqtt_event_cb(MQTTContext_t* mqtt_ctx, + MQTTPacketInfo_t* packet_info, + MQTTDeserializedInfo_t* deserialized_info) { switch (packet_info->type) { - case MQTT_PACKET_TYPE_CONNACK: LOGI("MQTT_PACKET_TYPE_CONNACK"); break; case MQTT_PACKET_TYPE_PUBLISH: LOGI("MQTT_PACKET_TYPE_PUBLISH"); peer_signaling_on_pub_event(deserialized_info->pPublishInfo->pPayload, - deserialized_info->pPublishInfo->payloadLength); + deserialized_info->pPublishInfo->payloadLength); break; case MQTT_PACKET_TYPE_SUBACK: LOGD("MQTT_PACKET_TYPE_SUBACK"); @@ -318,8 +306,7 @@ static void peer_signaling_mqtt_event_cb(MQTTContext_t *mqtt_ctx, } } -static int peer_signaling_mqtt_connect(const char *hostname, int port) { - +static int peer_signaling_mqtt_connect(const char* hostname, int port) { MQTTStatus_t status; MQTTConnectInfo_t conn_info; bool session_present; @@ -335,7 +322,7 @@ static int peer_signaling_mqtt_connect(const char *hostname, int port) { g_ps.mqtt_fixed_buf.pBuffer = g_ps.mqtt_buf; g_ps.mqtt_fixed_buf.size = sizeof(g_ps.mqtt_buf); status = MQTT_Init(&g_ps.mqtt_ctx, &g_ps.transport, - ports_get_epoch_time, peer_signaling_mqtt_event_cb, &g_ps.mqtt_fixed_buf); + ports_get_epoch_time, peer_signaling_mqtt_event_cb, &g_ps.mqtt_fixed_buf); memset(&conn_info, 0, sizeof(conn_info)); @@ -358,7 +345,7 @@ static int peer_signaling_mqtt_connect(const char *hostname, int port) { conn_info.keepAliveSeconds = KEEP_ALIVE_TIMEOUT_SECONDS; status = MQTT_Connect(&g_ps.mqtt_ctx, - &conn_info, NULL, CONNACK_RECV_TIMEOUT_MS, &session_present); + &conn_info, NULL, CONNACK_RECV_TIMEOUT_MS, &session_present); if (status != MQTTSuccess) { LOGE("MQTT_Connect failed: Status=%s.", MQTT_Status_strerror(status)); @@ -370,7 +357,6 @@ static int peer_signaling_mqtt_connect(const char *hostname, int port) { } static int peer_signaling_mqtt_subscribe(int subscribed) { - MQTTStatus_t status = MQTTSuccess; MQTTSubscribeInfo_t sub_info; @@ -402,12 +388,11 @@ static int peer_signaling_mqtt_subscribe(int subscribed) { return 0; } -static void peer_signaling_onicecandidate(char *description, void *userdata) { - - cJSON *res; - char *payload; - char cred_plaintext[2*CRED_LEN + 1]; - char cred_base64[2*CRED_LEN + 10]; +static void peer_signaling_onicecandidate(char* description, void* userdata) { + cJSON* res; + char* payload; + char cred_plaintext[2 * CRED_LEN + 1]; + char cred_base64[2 * CRED_LEN + 10]; if (g_ps.id > 0) { res = cJSON_CreateObject(); @@ -422,13 +407,12 @@ static void peer_signaling_onicecandidate(char *description, void *userdata) { cJSON_Delete(res); g_ps.id = 0; } else { - // enable authentication if (strlen(g_ps.username) > 0 && strlen(g_ps.password) > 0) { snprintf(cred_plaintext, sizeof(cred_plaintext), "%s:%s", g_ps.username, g_ps.password); snprintf(cred_base64, sizeof(cred_base64), "Basic "); base64_encode((unsigned char*)cred_plaintext, strlen(cred_plaintext), - cred_base64 + strlen(cred_base64), sizeof(cred_base64) - strlen(cred_base64)); + cred_base64 + strlen(cred_base64), sizeof(cred_base64) - strlen(cred_base64)); LOGD("Basic Auth: %s", cred_base64); peer_signaling_http_post(g_ps.http_host, g_ps.http_path, g_ps.http_port, cred_base64, description); } else { @@ -438,7 +422,6 @@ static void peer_signaling_onicecandidate(char *description, void *userdata) { } int peer_signaling_whip_connect() { - if (g_ps.pc == NULL) { LOGW("PeerConnection is NULL"); return -1; @@ -456,7 +439,6 @@ void peer_signaling_whip_disconnect() { } int peer_signaling_join_channel() { - if (g_ps.pc == NULL) { LOGW("PeerConnection is NULL"); return -1; @@ -479,7 +461,6 @@ int peer_signaling_join_channel() { } int peer_signaling_loop() { - if (g_ps.mqtt_port > 0) { MQTT_ProcessLoop(&g_ps.mqtt_ctx); } @@ -487,27 +468,22 @@ int peer_signaling_loop() { } void peer_signaling_leave_channel() { - MQTTStatus_t status = MQTTSuccess; if (g_ps.mqtt_port > 0 && peer_signaling_mqtt_subscribe(0) == 0) { - status = MQTT_Disconnect(&g_ps.mqtt_ctx); - if(status != MQTTSuccess) { - + if (status != MQTTSuccess) { LOGE("Failed to disconnect with broker: %s", MQTT_Status_strerror(status)); } } } -void peer_signaling_set_config(ServiceConfiguration *service_config) { - - char *pos; +void peer_signaling_set_config(ServiceConfiguration* service_config) { + char* pos; memset(&g_ps, 0, sizeof(g_ps)); do { - if (service_config->http_url == NULL || strlen(service_config->http_url) == 0) { break; } @@ -523,9 +499,7 @@ void peer_signaling_set_config(ServiceConfiguration *service_config) { LOGI("HTTP Host: %s, Port: %d, Path: %s", g_ps.http_host, g_ps.http_port, g_ps.http_path); } while (0); - do { - if (service_config->mqtt_url == NULL || strlen(service_config->mqtt_url) == 0) { break; } diff --git a/src/peer_signaling.h b/src/peer_signaling.h index 7ecff41..982c5d5 100644 --- a/src/peer_signaling.h +++ b/src/peer_signaling.h @@ -8,28 +8,29 @@ extern "C" { #endif typedef struct ServiceConfiguration { - const char *mqtt_url; + const char* mqtt_url; int mqtt_port; - const char *client_id; - const char *http_url; + const char* client_id; + const char* http_url; int http_port; - const char *username; - const char *password; - PeerConnection *pc; + const char* username; + const char* password; + PeerConnection* pc; } ServiceConfiguration; -#define SERVICE_CONFIG_DEFAULT() { \ - .mqtt_url = "broker.emqx.io", \ - .mqtt_port = 8883, \ - .client_id = "peer", \ - .http_url = "", \ - .http_port = 443, \ - .username = "", \ - .password = "", \ - .pc = NULL \ -} +#define SERVICE_CONFIG_DEFAULT() \ + { \ + .mqtt_url = "broker.emqx.io", \ + .mqtt_port = 8883, \ + .client_id = "peer", \ + .http_url = "", \ + .http_port = 443, \ + .username = "", \ + .password = "", \ + .pc = NULL \ + } -void peer_signaling_set_config(ServiceConfiguration *config); +void peer_signaling_set_config(ServiceConfiguration* config); int peer_signaling_whip_connect(); @@ -42,8 +43,7 @@ void peer_signaling_leave_channel(); int peer_signaling_loop(); #ifdef __cplusplus -} +} #endif -#endif //PEER_SIGNALING_H_ - +#endif // PEER_SIGNALING_H_ diff --git a/src/ports.c b/src/ports.c index be7229f..3f7efa0 100644 --- a/src/ports.c +++ b/src/ports.c @@ -1,28 +1,27 @@ -#include -#include -#include -#include #include +#include #include +#include #include +#include +#include #ifdef ESP32 #include #else +#include #include #include -#include #endif #include "ports.h" #include "utils.h" -int ports_get_host_addr(Address *addr) { - +int ports_get_host_addr(Address* addr) { int ret = 0; #ifdef ESP32 - esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); + esp_netif_t* netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); esp_netif_ip_info_t ip_info; esp_ip6_addr_t ip6_info; @@ -57,18 +56,18 @@ int ports_get_host_addr(Address *addr) { if (ifa->ifa_addr != NULL && strstr(ifa->ifa_name, IFR_NAME)) { if (ifa->ifa_addr->sa_family == addr->family) { switch (ifa->ifa_addr->sa_family) { - case AF_INET: - memcpy(&addr->sin, ifa->ifa_addr, sizeof(struct sockaddr_in)); - ret = 1; - break; - case AF_INET6: - memcpy(&addr->sin6, ifa->ifa_addr, sizeof(struct sockaddr_in6)); - ret = 1; - break; - default: - break; - } - if (ret) { + case AF_INET: + memcpy(&addr->sin, ifa->ifa_addr, sizeof(struct sockaddr_in)); + ret = 1; + break; + case AF_INET6: + memcpy(&addr->sin6, ifa->ifa_addr, sizeof(struct sockaddr_in6)); + ret = 1; + break; + default: + break; + } + if (ret) { break; } } @@ -78,7 +77,6 @@ int ports_get_host_addr(Address *addr) { return ret; - #if 0 struct ifaddrs *addrs,*tmp; @@ -128,8 +126,7 @@ LOGI("get_host_address inside while loop"); return ret; } -int ports_resolve_addr(const char *host, Address *addr) { - +int ports_resolve_addr(const char* host, Address* addr) { char addr_string[ADDRSTRLEN]; int ret = -1; struct addrinfo hints, *res, *p; @@ -148,13 +145,13 @@ int ports_resolve_addr(const char *host, Address *addr) { for (p = res; p != NULL; p = p->ai_next) { if (p->ai_family == addr->family) { switch (addr->family) { - case AF_INET6: - memcpy(&addr->sin6, p->ai_addr, sizeof(struct sockaddr_in6)); - break; + case AF_INET6: + memcpy(&addr->sin6, p->ai_addr, sizeof(struct sockaddr_in6)); + break; case AF_INET: - default: - memcpy(&addr->sin, p->ai_addr, sizeof(struct sockaddr_in)); - break; + default: + memcpy(&addr->sin, p->ai_addr, sizeof(struct sockaddr_in)); + break; } ret = 0; } @@ -167,8 +164,7 @@ int ports_resolve_addr(const char *host, Address *addr) { } uint32_t ports_get_epoch_time() { - struct timeval tv; gettimeofday(&tv, NULL); - return (uint32_t) tv.tv_sec * 1000 + tv.tv_usec / 1000; + return (uint32_t)tv.tv_sec * 1000 + tv.tv_usec / 1000; } diff --git a/src/ports.h b/src/ports.h index d5b4eee..ff569df 100644 --- a/src/ports.h +++ b/src/ports.h @@ -4,12 +4,12 @@ #include #include "address.h" -int ports_resolve_addr(const char *host, Address *addr); +int ports_resolve_addr(const char* host, Address* addr); -int ports_resolve_mdns_host(const char *host, Address *addr); +int ports_resolve_mdns_host(const char* host, Address* addr); -int ports_get_host_addr(Address *addr); +int ports_get_host_addr(Address* addr); uint32_t ports_get_epoch_time(); -#endif // PORTS_H_ +#endif // PORTS_H_ diff --git a/src/rtcp.c b/src/rtcp.c index 835ea73..49fafe4 100644 --- a/src/rtcp.c +++ b/src/rtcp.c @@ -1,63 +1,58 @@ -#include #include +#include #include #include "rtcp.h" #include "rtp.h" -int rtcp_probe(uint8_t *packet, size_t size) { - - if(size < 8) +int rtcp_probe(uint8_t* packet, size_t size) { + if (size < 8) return -1; - RtpHeader *header = (RtpHeader *)packet; + RtpHeader* header = (RtpHeader*)packet; return ((header->type >= 64) && (header->type < 96)); } -int rtcp_get_pli(uint8_t *packet, int len, uint32_t ssrc) { - - if(packet == NULL || len != 12) +int rtcp_get_pli(uint8_t* packet, int len, uint32_t ssrc) { + if (packet == NULL || len != 12) return -1; memset(packet, 0, len); - RtcpHeader *rtcp_header = (RtcpHeader *)packet; + RtcpHeader* rtcp_header = (RtcpHeader*)packet; rtcp_header->version = 2; rtcp_header->type = RTCP_PSFB; rtcp_header->rc = 1; - rtcp_header->length = htons((len/4)-1); + rtcp_header->length = htons((len / 4) - 1); memcpy(packet + 8, &ssrc, 4); return 12; } -int rtcp_get_fir(uint8_t *packet, int len, int *seqnr) { - - if(packet == NULL || len != 20 || seqnr == NULL) +int rtcp_get_fir(uint8_t* packet, int len, int* seqnr) { + if (packet == NULL || len != 20 || seqnr == NULL) return -1; memset(packet, 0, len); - RtcpHeader *rtcp = (RtcpHeader*)packet; + RtcpHeader* rtcp = (RtcpHeader*)packet; *seqnr = *seqnr + 1; - if(*seqnr < 0 || *seqnr >= 256) - *seqnr = 0; + if (*seqnr < 0 || *seqnr >= 256) + *seqnr = 0; rtcp->version = 2; rtcp->type = RTCP_PSFB; rtcp->rc = 4; - rtcp->length = htons((len/4)-1); - RtcpFb *rtcp_fb = (RtcpFb*)rtcp; - RtcpFir *fir = (RtcpFir*)rtcp_fb->fci; + rtcp->length = htons((len / 4) - 1); + RtcpFb* rtcp_fb = (RtcpFb*)rtcp; + RtcpFir* fir = (RtcpFir*)rtcp_fb->fci; fir->seqnr = htonl(*seqnr << 24); return 20; } -RtcpRr rtcp_parse_rr(uint8_t *packet) { - +RtcpRr rtcp_parse_rr(uint8_t* packet) { RtcpRr rtcp_rr; memcpy(&rtcp_rr.header, packet, sizeof(rtcp_rr.header)); - memcpy(&rtcp_rr.report_block[0], packet + 8, 6*sizeof(uint32_t)); + memcpy(&rtcp_rr.report_block[0], packet + 8, 6 * sizeof(uint32_t)); return rtcp_rr; } - diff --git a/src/rtcp.h b/src/rtcp.h index b7747a1..d3bbbb7 100644 --- a/src/rtcp.h +++ b/src/rtcp.h @@ -8,7 +8,6 @@ #include #endif - typedef enum RtcpType { RTCP_FIR = 192, @@ -24,24 +23,22 @@ typedef enum RtcpType { } RtcpType; typedef struct RtcpHeader { - #if __BYTE_ORDER == __BIG_ENDIAN - uint16_t version:2; - uint16_t padding:1; - uint16_t rc:5; - uint16_t type:8; + uint16_t version : 2; + uint16_t padding : 1; + uint16_t rc : 5; + uint16_t type : 8; #elif __BYTE_ORDER == __LITTLE_ENDIAN - uint16_t rc:5; - uint16_t padding:1; - uint16_t version:2; - uint16_t type:8; + uint16_t rc : 5; + uint16_t padding : 1; + uint16_t version : 2; + uint16_t type : 8; #endif - uint16_t length:16; + uint16_t length : 16; } RtcpHeader; typedef struct RtcpReportBlock { - uint32_t ssrc; uint32_t flcnpl; uint32_t ehsnr; @@ -51,9 +48,7 @@ typedef struct RtcpReportBlock { } RtcpReportBlock; - typedef struct RtcpRr { - RtcpHeader header; uint32_t ssrc; RtcpReportBlock report_block[1]; @@ -61,14 +56,12 @@ typedef struct RtcpRr { } RtcpRr; typedef struct RtcpFir { - uint32_t ssrc; uint32_t seqnr; } RtcpFir; typedef struct RtcpFb { - RtcpHeader header; uint32_t ssrc; uint32_t media; @@ -76,12 +69,12 @@ typedef struct RtcpFb { } RtcpFb; -int rtcp_probe(uint8_t *packet, size_t size); +int rtcp_probe(uint8_t* packet, size_t size); -int rtcp_get_pli(uint8_t *packet, int len, uint32_t ssrc); +int rtcp_get_pli(uint8_t* packet, int len, uint32_t ssrc); -int rtcp_get_fir(uint8_t *packet, int len, int *seqnr); +int rtcp_get_fir(uint8_t* packet, int len, int* seqnr); -RtcpRr rtcp_parse_rr(uint8_t *packet); +RtcpRr rtcp_parse_rr(uint8_t* packet); -#endif // RTCP_H_ +#endif // RTCP_H_ diff --git a/src/rtp.c b/src/rtp.c index c03bcae..b1edb1b 100644 --- a/src/rtp.c +++ b/src/rtp.c @@ -1,6 +1,6 @@ +#include #include #include -#include #include "peer_connection.h" #include "rtp.h" @@ -14,40 +14,36 @@ typedef enum RtpH264Type { } RtpH264Type; typedef struct NaluHeader { - - uint8_t type:5; - uint8_t nri:2; - uint8_t f:1; + uint8_t type : 5; + uint8_t nri : 2; + uint8_t f : 1; } NaluHeader; typedef struct FuHeader { - - uint8_t type:5; - uint8_t r:1; - uint8_t e:1; - uint8_t s:1; + uint8_t type : 5; + uint8_t r : 1; + uint8_t e : 1; + uint8_t s : 1; } FuHeader; #define RTP_PAYLOAD_SIZE (CONFIG_MTU - sizeof(RtpHeader)) #define FU_PAYLOAD_SIZE (CONFIG_MTU - sizeof(RtpHeader) - sizeof(FuHeader) - sizeof(NaluHeader)) -int rtp_packet_validate(uint8_t *packet, size_t size) { - - if(size < 12) +int rtp_packet_validate(uint8_t* packet, size_t size) { + if (size < 12) return 0; - RtpHeader *rtp_header = (RtpHeader*)packet; + RtpHeader* rtp_header = (RtpHeader*)packet; return ((rtp_header->type < 64) || (rtp_header->type >= 96)); } -uint32_t rtp_get_ssrc(uint8_t *packet) { - - RtpHeader *rtp_header = (RtpHeader*)packet; +uint32_t rtp_get_ssrc(uint8_t* packet) { + RtpHeader* rtp_header = (RtpHeader*)packet; return ntohl(rtp_header->ssrc); } -static int rtp_encoder_encode_h264_single(RtpEncoder *rtp_encoder, uint8_t *buf, size_t size) { - RtpPacket *rtp_packet = (RtpPacket*)rtp_encoder->buf; +static int rtp_encoder_encode_h264_single(RtpEncoder* rtp_encoder, uint8_t* buf, size_t size) { + RtpPacket* rtp_packet = (RtpPacket*)rtp_encoder->buf; rtp_packet->header.version = 2; rtp_packet->header.padding = 0; @@ -73,9 +69,8 @@ static int rtp_encoder_encode_h264_single(RtpEncoder *rtp_encoder, uint8_t *buf, return 0; } -static int rtp_encoder_encode_h264_fu_a(RtpEncoder *rtp_encoder, uint8_t *buf, size_t size) { - - RtpPacket *rtp_packet = (RtpPacket*)rtp_encoder->buf; +static int rtp_encoder_encode_h264_fu_a(RtpEncoder* rtp_encoder, uint8_t* buf, size_t size) { + RtpPacket* rtp_packet = (RtpPacket*)rtp_encoder->buf; rtp_packet->header.version = 2; rtp_packet->header.padding = 0; @@ -95,12 +90,11 @@ static int rtp_encoder_encode_h264_fu_a(RtpEncoder *rtp_encoder, uint8_t *buf, s rtp_encoder->timestamp += rtp_encoder->timestamp_increment; } - NaluHeader *fu_indicator = (NaluHeader*)rtp_packet->payload; - FuHeader *fu_header = (FuHeader*)rtp_packet->payload + sizeof(NaluHeader); + NaluHeader* fu_indicator = (NaluHeader*)rtp_packet->payload; + FuHeader* fu_header = (FuHeader*)rtp_packet->payload + sizeof(NaluHeader); fu_header->s = 1; while (size > 0) { - fu_indicator->type = FU_A; fu_indicator->nri = nri; fu_indicator->f = 0; @@ -109,7 +103,6 @@ static int rtp_encoder_encode_h264_fu_a(RtpEncoder *rtp_encoder, uint8_t *buf, s rtp_packet->header.seq_number = htons(rtp_encoder->seq_number++); if (size <= FU_PAYLOAD_SIZE) { - fu_header->e = 1; rtp_packet->header.markerbit = 1; memcpy(rtp_packet->payload + sizeof(NaluHeader) + sizeof(FuHeader), buf, size); @@ -129,12 +122,10 @@ static int rtp_encoder_encode_h264_fu_a(RtpEncoder *rtp_encoder, uint8_t *buf, s return 0; } -static uint8_t* h264_find_nalu(uint8_t *buf_start, uint8_t *buf_end) { - - uint8_t *p = buf_start + 2; +static uint8_t* h264_find_nalu(uint8_t* buf_start, uint8_t* buf_end) { + uint8_t* p = buf_start + 2; while (p < buf_end) { - if (*(p - 2) == 0x00 && *(p - 1) == 0x00 && *p == 0x01) return p + 1; p++; @@ -143,14 +134,12 @@ static uint8_t* h264_find_nalu(uint8_t *buf_start, uint8_t *buf_end) { return buf_end; } -static int rtp_encoder_encode_h264(RtpEncoder *rtp_encoder, uint8_t *buf, size_t size) { - - uint8_t *buf_end = buf + size; +static int rtp_encoder_encode_h264(RtpEncoder* rtp_encoder, uint8_t* buf, size_t size) { + uint8_t* buf_end = buf + size; uint8_t *pstart, *pend; size_t nalu_size; for (pstart = h264_find_nalu(buf, buf_end); pstart < buf_end; pstart = pend) { - pend = h264_find_nalu(pstart, buf_end); nalu_size = pend - pstart; @@ -161,22 +150,18 @@ static int rtp_encoder_encode_h264(RtpEncoder *rtp_encoder, uint8_t *buf, size_t nalu_size--; if (nalu_size <= RTP_PAYLOAD_SIZE) { - rtp_encoder_encode_h264_single(rtp_encoder, pstart, nalu_size); } else { - rtp_encoder_encode_h264_fu_a(rtp_encoder, pstart, nalu_size); } - } return 0; } -static int rtp_encoder_encode_generic(RtpEncoder *rtp_encoder, uint8_t *buf, size_t size) { - - RtpHeader *rtp_header = (RtpHeader*)rtp_encoder->buf; +static int rtp_encoder_encode_generic(RtpEncoder* rtp_encoder, uint8_t* buf, size_t size) { + RtpHeader* rtp_header = (RtpHeader*)rtp_encoder->buf; rtp_header->version = 2; rtp_header->padding = 0; rtp_header->extension = 0; @@ -190,41 +175,39 @@ static int rtp_encoder_encode_generic(RtpEncoder *rtp_encoder, uint8_t *buf, siz memcpy(rtp_encoder->buf + sizeof(RtpHeader), buf, size); rtp_encoder->on_packet(rtp_encoder->buf, size + sizeof(RtpHeader), rtp_encoder->user_data); - + return 0; } -void rtp_encoder_init(RtpEncoder *rtp_encoder, MediaCodec codec, RtpOnPacket on_packet, void *user_data) { - +void rtp_encoder_init(RtpEncoder* rtp_encoder, MediaCodec codec, RtpOnPacket on_packet, void* user_data) { rtp_encoder->on_packet = on_packet; rtp_encoder->user_data = user_data; rtp_encoder->timestamp = 0; rtp_encoder->seq_number = 0; switch (codec) { - case CODEC_H264: rtp_encoder->type = PT_H264; rtp_encoder->ssrc = SSRC_H264; - rtp_encoder->timestamp_increment = 90000/30; // 30 FPS. + rtp_encoder->timestamp_increment = 90000 / 30; // 30 FPS. rtp_encoder->encode_func = rtp_encoder_encode_h264; break; case CODEC_PCMA: rtp_encoder->type = PT_PCMA; rtp_encoder->ssrc = SSRC_PCMA; - rtp_encoder->timestamp_increment = AUDIO_LATENCY*8000/1000; + rtp_encoder->timestamp_increment = AUDIO_LATENCY * 8000 / 1000; rtp_encoder->encode_func = rtp_encoder_encode_generic; break; case CODEC_PCMU: rtp_encoder->type = PT_PCMU; rtp_encoder->ssrc = SSRC_PCMU; - rtp_encoder->timestamp_increment = AUDIO_LATENCY*8000/1000; + rtp_encoder->timestamp_increment = AUDIO_LATENCY * 8000 / 1000; rtp_encoder->encode_func = rtp_encoder_encode_generic; break; case CODEC_OPUS: rtp_encoder->type = PT_OPUS; rtp_encoder->ssrc = SSRC_OPUS; - rtp_encoder->timestamp_increment = AUDIO_LATENCY*48000/1000; + rtp_encoder->timestamp_increment = AUDIO_LATENCY * 48000 / 1000; rtp_encoder->encode_func = rtp_encoder_encode_generic; break; default: @@ -232,27 +215,23 @@ void rtp_encoder_init(RtpEncoder *rtp_encoder, MediaCodec codec, RtpOnPacket on_ } } -int rtp_encoder_encode(RtpEncoder *rtp_encoder, uint8_t *buf, size_t size) { - +int rtp_encoder_encode(RtpEncoder* rtp_encoder, uint8_t* buf, size_t size) { return rtp_encoder->encode_func(rtp_encoder, buf, size); } -static int rtp_decode_generic(RtpDecoder *rtp_decoder, uint8_t *buf, size_t size) { - - RtpPacket *rtp_packet = (RtpPacket*)buf; +static int rtp_decode_generic(RtpDecoder* rtp_decoder, uint8_t* buf, size_t size) { + RtpPacket* rtp_packet = (RtpPacket*)buf; if (rtp_decoder->on_packet != NULL) rtp_decoder->on_packet(rtp_packet->payload, size - sizeof(RtpHeader), rtp_decoder->user_data); // even if there is no callback set, assume everything is ok for caller and do not return an error - return (int) size; + return (int)size; } -void rtp_decoder_init(RtpDecoder *rtp_decoder, MediaCodec codec, RtpOnPacket on_packet, void *user_data) { - +void rtp_decoder_init(RtpDecoder* rtp_decoder, MediaCodec codec, RtpOnPacket on_packet, void* user_data) { rtp_decoder->on_packet = on_packet; rtp_decoder->user_data = user_data; switch (codec) { - case CODEC_H264: // TODO: implement rtp_decoder->decode_func = NULL; @@ -266,10 +245,8 @@ void rtp_decoder_init(RtpDecoder *rtp_decoder, MediaCodec codec, RtpOnPacket on_ } } -int rtp_decoder_decode(RtpDecoder *rtp_decoder, uint8_t *buf, size_t size) { - +int rtp_decoder_decode(RtpDecoder* rtp_decoder, uint8_t* buf, size_t size) { if (rtp_decoder->decode_func == NULL) return -1; return rtp_decoder->decode_func(rtp_decoder, buf, size); } - diff --git a/src/rtp.h b/src/rtp.h index b752a2e..12ab068 100644 --- a/src/rtp.h +++ b/src/rtp.h @@ -8,9 +8,8 @@ #include #endif - -#include "peer_connection.h" #include "config.h" +#include "peer_connection.h" #ifdef ESP32 #define __BIG_ENDIAN 4321 @@ -39,19 +38,19 @@ typedef enum RtpSsrc { typedef struct RtpHeader { #if __BYTE_ORDER == __BIG_ENDIAN - uint16_t version:2; - uint16_t padding:1; - uint16_t extension:1; - uint16_t csrccount:4; - uint16_t markerbit:1; - uint16_t type:7; + uint16_t version : 2; + uint16_t padding : 1; + uint16_t extension : 1; + uint16_t csrccount : 4; + uint16_t markerbit : 1; + uint16_t type : 7; #elif __BYTE_ORDER == __LITTLE_ENDIAN - uint16_t csrccount:4; - uint16_t extension:1; - uint16_t padding:1; - uint16_t version:2; - uint16_t type:7; - uint16_t markerbit:1; + uint16_t csrccount : 4; + uint16_t extension : 1; + uint16_t padding : 1; + uint16_t version : 2; + uint16_t type : 7; + uint16_t markerbit : 1; #endif uint16_t seq_number; uint32_t timestamp; @@ -61,14 +60,12 @@ typedef struct RtpHeader { } RtpHeader; typedef struct RtpPacket { - RtpHeader header; uint8_t payload[0]; } RtpPacket; typedef struct RtpMap { - int pt_h264; int pt_opus; int pt_pcma; @@ -77,22 +74,20 @@ typedef struct RtpMap { typedef struct RtpEncoder RtpEncoder; typedef struct RtpDecoder RtpDecoder; -typedef void (*RtpOnPacket)(uint8_t *packet, size_t bytes, void *user_data); +typedef void (*RtpOnPacket)(uint8_t* packet, size_t bytes, void* user_data); struct RtpDecoder { - RtpPayloadType type; RtpOnPacket on_packet; - int (*decode_func)(RtpDecoder *rtp_decoder, uint8_t *data, size_t size); - void *user_data; + int (*decode_func)(RtpDecoder* rtp_decoder, uint8_t* data, size_t size); + void* user_data; }; struct RtpEncoder { - RtpPayloadType type; RtpOnPacket on_packet; - int (*encode_func)(RtpEncoder *rtp_encoder, uint8_t *data, size_t size); - void *user_data; + int (*encode_func)(RtpEncoder* rtp_encoder, uint8_t* data, size_t size); + void* user_data; uint16_t seq_number; uint32_t ssrc; uint32_t timestamp; @@ -100,16 +95,16 @@ struct RtpEncoder { uint8_t buf[CONFIG_MTU + 128]; }; -int rtp_packet_validate(uint8_t *packet, size_t size); +int rtp_packet_validate(uint8_t* packet, size_t size); -void rtp_encoder_init(RtpEncoder *rtp_encoder, MediaCodec codec, RtpOnPacket on_packet, void *user_data); +void rtp_encoder_init(RtpEncoder* rtp_encoder, MediaCodec codec, RtpOnPacket on_packet, void* user_data); -int rtp_encoder_encode(RtpEncoder *rtp_encoder, uint8_t *data, size_t size); +int rtp_encoder_encode(RtpEncoder* rtp_encoder, uint8_t* data, size_t size); -void rtp_decoder_init(RtpDecoder *rtp_decoder, MediaCodec codec, RtpOnPacket on_packet, void *user_data); +void rtp_decoder_init(RtpDecoder* rtp_decoder, MediaCodec codec, RtpOnPacket on_packet, void* user_data); -int rtp_decoder_decode(RtpDecoder *rtp_decoder, uint8_t *data, size_t size); +int rtp_decoder_decode(RtpDecoder* rtp_decoder, uint8_t* data, size_t size); -uint32_t rtp_get_ssrc(uint8_t *packet); +uint32_t rtp_get_ssrc(uint8_t* packet); -#endif // RTP_H_ +#endif // RTP_H_ diff --git a/src/sctp.c b/src/sctp.c index 2b78c4f..5233c3c 100644 --- a/src/sctp.c +++ b/src/sctp.c @@ -1,6 +1,6 @@ +#include #include #include -#include #include "sctp.h" #ifdef HAVE_USRSCTP @@ -10,12 +10,12 @@ #include "dtls_srtp.h" #include "utils.h" -#define DATA_CHANNEL_PPID_CONTROL 50 -#define DATA_CHANNEL_PPID_DOMSTRING 51 -#define DATA_CHANNEL_PPID_BINARY_PARTIAL 52 -#define DATA_CHANNEL_PPID_BINARY 53 +#define DATA_CHANNEL_PPID_CONTROL 50 +#define DATA_CHANNEL_PPID_DOMSTRING 51 +#define DATA_CHANNEL_PPID_BINARY_PARTIAL 52 +#define DATA_CHANNEL_PPID_BINARY 53 #define DATA_CHANNEL_PPID_DOMSTRING_PARTIAL 54 -#define DATA_CHANNEL_OPEN 0x03 +#define DATA_CHANNEL_OPEN 0x03 static const uint32_t crc32c_table[256] = { 0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L, @@ -81,36 +81,29 @@ static const uint32_t crc32c_table[256] = { 0xF36E6F75L, 0x0105EC76L, 0x12551F82L, 0xE03E9C81L, 0x34F4F86AL, 0xC69F7B69L, 0xD5CF889DL, 0x27A40B9EL, 0x79B737BAL, 0x8BDCB4B9L, 0x988C474DL, 0x6AE7C44EL, - 0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, 0xAD7D5351L -}; - + 0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, 0xAD7D5351L}; -uint32_t crc32c(uint32_t crc, const uint8_t *data, unsigned int length) -{ - while (length--) { - crc = crc32c_table[(crc ^ *data++) & 0xFFL] ^ (crc >> 8); - } - return crc^0xffffffff; +uint32_t crc32c(uint32_t crc, const uint8_t* data, unsigned int length) { + while (length--) { + crc = crc32c_table[(crc ^ *data++) & 0xFFL] ^ (crc >> 8); + } + return crc ^ 0xffffffff; } - -static uint32_t sctp_get_checksum(Sctp *sctp, const uint8_t *buf, size_t len) { - +static uint32_t sctp_get_checksum(Sctp* sctp, const uint8_t* buf, size_t len) { uint32_t crc = crc32c(0xffffffff, buf, len); return crc; } -static int sctp_outgoing_data_cb(void *userdata, void *buf, size_t len, uint8_t tos, uint8_t set_df) { - - Sctp *sctp = (Sctp*)userdata; +static int sctp_outgoing_data_cb(void* userdata, void* buf, size_t len, uint8_t tos, uint8_t set_df) { + Sctp* sctp = (Sctp*)userdata; dtls_srtp_write(sctp->dtls_srtp, buf, len); return 0; } -int sctp_outgoing_data(Sctp *sctp, char *buf, size_t len, SctpDataPpid ppid, uint16_t sid) { - +int sctp_outgoing_data(Sctp* sctp, char* buf, size_t len, SctpDataPpid ppid, uint16_t sid) { #ifdef HAVE_USRSCTP int res; struct sctp_sendv_spa spa = {0}; @@ -122,7 +115,7 @@ int sctp_outgoing_data(Sctp *sctp, char *buf, size_t len, SctpDataPpid ppid, uin spa.sendv_sndinfo.snd_ppid = htonl(ppid); res = usrsctp_sendv(sctp->sock, buf, len, NULL, 0, &spa, sizeof(spa), SCTP_SENDV_SPA, 0); - if(res < 0) + if (res < 0) LOGE("sctp sendv error %d %s", errno, strerror(errno)); return res; #else @@ -131,8 +124,8 @@ int sctp_outgoing_data(Sctp *sctp, char *buf, size_t len, SctpDataPpid ppid, uin size_t pos = 0; static uint16_t sqn = 0; - SctpPacket *packet = (SctpPacket*)(sctp->buf); - SctpDataChunk *chunk = (SctpDataChunk*)(packet->chunks); + SctpPacket* packet = (SctpPacket*)(sctp->buf); + SctpDataChunk* chunk = (SctpDataChunk*)(packet->chunks); packet->header.source_port = htons(sctp->local_port); packet->header.destination_port = htons(sctp->remote_port); @@ -145,7 +138,6 @@ int sctp_outgoing_data(Sctp *sctp, char *buf, size_t len, SctpDataPpid ppid, uin chunk->ppid = htonl(ppid); while (len > payload_max) { - chunk->length = htons(payload_max + sizeof(SctpDataChunk)); chunk->tsn = htonl(sctp->tsn++); memcpy(chunk->data, buf + pos, payload_max); @@ -160,14 +152,13 @@ int sctp_outgoing_data(Sctp *sctp, char *buf, size_t len, SctpDataPpid ppid, uin } if (len > 0) { - chunk->length = htons(len + sizeof(SctpDataChunk)); chunk->iube++; chunk->tsn = htonl(sctp->tsn++); memset(chunk->data, 0, payload_max); memcpy(chunk->data, buf + pos, len); packet->header.checksum = 0; - + padding_len = 4 * ((len + sizeof(SctpDataChunk) + sizeof(SctpPacket) + 3) / 4); packet->header.checksum = sctp_get_checksum(sctp, (const uint8_t*)sctp->buf, padding_len); @@ -178,30 +169,30 @@ int sctp_outgoing_data(Sctp *sctp, char *buf, size_t len, SctpDataPpid ppid, uin return len; } -void sctp_add_stream_mapping(Sctp *sctp, const char *label, uint16_t sid) { - if (sctp->stream_countstream_count < SCTP_MAX_STREAMS) { strncpy(sctp->stream_table[sctp->stream_count].label, label, sizeof(sctp->stream_table[sctp->stream_count].label)); sctp->stream_table[sctp->stream_count].sid = sid; sctp->stream_count++; - } else - LOGE("Stream table full. Cannot add more streams."); + } else + LOGE("Stream table full. Cannot add more streams."); } -void sctp_parse_data_channel_open(Sctp *sctp, uint16_t sid, char *data, size_t length) { - if (length < 12) +void sctp_parse_data_channel_open(Sctp* sctp, uint16_t sid, char* data, size_t length) { + if (length < 12) return; // Not enough data for a DATA_CHANNEL_OPEN message - - if (data[0]==DATA_CHANNEL_OPEN) { - uint16_t label_length = ntohs(*(uint16_t *)(data + 8)); - uint16_t protocol_length = ntohs(*(uint16_t *)(data + 10)); + + if (data[0] == DATA_CHANNEL_OPEN) { + uint16_t label_length = ntohs(*(uint16_t*)(data + 8)); + uint16_t protocol_length = ntohs(*(uint16_t*)(data + 10)); // Ensure we have enough data for the label and protocol - if (length < 12 + label_length + protocol_length) + if (length < 12 + label_length + protocol_length) return; - char *label = (char *)(data + 12); + char* label = (char*)(data + 12); - // copy and null-terminate + // copy and null-terminate char label_str[label_length + 1]; memcpy(label_str, label, label_length); label_str[label_length] = '\0'; @@ -214,23 +205,22 @@ void sctp_parse_data_channel_open(Sctp *sctp, uint16_t sid, char *data, size_t l } } -void sctp_handle_sctp_packet(Sctp *sctp, char *buf, size_t len) { - if (len<=29) - return; - - if (buf[12]!=0) // if chunk_type is no zero, it's not data - return; - - uint16_t sid = ntohs(*(uint16_t *)(buf + 20)); - uint32_t ppid = ntohl(*(uint32_t *)(buf + 24)); - - if (ppid==DATA_CHANNEL_PPID_CONTROL) - sctp_parse_data_channel_open(sctp, sid, buf + 28, len - 28); -} +void sctp_handle_sctp_packet(Sctp* sctp, char* buf, size_t len) { + if (len <= 29) + return; -void sctp_incoming_data(Sctp *sctp, char *buf, size_t len) { + if (buf[12] != 0) // if chunk_type is no zero, it's not data + return; + + uint16_t sid = ntohs(*(uint16_t*)(buf + 20)); + uint32_t ppid = ntohl(*(uint32_t*)(buf + 24)); - if(!sctp) + if (ppid == DATA_CHANNEL_PPID_CONTROL) + sctp_parse_data_channel_open(sctp, sid, buf + 28, len - 28); +} + +void sctp_incoming_data(Sctp* sctp, char* buf, size_t len) { + if (!sctp) return; #ifdef HAVE_USRSCTP @@ -239,11 +229,11 @@ void sctp_incoming_data(Sctp *sctp, char *buf, size_t len) { #else size_t length = 0; size_t pos = sizeof(SctpHeader); - SctpChunkCommon *chunk_common; - SctpDataChunk *data_chunk; - SctpSackChunk *sack; - SctpPacket *in_packet = (SctpPacket*)buf; - SctpPacket *out_packet = (SctpPacket*)sctp->buf; + SctpChunkCommon* chunk_common; + SctpDataChunk* data_chunk; + SctpSackChunk* sack; + SctpPacket* in_packet = (SctpPacket*)buf; + SctpPacket* out_packet = (SctpPacket*)sctp->buf; // Header #if 0 @@ -265,12 +255,10 @@ void sctp_incoming_data(Sctp *sctp, char *buf, size_t len) { memset(sctp->buf, 0, sizeof(sctp->buf)); // chunks - while ((4*(pos + 3)/4) < len) { - + while ((4 * (pos + 3) / 4) < len) { chunk_common = (SctpChunkCommon*)(buf + pos); switch (chunk_common->type) { - case SCTP_DATA: data_chunk = (SctpDataChunk*)(buf + pos); @@ -283,7 +271,6 @@ void sctp_incoming_data(Sctp *sctp, char *buf, size_t len) { } else if (ntohl(data_chunk->ppid) == DATA_CHANNEL_PPID_DOMSTRING) { #endif if (ntohl(data_chunk->ppid) == DATA_CHANNEL_PPID_DOMSTRING) { - if (sctp->onmessage) { sctp->onmessage((char*)data_chunk->data, ntohs(data_chunk->length) - sizeof(SctpDataChunk), sctp->userdata, ntohs(data_chunk->sid)); } @@ -296,16 +283,16 @@ void sctp_incoming_data(Sctp *sctp, char *buf, size_t len) { sack->cumulative_tsn_ack = data_chunk->tsn; sack->a_rwnd = htonl(0x02); length = ntohs(sack->common.length) + sizeof(SctpHeader); - pos = len; // Do not handle other msg + pos = len; // Do not handle other msg break; case SCTP_INIT: LOGD("SCTP_INIT"); - SctpInitChunk *init_chunk; + SctpInitChunk* init_chunk; init_chunk = (SctpInitChunk*)in_packet->chunks; sctp->verification_tag = init_chunk->initiate_tag; - SctpInitChunk *init_ack = (SctpInitChunk*)out_packet->chunks; + SctpInitChunk* init_ack = (SctpInitChunk*)out_packet->chunks; init_ack->common.type = SCTP_INIT_ACK; init_ack->common.flags = 0x00; init_ack->common.length = htons(20 + 8); @@ -315,7 +302,7 @@ void sctp_incoming_data(Sctp *sctp, char *buf, size_t len) { init_ack->number_of_inbound_streams = 0xffff; init_ack->initial_tsn = htonl(sctp->tsn); - SctpChunkParam *param = init_ack->param; + SctpChunkParam* param = init_ack->param; param->type = htons(SCTP_PARAM_STATE_COOKIE); param->length = htons(0x08); @@ -357,16 +344,16 @@ void sctp_incoming_data(Sctp *sctp, char *buf, size_t len) { break; case SCTP_COOKIE_ECHO: LOGD("SCTP_COOKIE_ECHO"); - SctpChunkCommon *common = (SctpChunkCommon*)out_packet->chunks; + SctpChunkCommon* common = (SctpChunkCommon*)out_packet->chunks; common->type = SCTP_COOKIE_ACK; common->length = htons(4); length = ntohs(common->length) + sizeof(SctpHeader); - pos = len; // Do not handle other msg + pos = len; // Do not handle other msg // XXX: Initiate the sctp association if (!sctp->connected) { sctp->connected = 1; - if(sctp->onopen) { + if (sctp->onopen) { sctp->onopen(sctp->userdata); } } @@ -384,21 +371,20 @@ void sctp_incoming_data(Sctp *sctp, char *buf, size_t len) { if (length > 0) { // padding 4 - length = (4*((length + 3)/4)); + length = (4 * ((length + 3) / 4)); out_packet->header.checksum = sctp_get_checksum(sctp, sctp->buf, length); dtls_srtp_write(sctp->dtls_srtp, sctp->buf, length); - //sctp_outgoing_data_cb(sctp, sctp->buf, SCTP_MTU, 0, 0); + // sctp_outgoing_data_cb(sctp, sctp->buf, SCTP_MTU, 0, 0); } pos += ntohs(chunk_common->length); } #endif - } -static int sctp_handle_incoming_data(Sctp *sctp, char *data, size_t len, uint32_t ppid, uint16_t sid, int flags) { +static int sctp_handle_incoming_data(Sctp* sctp, char* data, size_t len, uint32_t ppid, uint16_t sid, int flags) { #ifdef HAVE_USRSCTP - switch(ppid) { + switch (ppid) { case DATA_CHANNEL_PPID_CONTROL: break; @@ -408,7 +394,7 @@ static int sctp_handle_incoming_data(Sctp *sctp, char *data, size_t len, uint32_ case DATA_CHANNEL_PPID_BINARY_PARTIAL: LOGD("Got message (size = %ld)", len); - if(sctp->onmessage) { + if (sctp->onmessage) { sctp->onmessage(data, len, sctp->userdata, sid); } break; @@ -420,26 +406,21 @@ static int sctp_handle_incoming_data(Sctp *sctp, char *data, size_t len, uint32_ return 0; } - #ifdef HAVE_USRSCTP -static void sctp_process_notification(Sctp *sctp, union sctp_notification *notification, size_t len) { - - - if(notification->sn_header.sn_length != (uint32_t)len) { - return; - } +static void sctp_process_notification(Sctp* sctp, union sctp_notification* notification, size_t len) { + if (notification->sn_header.sn_length != (uint32_t)len) { + return; + } switch (notification->sn_header.sn_type) { - case SCTP_ASSOC_CHANGE: switch (notification->sn_assoc_change.sac_state) { - case SCTP_COMM_UP: sctp->connected = 1; - if(sctp->onopen) { + if (sctp->onopen) { sctp->onopen(sctp->userdata); } @@ -448,7 +429,7 @@ static void sctp_process_notification(Sctp *sctp, union sctp_notification *notif case SCTP_COMM_LOST: case SCTP_SHUTDOWN_COMP: sctp->connected = 0; - if(sctp->onclose) { + if (sctp->onclose) { sctp->onclose(sctp->userdata); } default: @@ -458,20 +439,19 @@ static void sctp_process_notification(Sctp *sctp, union sctp_notification *notif default: break; } - free(notification); // we need to free the memory that usrsctp allocates + free(notification); // we need to free the memory that usrsctp allocates } -static int sctp_incoming_data_cb(struct socket *sock, union sctp_sockstore addr, - void *data, size_t len, struct sctp_rcvinfo recv_info, int flags, void *userdata) { - Sctp *sctp = (Sctp*)userdata; +static int sctp_incoming_data_cb(struct socket* sock, union sctp_sockstore addr, void* data, size_t len, struct sctp_rcvinfo recv_info, int flags, void* userdata) { + Sctp* sctp = (Sctp*)userdata; LOGD("Data of length %u received on stream %u with SSN %u, TSN %u, PPID %u", - (uint32_t)len, - recv_info.rcv_sid, - recv_info.rcv_ssn, - recv_info.rcv_tsn, - ntohl(recv_info.rcv_ppid)); - if(flags & MSG_NOTIFICATION) { - sctp_process_notification(sctp, (union sctp_notification *)data, len); + (uint32_t)len, + recv_info.rcv_sid, + recv_info.rcv_ssn, + recv_info.rcv_tsn, + ntohl(recv_info.rcv_ppid)); + if (flags & MSG_NOTIFICATION) { + sctp_process_notification(sctp, (union sctp_notification*)data, len); } else { sctp_handle_incoming_data(sctp, data, len, ntohl(recv_info.rcv_ppid), recv_info.rcv_sid, flags); } @@ -479,8 +459,7 @@ static int sctp_incoming_data_cb(struct socket *sock, union sctp_sockstore addr, } #endif -int sctp_create_socket(Sctp *sctp, DtlsSrtp *dtls_srtp) { - +int sctp_create_socket(Sctp* sctp, DtlsSrtp* dtls_srtp) { sctp->dtls_srtp = dtls_srtp; sctp->local_port = 5000; sctp->remote_port = 5000; @@ -491,17 +470,16 @@ int sctp_create_socket(Sctp *sctp, DtlsSrtp *dtls_srtp) { usrsctp_sysctl_set_sctp_ecn_enable(0); usrsctp_register_address(sctp); - struct socket *sock = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP, - sctp_incoming_data_cb, NULL, 0, sctp); + struct socket* sock = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP, + sctp_incoming_data_cb, NULL, 0, sctp); - if(!sock) { + if (!sock) { LOGE("usrsctp_socket failed"); return -1; } do { - - if(usrsctp_set_non_blocking(sock, 1) < 0) { + if (usrsctp_set_non_blocking(sock, 1) < 0) { LOGE("usrsctp_set_non_blocking failed"); break; } @@ -528,24 +506,23 @@ int sctp_create_socket(Sctp *sctp, DtlsSrtp *dtls_srtp) { usrsctp_setsockopt(sock, IPPROTO_SCTP, SCTP_NODELAY, &nodelay, sizeof(nodelay)); static uint16_t event_types[] = { - SCTP_ASSOC_CHANGE, - SCTP_PEER_ADDR_CHANGE, - SCTP_REMOTE_ERROR, - SCTP_SHUTDOWN_EVENT, - SCTP_ADAPTATION_INDICATION, - SCTP_SEND_FAILED_EVENT, - SCTP_SENDER_DRY_EVENT, - SCTP_STREAM_RESET_EVENT, - SCTP_STREAM_CHANGE_EVENT - }; + SCTP_ASSOC_CHANGE, + SCTP_PEER_ADDR_CHANGE, + SCTP_REMOTE_ERROR, + SCTP_SHUTDOWN_EVENT, + SCTP_ADAPTATION_INDICATION, + SCTP_SEND_FAILED_EVENT, + SCTP_SENDER_DRY_EVENT, + SCTP_STREAM_RESET_EVENT, + SCTP_STREAM_CHANGE_EVENT}; struct sctp_event event; memset(&event, 0, sizeof(event)); event.se_assoc_id = SCTP_ALL_ASSOC; event.se_on = 1; - for(int i = 0; i < sizeof(event_types)/sizeof(uint16_t); i++) { - event.se_type = event_types[i]; - usrsctp_setsockopt(sock, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(event)); + for (int i = 0; i < sizeof(event_types) / sizeof(uint16_t); i++) { + event.se_type = event_types[i]; + usrsctp_setsockopt(sock, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(event)); } struct sctp_initmsg init_msg; @@ -558,8 +535,8 @@ int sctp_create_socket(Sctp *sctp, DtlsSrtp *dtls_srtp) { memset(&sconn, 0, sizeof(sconn)); sconn.sconn_family = AF_CONN; sconn.sconn_port = htons(sctp->local_port); - sconn.sconn_addr = (void *)sctp; - ret = usrsctp_bind(sock, (struct sockaddr *)&sconn, sizeof(sconn)); + sconn.sconn_addr = (void*)sctp; + ret = usrsctp_bind(sock, (struct sockaddr*)&sconn, sizeof(sconn)); struct sockaddr_conn rconn; @@ -567,19 +544,18 @@ int sctp_create_socket(Sctp *sctp, DtlsSrtp *dtls_srtp) { rconn.sconn_family = AF_CONN; rconn.sconn_port = htons(sctp->remote_port); rconn.sconn_addr = (void*)sctp; - ret = usrsctp_connect(sock, (struct sockaddr *)&rconn, sizeof(struct sockaddr_conn)); + ret = usrsctp_connect(sock, (struct sockaddr*)&rconn, sizeof(struct sockaddr_conn)); - if(ret < 0 && errno != EINPROGRESS) { + if (ret < 0 && errno != EINPROGRESS) { LOGE("connect error"); break; } ret = 0; - } while(0); - - if(ret < 0) { + } while (0); + if (ret < 0) { usrsctp_shutdown(sctp->sock, SHUT_RDWR); usrsctp_close(sctp->sock); sctp->sock = NULL; @@ -592,16 +568,14 @@ int sctp_create_socket(Sctp *sctp, DtlsSrtp *dtls_srtp) { return 0; } -int sctp_is_connected(Sctp *sctp) { - +int sctp_is_connected(Sctp* sctp) { return sctp->connected; } -void sctp_destroy(Sctp *sctp) { +void sctp_destroy(Sctp* sctp) { #ifdef HAVE_USRSCTP - if(sctp) { - - if(sctp->sock) { + if (sctp) { + if (sctp->sock) { usrsctp_shutdown(sctp->sock, SHUT_RDWR); usrsctp_close(sctp->sock); sctp->sock = NULL; @@ -613,18 +587,14 @@ void sctp_destroy(Sctp *sctp) { #endif } -void sctp_onmessage(Sctp *sctp, void (*onmessage)(char *msg, size_t len, void *userdata, uint16_t sid)) { - +void sctp_onmessage(Sctp* sctp, void (*onmessage)(char* msg, size_t len, void* userdata, uint16_t sid)) { sctp->onmessage = onmessage; } -void sctp_onopen(Sctp *sctp, void (*onopen)(void *userdata)) { - +void sctp_onopen(Sctp* sctp, void (*onopen)(void* userdata)) { sctp->onopen = onopen; } -void sctp_onclose(Sctp *sctp, void (*onclose)(void *userdata)) { - +void sctp_onclose(Sctp* sctp, void (*onclose)(void* userdata)) { sctp->onclose = onclose; } - diff --git a/src/sctp.h b/src/sctp.h index ddcabca..6489603 100644 --- a/src/sctp.h +++ b/src/sctp.h @@ -1,22 +1,21 @@ #ifndef SCTP_H_ #define SCTP_H_ +#include "buffer.h" #include "config.h" #include "dtls_srtp.h" #include "utils.h" -#include "buffer.h" #ifndef HAVE_USRSCTP typedef enum DecpMsgType { - + DATA_CHANNEL_OPEN = 0x03, DATA_CHANNEL_ACK = 0x02, } DecpMsgType; typedef struct SctpChunkParam { - uint16_t type; uint16_t length; uint8_t value[0]; @@ -34,10 +33,10 @@ typedef enum SctpHeaderType { SCTP_DATA = 0, SCTP_INIT = 1, SCTP_INIT_ACK = 2, - SCTP_SACK = 3, + SCTP_SACK = 3, SCTP_HEARTBEAT = 4, SCTP_HEARTBEAT_ACK = 5, - SCTP_ABORT = 6, + SCTP_ABORT = 6, SCTP_SHUTDOWN = 7, SCTP_SHUTDOWN_ACK = 8, SCTP_ERROR = 9, @@ -46,7 +45,7 @@ typedef enum SctpHeaderType { SCTP_ECNE = 12, SCTP_CWR = 13, SCTP_SHUTDOWN_COMPLETE = 14, - SCTP_AUTH = 15, + SCTP_AUTH = 15, SCTP_ASCONF_ACK = 128, SCTP_ASCONF = 130, SCTP_FORWARD_TSN = 192 @@ -54,7 +53,6 @@ typedef enum SctpHeaderType { } SctpHeaderType; typedef struct SctpChunkCommon { - uint8_t type; uint8_t flags; uint16_t length; @@ -62,7 +60,6 @@ typedef struct SctpChunkCommon { } SctpChunkCommon; typedef struct SctpForwardTsnChunk { - SctpChunkCommon common; uint32_t new_cumulative_tsn; uint16_t stream_number; @@ -70,10 +67,7 @@ typedef struct SctpForwardTsnChunk { } SctpForwardTsnChunk; - - typedef struct SctpHeader { - uint16_t source_port; uint16_t destination_port; uint32_t verification_tag; @@ -82,14 +76,12 @@ typedef struct SctpHeader { } SctpHeader; typedef struct SctpPacket { - SctpHeader header; uint8_t chunks[0]; } SctpPacket; typedef struct SctpSackChunk { - SctpChunkCommon common; uint32_t cumulative_tsn_ack; uint32_t a_rwnd; @@ -100,7 +92,6 @@ typedef struct SctpSackChunk { } SctpSackChunk; typedef struct SctpDataChunk { - uint8_t type; uint8_t iube; uint16_t length; @@ -113,7 +104,6 @@ typedef struct SctpDataChunk { } SctpDataChunk; typedef struct SctpInitChunk { - SctpChunkCommon common; uint32_t initiate_tag; uint32_t a_rwnd; @@ -136,53 +126,51 @@ typedef enum SctpDataPpid { } SctpDataPpid; -#define SCTP_MAX_STREAMS 5 +#define SCTP_MAX_STREAMS 5 typedef struct { - char label[32]; // Stream label - uint16_t sid; // Stream ID + char label[32]; // Stream label + uint16_t sid; // Stream ID } SctpStreamEntry; typedef struct Sctp { - - struct socket *sock; + struct socket* sock; int local_port; int remote_port; int connected; uint32_t verification_tag; uint32_t tsn; - DtlsSrtp *dtls_srtp; - Buffer **data_rb; + DtlsSrtp* dtls_srtp; + Buffer** data_rb; int stream_count; SctpStreamEntry stream_table[SCTP_MAX_STREAMS]; /* datachannel */ - void (*onmessage)(char *msg, size_t len, void *userdata, uint16_t sid); - void (*onopen)(void *userdata); - void (*onclose)(void *userdata); + void (*onmessage)(char* msg, size_t len, void* userdata, uint16_t sid); + void (*onopen)(void* userdata); + void (*onclose)(void* userdata); - void *userdata; + void* userdata; uint8_t buf[CONFIG_MTU]; } Sctp; +Sctp* sctp_create(DtlsSrtp* dtls_srtp); -Sctp* sctp_create(DtlsSrtp *dtls_srtp); - -void sctp_destroy(Sctp *sctp); +void sctp_destroy(Sctp* sctp); -int sctp_create_socket(Sctp *sctp, DtlsSrtp *dtls_srtp); +int sctp_create_socket(Sctp* sctp, DtlsSrtp* dtls_srtp); -int sctp_is_connected(Sctp *sctp); +int sctp_is_connected(Sctp* sctp); -void sctp_incoming_data(Sctp *sctp, char *buf, size_t len); +void sctp_incoming_data(Sctp* sctp, char* buf, size_t len); -int sctp_outgoing_data(Sctp *sctp, char *buf, size_t len, SctpDataPpid ppid, uint16_t sid); +int sctp_outgoing_data(Sctp* sctp, char* buf, size_t len, SctpDataPpid ppid, uint16_t sid); -void sctp_onmessage(Sctp *sctp, void (*onmessage)(char *msg, size_t len, void *userdata, uint16_t sid)); +void sctp_onmessage(Sctp* sctp, void (*onmessage)(char* msg, size_t len, void* userdata, uint16_t sid)); -void sctp_onopen(Sctp *sctp, void (*onopen)(void *userdata)); +void sctp_onopen(Sctp* sctp, void (*onopen)(void* userdata)); -void sctp_onclose(Sctp *sctp, void (*onclose)(void *userdata)); +void sctp_onclose(Sctp* sctp, void (*onclose)(void* userdata)); -#endif // SCTP_H_ +#endif // SCTP_H_ diff --git a/src/sdp.c b/src/sdp.c index f959e56..871e451 100644 --- a/src/sdp.c +++ b/src/sdp.c @@ -1,10 +1,9 @@ -#include #include +#include #include "sdp.h" -int sdp_append(Sdp *sdp, const char *format, ...) { - +int sdp_append(Sdp* sdp, const char* format, ...) { va_list argptr; char attr[SDP_ATTR_LENGTH]; @@ -22,13 +21,11 @@ int sdp_append(Sdp *sdp, const char *format, ...) { return 0; } -void sdp_reset(Sdp *sdp) { - +void sdp_reset(Sdp* sdp) { memset(sdp->content, 0, sizeof(sdp->content)); } -void sdp_append_h264(Sdp *sdp) { - +void sdp_append_h264(Sdp* sdp) { sdp_append(sdp, "m=video 9 UDP/TLS/RTP/SAVPF 96 102"); sdp_append(sdp, "a=rtcp-fb:102 nack"); sdp_append(sdp, "a=rtcp-fb:102 nack pli"); @@ -43,8 +40,7 @@ void sdp_append_h264(Sdp *sdp) { sdp_append(sdp, "a=rtcp-mux"); } -void sdp_append_pcma(Sdp *sdp) { - +void sdp_append_pcma(Sdp* sdp) { sdp_append(sdp, "m=audio 9 UDP/TLS/RTP/SAVP 8"); sdp_append(sdp, "a=rtpmap:8 PCMA/8000"); sdp_append(sdp, "a=ssrc:4 cname:webrtc-pcma"); @@ -54,8 +50,7 @@ void sdp_append_pcma(Sdp *sdp) { sdp_append(sdp, "a=rtcp-mux"); } -void sdp_append_pcmu(Sdp *sdp) { - +void sdp_append_pcmu(Sdp* sdp) { sdp_append(sdp, "m=audio 9 UDP/TLS/RTP/SAVP 0"); sdp_append(sdp, "a=rtpmap:0 PCMU/8000"); sdp_append(sdp, "a=ssrc:5 cname:webrtc-pcmu"); @@ -65,8 +60,7 @@ void sdp_append_pcmu(Sdp *sdp) { sdp_append(sdp, "a=rtcp-mux"); } -void sdp_append_opus(Sdp *sdp) { - +void sdp_append_opus(Sdp* sdp) { sdp_append(sdp, "m=audio 9 UDP/TLS/RTP/SAVP 111"); sdp_append(sdp, "a=rtpmap:111 opus/48000/2"); sdp_append(sdp, "a=ssrc:6 cname:webrtc-opus"); @@ -76,8 +70,7 @@ void sdp_append_opus(Sdp *sdp) { sdp_append(sdp, "a=rtcp-mux"); } -void sdp_append_datachannel(Sdp *sdp) { - +void sdp_append_datachannel(Sdp* sdp) { sdp_append(sdp, "m=application 50712 UDP/DTLS/SCTP webrtc-datachannel"); sdp_append(sdp, "a=mid:datachannel"); sdp_append(sdp, "a=sctp-port:5000"); @@ -85,8 +78,7 @@ void sdp_append_datachannel(Sdp *sdp) { sdp_append(sdp, "a=max-message-size:262144"); } -void sdp_create(Sdp *sdp, int b_video, int b_audio, int b_datachannel) { - +void sdp_create(Sdp* sdp, int b_video, int b_audio, int b_datachannel) { char bundle[64]; sdp_append(sdp, "v=0"); sdp_append(sdp, "o=- 1495799811084970 1495799811084970 IN IP4 0.0.0.0"); @@ -114,4 +106,3 @@ void sdp_create(Sdp *sdp, int b_video, int b_audio, int b_datachannel) { sdp_append(sdp, bundle); } - diff --git a/src/sdp.h b/src/sdp.h index 802107a..ebebab8 100644 --- a/src/sdp.h +++ b/src/sdp.h @@ -11,25 +11,24 @@ #endif typedef struct Sdp { - char content[SDP_CONTENT_LENGTH]; } Sdp; -void sdp_append_h264(Sdp *sdp); +void sdp_append_h264(Sdp* sdp); -void sdp_append_pcma(Sdp *sdp); +void sdp_append_pcma(Sdp* sdp); -void sdp_append_pcmu(Sdp *sdp); +void sdp_append_pcmu(Sdp* sdp); -void sdp_append_opus(Sdp *sdp); +void sdp_append_opus(Sdp* sdp); -void sdp_append_datachannel(Sdp *sdp); +void sdp_append_datachannel(Sdp* sdp); -void sdp_create(Sdp *sdp, int b_video, int b_audio, int b_datachannel); +void sdp_create(Sdp* sdp, int b_video, int b_audio, int b_datachannel); -int sdp_append(Sdp *sdp, const char *format, ...); +int sdp_append(Sdp* sdp, const char* format, ...); -void sdp_reset(Sdp *sdp); +void sdp_reset(Sdp* sdp); -#endif // SDP_H_ +#endif // SDP_H_ diff --git a/src/socket.c b/src/socket.c index 5ce568a..ea59696 100644 --- a/src/socket.c +++ b/src/socket.c @@ -1,20 +1,19 @@ -#include -#include #include -#include -#include -#include -#include #include +#include #include -#include #include +#include +#include +#include +#include +#include +#include -#include "utils.h" #include "socket.h" +#include "utils.h" -int udp_socket_add_multicast_group(UdpSocket *udp_socket, Address *mcast_addr) { - +int udp_socket_add_multicast_group(UdpSocket* udp_socket, Address* mcast_addr) { int ret = 0; struct ip_mreq imreq = {0}; struct in_addr iaddr = {0}; @@ -36,11 +35,10 @@ int udp_socket_add_multicast_group(UdpSocket *udp_socket, Address *mcast_addr) { return 0; } -int udp_socket_open(UdpSocket *udp_socket, int family, int port) { - +int udp_socket_open(UdpSocket* udp_socket, int family, int port) { int ret; int reuse = 1; - struct sockaddr *sa; + struct sockaddr* sa; socklen_t sock_len; udp_socket->bind_addr.family = family; @@ -51,7 +49,7 @@ int udp_socket_open(UdpSocket *udp_socket, int family, int port) { udp_socket->bind_addr.sin6.sin6_port = htons(port); udp_socket->bind_addr.sin6.sin6_addr = in6addr_any; udp_socket->bind_addr.port = ntohs(udp_socket->bind_addr.sin6.sin6_port); - sa = (struct sockaddr *)&udp_socket->bind_addr.sin6; + sa = (struct sockaddr*)&udp_socket->bind_addr.sin6; sock_len = sizeof(struct sockaddr_in6); break; case AF_INET: @@ -60,7 +58,7 @@ int udp_socket_open(UdpSocket *udp_socket, int family, int port) { udp_socket->bind_addr.sin.sin_family = AF_INET; udp_socket->bind_addr.sin.sin_port = htons(port); udp_socket->bind_addr.sin.sin_addr.s_addr = htonl(INADDR_ANY); - sa = (struct sockaddr *)&udp_socket->bind_addr.sin; + sa = (struct sockaddr*)&udp_socket->bind_addr.sin; sock_len = sizeof(struct sockaddr_in); break; } @@ -100,21 +98,19 @@ int udp_socket_open(UdpSocket *udp_socket, int family, int port) { default: udp_socket->bind_addr.port = ntohs(udp_socket->bind_addr.sin.sin_port); break; - } + } return 0; } -void udp_socket_close(UdpSocket *udp_socket) { - +void udp_socket_close(UdpSocket* udp_socket) { if (udp_socket->fd > 0) { close(udp_socket->fd); } } -int udp_socket_sendto(UdpSocket *udp_socket, Address *addr, const uint8_t *buf, int len) { - - struct sockaddr *sa; +int udp_socket_sendto(UdpSocket* udp_socket, Address* addr, const uint8_t* buf, int len) { + struct sockaddr* sa; socklen_t sock_len; int ret = -1; @@ -126,13 +122,13 @@ int udp_socket_sendto(UdpSocket *udp_socket, Address *addr, const uint8_t *buf, switch (addr->family) { case AF_INET6: addr->sin6.sin6_family = AF_INET6; - sa = (struct sockaddr *)&addr->sin6; + sa = (struct sockaddr*)&addr->sin6; sock_len = sizeof(struct sockaddr_in6); break; case AF_INET: default: addr->sin.sin_family = AF_INET; - sa = (struct sockaddr *)&addr->sin; + sa = (struct sockaddr*)&addr->sin; sock_len = sizeof(struct sockaddr_in); break; } @@ -145,29 +141,28 @@ int udp_socket_sendto(UdpSocket *udp_socket, Address *addr, const uint8_t *buf, return ret; } -int udp_socket_recvfrom(UdpSocket *udp_socket, Address *addr, uint8_t *buf, int len) { - +int udp_socket_recvfrom(UdpSocket* udp_socket, Address* addr, uint8_t* buf, int len) { struct sockaddr_in6 sin6; struct sockaddr_in sin; - struct sockaddr *sa; + struct sockaddr* sa; socklen_t sock_len; int ret; if (udp_socket->fd < 0) { LOGE("recvfrom before socket init"); - return -1; + return -1; } switch (udp_socket->bind_addr.family) { case AF_INET6: sin6.sin6_family = AF_INET6; - sa = (struct sockaddr *)&sin6; + sa = (struct sockaddr*)&sin6; sock_len = sizeof(struct sockaddr_in6); break; case AF_INET: default: sin.sin_family = AF_INET; - sa = (struct sockaddr *)&sin; + sa = (struct sockaddr*)&sin; sock_len = sizeof(struct sockaddr_in); break; } @@ -183,21 +178,20 @@ int udp_socket_recvfrom(UdpSocket *udp_socket, Address *addr, uint8_t *buf, int addr->family = AF_INET6; addr->port = htons(addr->sin6.sin6_port); memcpy(&addr->sin6, &sin6, sizeof(struct sockaddr_in6)); - break; - case AF_INET: - default: + break; + case AF_INET: + default: addr->family = AF_INET; addr->port = htons(addr->sin.sin_port); memcpy(&addr->sin, &sin, sizeof(struct sockaddr_in)); - break; + break; } } return ret; } -int tcp_socket_open(TcpSocket *tcp_socket, int family) { - +int tcp_socket_open(TcpSocket* tcp_socket, int family) { tcp_socket->bind_addr.family = family; switch (family) { case AF_INET6: @@ -216,11 +210,10 @@ int tcp_socket_open(TcpSocket *tcp_socket, int family) { return 0; } -int tcp_socket_connect(TcpSocket *tcp_socket, Address *addr) { - +int tcp_socket_connect(TcpSocket* tcp_socket, Address* addr) { char addr_string[ADDRSTRLEN]; int ret; - struct sockaddr *sa; + struct sockaddr* sa; socklen_t sock_len; if (tcp_socket->fd < 0) { @@ -231,13 +224,13 @@ int tcp_socket_connect(TcpSocket *tcp_socket, Address *addr) { switch (addr->family) { case AF_INET6: addr->sin6.sin6_family = AF_INET6; - sa = (struct sockaddr *)&addr->sin6; + sa = (struct sockaddr*)&addr->sin6; sock_len = sizeof(struct sockaddr_in6); break; case AF_INET: default: addr->sin.sin_family = AF_INET; - sa = (struct sockaddr *)&addr->sin; + sa = (struct sockaddr*)&addr->sin; sock_len = sizeof(struct sockaddr_in); break; } @@ -253,21 +246,18 @@ int tcp_socket_connect(TcpSocket *tcp_socket, Address *addr) { return 0; } -void tcp_socket_close(TcpSocket *tcp_socket) { - +void tcp_socket_close(TcpSocket* tcp_socket) { if (tcp_socket->fd > 0) { close(tcp_socket->fd); } } -int tcp_socket_send(TcpSocket *tcp_socket, const uint8_t *buf, int len) { - +int tcp_socket_send(TcpSocket* tcp_socket, const uint8_t* buf, int len) { fd_set write_set; struct timeval tv; int ret = -1; if (tcp_socket->fd < 0) { - LOGE("sendto before socket init"); return -1; } @@ -279,13 +269,11 @@ int tcp_socket_send(TcpSocket *tcp_socket, const uint8_t *buf, int len) { tv.tv_usec = 500000; if ((ret = select(tcp_socket->fd + 1, NULL, &write_set, NULL, &tv)) < 0) { - LOGE("Failed to select: %s", strerror(errno)); return -1; } if (FD_ISSET(tcp_socket->fd, &write_set)) { - ret = send(tcp_socket->fd, buf, len, 0); if (ret < 0) { LOGE("Failed to send: %s", strerror(errno)); @@ -296,14 +284,12 @@ int tcp_socket_send(TcpSocket *tcp_socket, const uint8_t *buf, int len) { return ret; } -int tcp_socket_recv(TcpSocket *tcp_socket, uint8_t *buf, int len) { - +int tcp_socket_recv(TcpSocket* tcp_socket, uint8_t* buf, int len) { fd_set read_set; struct timeval tv; int ret; if (tcp_socket->fd < 0) { - LOGE("recvfrom before socket init"); return -1; } @@ -314,13 +300,11 @@ int tcp_socket_recv(TcpSocket *tcp_socket, uint8_t *buf, int len) { tv.tv_usec = 500000; if ((ret = select(tcp_socket->fd + 1, &read_set, NULL, NULL, &tv)) < 0) { - LOGE("Failed to select: %s", strerror(errno)); return -1; } if (FD_ISSET(tcp_socket->fd, &read_set)) { - ret = recv(tcp_socket->fd, buf, len, 0); if (ret < 0) { LOGE("Failed to recv: %s", strerror(errno)); diff --git a/src/socket.h b/src/socket.h index e87f5b3..2570373 100644 --- a/src/socket.h +++ b/src/socket.h @@ -13,26 +13,26 @@ typedef struct TcpSocket { Address bind_addr; } TcpSocket; -int udp_socket_open(UdpSocket *udp_socket, int family, int port); +int udp_socket_open(UdpSocket* udp_socket, int family, int port); -int udp_socket_bind(UdpSocket *udp_socket, int port); +int udp_socket_bind(UdpSocket* udp_socket, int port); -void udp_socket_close(UdpSocket *udp_socket); +void udp_socket_close(UdpSocket* udp_socket); -int udp_socket_sendto(UdpSocket *udp_socket, Address *bind_addr, const uint8_t *buf, int len); +int udp_socket_sendto(UdpSocket* udp_socket, Address* bind_addr, const uint8_t* buf, int len); -int udp_socket_recvfrom(UdpSocket *udp_sock, Address *bind_addr, uint8_t *buf, int len); +int udp_socket_recvfrom(UdpSocket* udp_sock, Address* bind_addr, uint8_t* buf, int len); -int udp_socket_add_multicast_group(UdpSocket *udp_socket, Address *mcast_addr); +int udp_socket_add_multicast_group(UdpSocket* udp_socket, Address* mcast_addr); -int tcp_socket_open(TcpSocket *tcp_socket, int family); +int tcp_socket_open(TcpSocket* tcp_socket, int family); -int tcp_socket_connect(TcpSocket *tcp_socket, Address *addr); +int tcp_socket_connect(TcpSocket* tcp_socket, Address* addr); -void tcp_socket_close(TcpSocket *tcp_socket); +void tcp_socket_close(TcpSocket* tcp_socket); -int tcp_socket_send(TcpSocket *tcp_socket, const uint8_t *buf, int len); +int tcp_socket_send(TcpSocket* tcp_socket, const uint8_t* buf, int len); -int tcp_socket_recv(TcpSocket *tcp_socket, uint8_t *buf, int len); +int tcp_socket_recv(TcpSocket* tcp_socket, uint8_t* buf, int len); -#endif // SOCKET_H_ +#endif // SOCKET_H_ diff --git a/src/ssl_transport.c b/src/ssl_transport.c index 6ae67a8..9a9dbe3 100644 --- a/src/ssl_transport.c +++ b/src/ssl_transport.c @@ -2,50 +2,48 @@ #include #include +#include "mbedtls/ctr_drbg.h" #include "mbedtls/debug.h" -#include "mbedtls/ssl.h" #include "mbedtls/entropy.h" -#include "mbedtls/ctr_drbg.h" +#include "mbedtls/ssl.h" -#include "utils.h" #include "config.h" #include "ports.h" #include "ssl_transport.h" +#include "utils.h" -static int ssl_transport_mbedtls_recv(void *ctx, unsigned char *buf, size_t len) { - +static int ssl_transport_mbedtls_recv(void* ctx, unsigned char* buf, size_t len) { return tcp_socket_recv((TcpSocket*)ctx, buf, len); } -static int ssl_transport_mbedlts_send(void *ctx, const uint8_t *buf, size_t len) { - +static int ssl_transport_mbedlts_send(void* ctx, const uint8_t* buf, size_t len) { return tcp_socket_send((TcpSocket*)ctx, buf, len); } -int ssl_transport_connect(NetworkContext_t *net_ctx, - const char *host, uint16_t port, const char *cacert) { - - const char *pers = "ssl_client"; +int ssl_transport_connect(NetworkContext_t* net_ctx, + const char* host, + uint16_t port, + const char* cacert) { + const char* pers = "ssl_client"; int ret; Address resolved_addr; mbedtls_ssl_init(&net_ctx->ssl); mbedtls_ssl_config_init(&net_ctx->conf); - //mbedtls_x509_crt_init(&net_ctx->cacert); + // mbedtls_x509_crt_init(&net_ctx->cacert); mbedtls_ctr_drbg_init(&net_ctx->ctr_drbg); mbedtls_entropy_init(&net_ctx->entropy); if ((ret = mbedtls_ctr_drbg_seed(&net_ctx->ctr_drbg, mbedtls_entropy_func, &net_ctx->entropy, - (const unsigned char *) pers, strlen(pers))) != 0) { + (const unsigned char*)pers, strlen(pers))) != 0) { return -1; } if ((ret = mbedtls_ssl_config_defaults(&net_ctx->conf, - MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { - - LOGE("ssl config error: -0x%x", (unsigned int) -ret); + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { + LOGE("ssl config error: -0x%x", (unsigned int)-ret); return -1; } @@ -62,12 +60,12 @@ int ssl_transport_connect(NetworkContext_t *net_ctx, mbedtls_ssl_conf_rng(&net_ctx->conf, mbedtls_ctr_drbg_random, &net_ctx->ctr_drbg); if ((ret = mbedtls_ssl_setup(&net_ctx->ssl, &net_ctx->conf)) != 0) { - LOGE("ssl setup error: -0x%x", (unsigned int) -ret); + LOGE("ssl setup error: -0x%x", (unsigned int)-ret); return -1; } if ((ret = mbedtls_ssl_set_hostname(&net_ctx->ssl, host)) != 0) { - LOGE("ssl set hostname error: -0x%x", (unsigned int) -ret); + LOGE("ssl set hostname error: -0x%x", (unsigned int)-ret); return -1; } @@ -80,13 +78,13 @@ int ssl_transport_connect(NetworkContext_t *net_ctx, } mbedtls_ssl_set_bio(&net_ctx->ssl, &net_ctx->tcp_socket, - ssl_transport_mbedlts_send, ssl_transport_mbedtls_recv, NULL); + ssl_transport_mbedlts_send, ssl_transport_mbedtls_recv, NULL); LOGI("start to handshake"); while ((ret = mbedtls_ssl_handshake(&net_ctx->ssl)) != 0) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - LOGE("ssl handshake error: -0x%x", (unsigned int) -ret); + LOGE("ssl handshake error: -0x%x", (unsigned int)-ret); } } @@ -95,10 +93,9 @@ int ssl_transport_connect(NetworkContext_t *net_ctx, return 0; } -void ssl_transport_disconnect(NetworkContext_t *net_ctx) { - +void ssl_transport_disconnect(NetworkContext_t* net_ctx) { mbedtls_ssl_config_free(&net_ctx->conf); - //mbedtls_x509_crt_free(&net_ctx->cacert); + // mbedtls_x509_crt_free(&net_ctx->cacert); mbedtls_ctr_drbg_free(&net_ctx->ctr_drbg); mbedtls_entropy_free(&net_ctx->entropy); mbedtls_ssl_free(&net_ctx->ssl); @@ -106,8 +103,7 @@ void ssl_transport_disconnect(NetworkContext_t *net_ctx) { tcp_socket_close(&net_ctx->tcp_socket); } -int ssl_transport_recv(NetworkContext_t *net_ctx, void *buf, size_t len) { - +int ssl_transport_recv(NetworkContext_t* net_ctx, void* buf, size_t len) { int ret; memset(buf, 0, len); ret = mbedtls_ssl_read(&net_ctx->ssl, buf, len); @@ -115,12 +111,10 @@ int ssl_transport_recv(NetworkContext_t *net_ctx, void *buf, size_t len) { return ret; } -int ssl_transport_send(NetworkContext_t *net_ctx, const void *buf, size_t len) { - +int ssl_transport_send(NetworkContext_t* net_ctx, const void* buf, size_t len) { int ret; while ((ret = mbedtls_ssl_write(&net_ctx->ssl, buf, len)) <= 0) { - if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { LOGE(""); } @@ -128,5 +122,3 @@ int ssl_transport_send(NetworkContext_t *net_ctx, const void *buf, size_t len) { return ret; } - - diff --git a/src/ssl_transport.h b/src/ssl_transport.h index fd1cbe5..95b8468 100644 --- a/src/ssl_transport.h +++ b/src/ssl_transport.h @@ -1,16 +1,15 @@ #ifndef SSL_TRANSPORT_H_ #define SSL_TRANSPORT_H_ -#include -#include -#include #include +#include +#include +#include #include "socket.h" #include "transport_interface.h" struct NetworkContext { - TcpSocket tcp_socket; mbedtls_ssl_context ssl; mbedtls_entropy_context entropy; @@ -19,14 +18,15 @@ struct NetworkContext { mbedtls_x509_crt cacert; }; -int ssl_transport_connect(NetworkContext_t *net_ctx, - const char *host, uint16_t port, const char *cacert); - -void ssl_transport_disconnect(NetworkContext_t *net_ctx); +int ssl_transport_connect(NetworkContext_t* net_ctx, + const char* host, + uint16_t port, + const char* cacert); -int ssl_transport_recv(NetworkContext_t *net_ctx, void *buf, size_t len); +void ssl_transport_disconnect(NetworkContext_t* net_ctx); -int ssl_transport_send(NetworkContext_t *net_ctx, const void *buf, size_t len); +int ssl_transport_recv(NetworkContext_t* net_ctx, void* buf, size_t len); -#endif // SSL_TRANSPORT_H_ +int ssl_transport_send(NetworkContext_t* net_ctx, const void* buf, size_t len); +#endif // SSL_TRANSPORT_H_ diff --git a/src/stun.c b/src/stun.c index aaa9421..d78264c 100644 --- a/src/stun.c +++ b/src/stun.c @@ -1,56 +1,54 @@ +#include #include #include #include -#include -#include #include +#include -#include "utils.h" #include "stun.h" +#include "utils.h" uint32_t CRC32_TABLE[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, - 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, - 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, - 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, - 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, - 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, - 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, - 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, - 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, - 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, - 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, - 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, - 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, - 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, - 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, - 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, - 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, - 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, - 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, - 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, - 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, - 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, - 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, - 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, - 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; - -void stun_msg_create(StunMessage *msg, uint16_t type) { - - StunHeader *header = (StunHeader *)msg->buf; + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, + 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, + 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, + 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, + 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, + 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, + 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, + 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, + 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, + 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, + 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, + 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, + 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, + 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, + 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, + 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, + 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, + 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, + 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, + 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, + 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, + 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, + 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, + 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, + 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, + 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, + 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, + 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, + 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, + 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, + 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; + +void stun_msg_create(StunMessage* msg, uint16_t type) { + StunHeader* header = (StunHeader*)msg->buf; header->type = htons(type); header->length = 0; header->magic_cookie = htonl(MAGIC_COOKIE); @@ -58,53 +56,49 @@ void stun_msg_create(StunMessage *msg, uint16_t type) { header->transaction_id[1] = htonl(0x90abcdef); header->transaction_id[2] = htonl(0x12345678); msg->size = sizeof(StunHeader); - } -void stun_set_mapped_address(char *value, uint8_t *mask, Address *addr) { - - uint8_t *family = (uint8_t *)(value + 1); - uint16_t *port = (uint16_t *)(value + 2); - uint8_t *ipv4 = (uint8_t *)(value + 4); +void stun_set_mapped_address(char* value, uint8_t* mask, Address* addr) { + uint8_t* family = (uint8_t*)(value + 1); + uint16_t* port = (uint16_t*)(value + 2); + uint8_t* ipv4 = (uint8_t*)(value + 4); *family = 0x01; *port = htons(addr->port); memcpy(ipv4, &addr->sin.sin_addr, 4); - //LOGD("XOR Mapped Address Family: 0x%02x", *family); - //LOGD("XOR Mapped Address Port: %d", *port); - //LOGD("XOR Mapped Address Address: %d.%d.%d.%d", ipv4[0], ipv4[1], ipv4[2], ipv4[3]); + // LOGD("XOR Mapped Address Family: 0x%02x", *family); + // LOGD("XOR Mapped Address Port: %d", *port); + // LOGD("XOR Mapped Address Address: %d.%d.%d.%d", ipv4[0], ipv4[1], ipv4[2], ipv4[3]); } -void stun_get_mapped_address(char *value, uint8_t *mask, Address *addr) { - +void stun_get_mapped_address(char* value, uint8_t* mask, Address* addr) { int i; char addr_string[ADDRSTRLEN]; - uint32_t *addr32 = (uint32_t *)&addr->sin.sin_addr; - uint16_t *addr16 = (uint16_t *)&addr->sin6.sin6_addr; + uint32_t* addr32 = (uint32_t*)&addr->sin.sin_addr; + uint16_t* addr16 = (uint16_t*)&addr->sin6.sin6_addr; uint8_t family = value[1]; if (family == 0x02) { addr_set_family(addr, AF_INET6); for (i = 0; i < 8; i++) { - addr16[i] = (*(uint16_t *)(value + 4 + 2*i) ^ *(uint16_t*)(mask + 2*i)); + addr16[i] = (*(uint16_t*)(value + 4 + 2 * i) ^ *(uint16_t*)(mask + 2 * i)); } } else if (family == 0x01) { addr_set_family(addr, AF_INET); - *addr32 = (*(uint32_t *)(value + 4) ^ *(uint32_t*)mask); + *addr32 = (*(uint32_t*)(value + 4) ^ *(uint32_t*)mask); } addr_to_string(addr, addr_string, sizeof(addr_string)); - addr_set_port(addr, ntohs(*(uint16_t *)(value + 2) ^ *(uint16_t*)mask)); + addr_set_port(addr, ntohs(*(uint16_t*)(value + 2) ^ *(uint16_t*)mask)); LOGD("XOR Mapped Address Family: 0x%02x", addr->family); LOGD("XOR Mapped Address Port: %d", addr->port); LOGD("XOR Mapped Address Address: %s", addr_string); } -void stun_parse_msg_buf(StunMessage *msg) { - - StunHeader *header = (StunHeader *)msg->buf; +void stun_parse_msg_buf(StunMessage* msg) { + StunHeader* header = (StunHeader*)msg->buf; int length = ntohs(header->length) + sizeof(StunHeader); @@ -131,11 +125,10 @@ void stun_parse_msg_buf(StunMessage *msg) { } while (pos < length) { - - StunAttribute *attr = (StunAttribute *)(msg->buf + pos); + StunAttribute* attr = (StunAttribute*)(msg->buf + pos); memset(mask, 0, sizeof(mask)); - //LOGD("Attribute Type: 0x%04x", ntohs(attr->type)); - //LOGD("Attribute Length: %d", ntohs(attr->length)); + // LOGD("Attribute Type: 0x%04x", ntohs(attr->type)); + // LOGD("Attribute Length: %d", ntohs(attr->length)); switch (ntohs(attr->type)) { case STUN_ATTR_TYPE_MAPPED_ADDRESS: @@ -144,7 +137,7 @@ void stun_parse_msg_buf(StunMessage *msg) { case STUN_ATTR_TYPE_USERNAME: memset(msg->username, 0, sizeof(msg->username)); memcpy(msg->username, attr->value, ntohs(attr->length)); - //LOGD("length = %d, Username %s", ntohs(attr->length), msg->username); + // LOGD("length = %d, Username %s", ntohs(attr->length), msg->username); break; case STUN_ATTR_TYPE_MESSAGE_INTEGRITY: memcpy(msg->message_integrity, attr->value, ntohs(attr->length)); @@ -152,7 +145,7 @@ void stun_parse_msg_buf(StunMessage *msg) { char message_integrity_hex[41]; for (int i = 0; i < 20; i++) { - sprintf(message_integrity_hex + 2*i, "%02x", (uint8_t)msg->message_integrity[i]); + sprintf(message_integrity_hex + 2 * i, "%02x", (uint8_t)msg->message_integrity[i]); } break; @@ -169,24 +162,24 @@ void stun_parse_msg_buf(StunMessage *msg) { LOGD("Nonce %s", msg->nonce); break; case STUN_ATTR_TYPE_XOR_RELAYED_ADDRESS: - *((uint32_t *)mask) = htonl(MAGIC_COOKIE); + *((uint32_t*)mask) = htonl(MAGIC_COOKIE); memcpy(mask + 4, header->transaction_id, sizeof(header->transaction_id)); LOGD("XOR Relayed Address"); stun_get_mapped_address(attr->value, mask, &msg->relayed_addr); break; case STUN_ATTR_TYPE_XOR_MAPPED_ADDRESS: - *((uint32_t *)mask) = htonl(MAGIC_COOKIE); + *((uint32_t*)mask) = htonl(MAGIC_COOKIE); memcpy(mask + 4, header->transaction_id, sizeof(header->transaction_id)); stun_get_mapped_address(attr->value, mask, &msg->mapped_addr); break; case STUN_ATTR_TYPE_PRIORITY: break; case STUN_ATTR_TYPE_USE_CANDIDATE: - //LOGD("Use Candidate"); + // LOGD("Use Candidate"); break; case STUN_ATTR_TYPE_FINGERPRINT: memcpy(&msg->fingerprint, attr->value, ntohs(attr->length)); - //LOGD("Fingerprint: 0x%.4x", msg->fingerprint); + // LOGD("Fingerprint: 0x%.4x", msg->fingerprint); break; case STUN_ATTR_TYPE_ICE_CONTROLLED: case STUN_ATTR_TYPE_ICE_CONTROLLING: @@ -198,37 +191,30 @@ void stun_parse_msg_buf(StunMessage *msg) { break; } - pos += 4*((ntohs(attr->length) + 3)/4) + sizeof(StunAttribute); + pos += 4 * ((ntohs(attr->length) + 3) / 4) + sizeof(StunAttribute); } - - } -void stun_parse_binding_response(char *buf, size_t len, Address *addr) { - +void stun_parse_binding_response(char* buf, size_t len, Address* addr) { int pos = 0; uint8_t mask[16]; while (pos < len) { + StunAttribute* attr = (StunAttribute*)(buf + pos); - StunAttribute *attr = (StunAttribute *)(buf + pos); - - //LOGD("Attribute Type: 0x%04x", ntohs(attr->type)); - //LOGD("Attribute Length: %d", ntohs(attr->length)); + // LOGD("Attribute Type: 0x%04x", ntohs(attr->type)); + // LOGD("Attribute Length: %d", ntohs(attr->length)); if (ntohs(attr->type) == STUN_ATTR_TYPE_MAPPED_ADDRESS) { - stun_get_mapped_address(attr->value, mask, addr); } else if (ntohs(attr->type) == STUN_ATTR_TYPE_XOR_MAPPED_ADDRESS) { - - *((uint32_t *)mask) = htonl(MAGIC_COOKIE); + *((uint32_t*)mask) = htonl(MAGIC_COOKIE); stun_get_mapped_address(attr->value, mask, addr); } else if (ntohs(attr->type) == STUN_ATTR_TYPE_USERNAME) { - char username[16]; memset(username, 0, sizeof(username)); @@ -236,8 +222,6 @@ void stun_parse_binding_response(char *buf, size_t len, Address *addr) { LOGD("Username %s", username); } else if (ntohs(attr->type) == STUN_ATTR_TYPE_MESSAGE_INTEGRITY) { - - char message_integrity[20]; memcpy(message_integrity, attr->value, ntohs(attr->length)); @@ -248,42 +232,36 @@ void stun_parse_binding_response(char *buf, size_t len, Address *addr) { printf("\n"); -// stun_calculate_fingerprint((char*)msg, sizeof(StunHeader) + header_length + 24, (uint32_t*)(msg->buf + header_length + 24 + sizeof(StunAttribute))); - + // stun_calculate_fingerprint((char*)msg, sizeof(StunHeader) + header_length + 24, (uint32_t*)(msg->buf + header_length + 24 + sizeof(StunAttribute))); LOGD("Message Integrity"); } else if (ntohs(attr->type) == STUN_ATTR_TYPE_FINGERPRINT) { - LOGD("Fingerprint"); } else { - LOGD("Unknown Attribute"); } - pos += 4*((ntohs(attr->length) + 3)/4) + sizeof(StunAttribute); + pos += 4 * ((ntohs(attr->length) + 3) / 4) + sizeof(StunAttribute); } } -void stun_calculate_fingerprint(char *buf, size_t len, uint32_t *fingerprint) { - +void stun_calculate_fingerprint(char* buf, size_t len, uint32_t* fingerprint) { uint32_t c = 0xFFFFFFFF; int i = 0; - - for (i = 0; i < len; ++i) { + for (i = 0; i < len; ++i) { c = CRC32_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >> 8); } - *fingerprint = htonl((c ^ 0xFFFFFFFF)^STUN_FINGERPRINT_XOR); + *fingerprint = htonl((c ^ 0xFFFFFFFF) ^ STUN_FINGERPRINT_XOR); } -int stun_msg_write_attr(StunMessage *msg, StunAttrType type, uint16_t length, char *value) { - - StunHeader *header = (StunHeader *)msg->buf; +int stun_msg_write_attr(StunMessage* msg, StunAttrType type, uint16_t length, char* value) { + StunHeader* header = (StunHeader*)msg->buf; - StunAttribute *stun_attr = (StunAttribute*)(msg->buf + msg->size); + StunAttribute* stun_attr = (StunAttribute*)(msg->buf + msg->size); stun_attr->type = htons(type); stun_attr->length = htons(length); @@ -295,7 +273,6 @@ int stun_msg_write_attr(StunMessage *msg, StunAttrType type, uint16_t length, ch msg->size += length + sizeof(StunAttribute); switch (type) { - case STUN_ATTR_TYPE_REALM: memcpy(msg->realm, value, length); break; @@ -312,11 +289,10 @@ int stun_msg_write_attr(StunMessage *msg, StunAttrType type, uint16_t length, ch return 0; } -int stun_msg_finish(StunMessage *msg, StunCredential credential, const char *password, size_t password_len) { +int stun_msg_finish(StunMessage* msg, StunCredential credential, const char* password, size_t password_len) { + StunHeader* header = (StunHeader*)msg->buf; + StunAttribute* stun_attr; - StunHeader *header = (StunHeader *)msg->buf; - StunAttribute *stun_attr; - uint16_t header_length = ntohs(header->length); char key[256]; char hash_key[17]; @@ -352,15 +328,14 @@ int stun_msg_finish(StunMessage *msg, StunCredential credential, const char *pas return 0; } -int stun_probe(uint8_t *buf, size_t size) { - - StunHeader *header; +int stun_probe(uint8_t* buf, size_t size) { + StunHeader* header; if (size < sizeof(StunHeader)) { LOGE("STUN message is too short."); return -1; } - header = (StunHeader *)buf; + header = (StunHeader*)buf; if (header->magic_cookie != htonl(MAGIC_COOKIE)) { return -1; } @@ -401,27 +376,26 @@ StunMsgType stun_is_stun_msg(uint8_t *buf, size_t size) { return 0; } #endif -int stun_msg_is_valid(uint8_t *buf, size_t size, char *password) { - +int stun_msg_is_valid(uint8_t* buf, size_t size, char* password) { StunMessage msg; memcpy(msg.buf, buf, size); - stun_parse_msg_buf(&msg); + stun_parse_msg_buf(&msg); - StunHeader *header = (StunHeader *)msg.buf; + StunHeader* header = (StunHeader*)msg.buf; // FINGERPRINT uint32_t fingerprint = 0; size_t length = size - 4 - sizeof(StunAttribute); stun_calculate_fingerprint((char*)msg.buf, length, &fingerprint); - //LOGD("Fingerprint: 0x%08x", fingerprint); + // LOGD("Fingerprint: 0x%08x", fingerprint); if (fingerprint != msg.fingerprint) { - //LOGE("Fingerprint does not match."); + // LOGE("Fingerprint does not match."); return -1; } else { - //LOGD("Fingerprint matches."); + // LOGD("Fingerprint matches."); } // MESSAGE-INTEGRITY @@ -431,18 +405,17 @@ int stun_msg_is_valid(uint8_t *buf, size_t size, char *password) { length = length - 20 - sizeof(StunAttribute); utils_get_hmac_sha1((char*)msg.buf, length, password, strlen(password), message_integrity); for (int i = 0; i < 20; i++) { - sprintf((char*)&message_integrity_hex[2*i], "%02x", (uint8_t)message_integrity[i]); + sprintf((char*)&message_integrity_hex[2 * i], "%02x", (uint8_t)message_integrity[i]); } - //LOGD("message_integrity: 0x%s", message_integrity_hex); + // LOGD("message_integrity: 0x%s", message_integrity_hex); if (memcmp(message_integrity, msg.message_integrity, 20) != 0) { - //LOGE("Message Integrity does not match."); + // LOGE("Message Integrity does not match."); return -1; } else { - //LOGD("Message Integrity matches."); + // LOGD("Message Integrity matches."); } return 0; } - diff --git a/src/stun.h b/src/stun.h index 9a36d17..e055094 100644 --- a/src/stun.h +++ b/src/stun.h @@ -16,9 +16,9 @@ typedef struct StunMessage StunMessage; #define STUN_ATTR_BUF_SIZE 256 #define MAGIC_COOKIE 0x2112A442 #define STUN_FINGERPRINT_XOR 0x5354554e - + typedef enum StunClass { - + STUN_CLASS_REQUEST = 0x0000, STUN_CLASS_INDICATION = 0x0010, STUN_CLASS_RESPONSE = 0x0100, @@ -63,22 +63,19 @@ typedef enum StunCredential { } StunCredential; struct StunHeader { - uint16_t type; uint16_t length; uint32_t magic_cookie; uint32_t transaction_id[3]; }; - -struct StunAttribute { +struct StunAttribute { uint16_t type; uint16_t length; char value[0]; }; struct StunMessage { - StunClass stunclass; StunMethod stunmethod; uint32_t fingerprint; @@ -90,29 +87,28 @@ struct StunMessage { Address relayed_addr; uint8_t buf[STUN_ATTR_BUF_SIZE]; size_t size; +}; -}; - -void stun_msg_create(StunMessage *msg, uint16_t type); +void stun_msg_create(StunMessage* msg, uint16_t type); -void stun_set_mapped_address(char *value, uint8_t *mask, Address *addr); +void stun_set_mapped_address(char* value, uint8_t* mask, Address* addr); -void stun_get_mapped_address(char *value, uint8_t *mask, Address *addr); +void stun_get_mapped_address(char* value, uint8_t* mask, Address* addr); -void stun_parse_binding_response(char *attr_buf, size_t len, Address *addr); +void stun_parse_binding_response(char* attr_buf, size_t len, Address* addr); -void stun_msg_parse(StunMessage *msg, uint8_t *buf, size_t len); +void stun_msg_parse(StunMessage* msg, uint8_t* buf, size_t len); -void stun_parse_msg_buf(StunMessage *msg); +void stun_parse_msg_buf(StunMessage* msg); -void stun_calculate_fingerprint(char *buf, size_t len, uint32_t *fingerprint); +void stun_calculate_fingerprint(char* buf, size_t len, uint32_t* fingerprint); -int stun_msg_write_attr(StunMessage *msg, StunAttrType type, uint16_t length, char *value); +int stun_msg_write_attr(StunMessage* msg, StunAttrType type, uint16_t length, char* value); -int stun_probe(uint8_t *buf, size_t size); +int stun_probe(uint8_t* buf, size_t size); -int stun_msg_is_valid(uint8_t *buf, size_t len, char *password); +int stun_msg_is_valid(uint8_t* buf, size_t len, char* password); -int stun_msg_finish(StunMessage *msg, StunCredential credential, const char *password, size_t password_len); +int stun_msg_finish(StunMessage* msg, StunCredential credential, const char* password, size_t password_len); -#endif // STUN_H_ +#endif // STUN_H_ diff --git a/src/utils.c b/src/utils.c index 16d5ad7..f4060b1 100644 --- a/src/utils.c +++ b/src/utils.c @@ -1,23 +1,22 @@ +#include +#include #include #include #include -#include -#include #include #include #include -#include "utils.h" #include "mbedtls/md.h" +#include "utils.h" -void utils_random_string(char *s, const int len) { - +void utils_random_string(char* s, const int len) { int i; static const char alphanum[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; + "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; srand(time(NULL)); @@ -28,26 +27,24 @@ void utils_random_string(char *s, const int len) { s[len] = '\0'; } -void utils_get_hmac_sha1(const char *input, size_t input_len, const char *key, size_t key_len, unsigned char *output) { - +void utils_get_hmac_sha1(const char* input, size_t input_len, const char* key, size_t key_len, unsigned char* output) { mbedtls_md_context_t ctx; mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1; mbedtls_md_init(&ctx); mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 1); - mbedtls_md_hmac_starts(&ctx, (const unsigned char *) key, key_len); - mbedtls_md_hmac_update(&ctx, (const unsigned char *) input, input_len); + mbedtls_md_hmac_starts(&ctx, (const unsigned char*)key, key_len); + mbedtls_md_hmac_update(&ctx, (const unsigned char*)input, input_len); mbedtls_md_hmac_finish(&ctx, output); mbedtls_md_free(&ctx); } -void utils_get_md5(const char *input, size_t input_len, unsigned char *output) { - +void utils_get_md5(const char* input, size_t input_len, unsigned char* output) { mbedtls_md_context_t ctx; mbedtls_md_type_t md_type = MBEDTLS_MD_MD5; mbedtls_md_init(&ctx); mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 1); mbedtls_md_starts(&ctx); - mbedtls_md_update(&ctx, (const unsigned char *) input, input_len); + mbedtls_md_update(&ctx, (const unsigned char*)input, input_len); mbedtls_md_finish(&ctx, output); mbedtls_md_free(&ctx); } diff --git a/src/utils.h b/src/utils.h index b0f6f0c..72040ae 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,9 +1,9 @@ #ifndef UTILS_H_ #define UTILS_H_ +#include #include #include -#include #include "config.h" #define LEVEL_ERROR 0x00 @@ -21,12 +21,12 @@ #endif #if LOG_REDIRECT -void peer_log(char *level_tag, const char *file_name, int line_number, const char *fmt, ...); +void peer_log(char* level_tag, const char* file_name, int line_number, const char* fmt, ...); #define LOG_PRINT(level_tag, fmt, ...) \ peer_log(level_tag, __FILE__, __LINE__, fmt, ##__VA_ARGS__) #else #define LOG_PRINT(level_tag, fmt, ...) \ - fprintf(stdout, "%s\t%s\t%d\t" fmt"\n", level_tag, __FILE__, __LINE__, ##__VA_ARGS__) + fprintf(stdout, "%s\t%s\t%d\t" fmt "\n", level_tag, __FILE__, __LINE__, ##__VA_ARGS__) #endif #if LOG_LEVEL >= LEVEL_DEBUG @@ -55,10 +55,10 @@ void peer_log(char *level_tag, const char *file_name, int line_number, const cha #define ALIGN32(num) ((num + 3) & ~3) -void utils_random_string(char *s, const int len); +void utils_random_string(char* s, const int len); -void utils_get_hmac_sha1(const char *input, size_t input_len, const char *key, size_t key_len, unsigned char *output); +void utils_get_hmac_sha1(const char* input, size_t input_len, const char* key, size_t key_len, unsigned char* output); -void utils_get_md5(const char *input, size_t input_len, unsigned char *output); +void utils_get_md5(const char* input, size_t input_len, unsigned char* output); -#endif // UTILS_H_ +#endif // UTILS_H_ diff --git a/tests/test_agent.c b/tests/test_agent.c index fb21bbd..0a36ce6 100644 --- a/tests/test_agent.c +++ b/tests/test_agent.c @@ -1,11 +1,10 @@ #include #include #include -#include "ports.h" #include "agent.h" +#include "ports.h" -void test_turn(Agent *agent, char *turnserver, char *username, char *credential) { - +void test_turn(Agent* agent, char* turnserver, char* username, char* credential) { char description[1024]; memset(&description, 0, sizeof(description)); agent_gather_candidate(agent, turnserver, username, credential); @@ -14,8 +13,7 @@ void test_turn(Agent *agent, char *turnserver, char *username, char *credential) printf("sdp: %s\n", description); } -void test_stun(Agent *agent, char *stunserver) { - +void test_stun(Agent* agent, char* stunserver) { char description[1024]; memset(&description, 0, sizeof(description)); agent_gather_candidate(agent, stunserver, NULL, NULL); @@ -24,8 +22,7 @@ void test_stun(Agent *agent, char *stunserver) { printf("sdp: %s\n", description); } -int main(int argc, char *argv[]) { - +int main(int argc, char* argv[]) { Agent agent; char stunserver[] = "stun:stun.l.google.com:19302"; @@ -43,4 +40,3 @@ int main(int argc, char *argv[]) { return 0; } - diff --git a/tests/test_dtls.c b/tests/test_dtls.c index 7248d83..635c0e8 100644 --- a/tests/test_dtls.c +++ b/tests/test_dtls.c @@ -5,7 +5,7 @@ #include "dtls_srtp.h" -void test_handshake(int argc, char *argv[]) { +void test_handshake(int argc, char* argv[]) { #if 0 DtlsSrtp dtls_srtp; UdpSocket udp_socket; @@ -86,17 +86,14 @@ void test_handshake(int argc, char *argv[]) { } void test_reset() { - DtlsSrtp dtls_srtp; dtls_srtp_init(&dtls_srtp, DTLS_SRTP_ROLE_CLIENT, NULL); dtls_srtp_deinit(&dtls_srtp); } -int main(int argc, char *argv[]) { - +int main(int argc, char* argv[]) { test_reset(); test_handshake(argc, argv); return 0; } - diff --git a/tests/test_peer_connection.c b/tests/test_peer_connection.c index b567508..05b36c4 100644 --- a/tests/test_peer_connection.c +++ b/tests/test_peer_connection.c @@ -1,14 +1,14 @@ +#include #include #include #include -#include #include "stun.h" #include "peer_connection.h" #define STUN_ADDR "142.250.21.127" #define STUN_PORT 19302 -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { #if 0 PeerConnection pc; @@ -67,4 +67,3 @@ int main(int argc, char *argv[]) { } #endif } - diff --git a/tests/test_rb.c b/tests/test_rb.c index 39c4c17..977d24a 100644 --- a/tests/test_rb.c +++ b/tests/test_rb.c @@ -1,5 +1,5 @@ -#include #include +#include #include #include "buffer.h" @@ -7,13 +7,11 @@ int g_data_length[8] = {100, 200, 300, 400, 500, 600, 700, 800}; int g_testing = 1; -int check_data(uint8_t *data, int length) { - +int check_data(uint8_t* data, int length) { int sum = 0; - int value = length*(length/100 + '0'); + int value = length * (length / 100 + '0'); for (int i = 0; i < length; i++) { - sum += data[i]; } @@ -22,21 +20,17 @@ int check_data(uint8_t *data, int length) { } void* test_thread(void* arg) { - - Buffer *rb = (Buffer*) arg; + Buffer* rb = (Buffer*)arg; int size = 0; - uint8_t *data = NULL; + uint8_t* data = NULL; while (g_testing) { - data = buffer_peak_head(rb, &size); if (data) { - if (check_data(data, size) == 0) { - printf("data error\n"); exit(1); } @@ -44,19 +38,15 @@ void* test_thread(void* arg) { buffer_pop_head(rb); } else { - usleep(1000); } - } return NULL; } - -int main(int argc, char *argv[]) { - - Buffer *rb = buffer_new(2000); +int main(int argc, char* argv[]) { + Buffer* rb = buffer_new(2000); pthread_t thread; pthread_create(&thread, NULL, test_thread, rb); @@ -64,17 +54,16 @@ int main(int argc, char *argv[]) { uint8_t data[MTU]; for (int i = 0; i < 8; i++) { - memset(data, i + '1', MTU); - buffer_push_tail(rb, data, g_data_length[i]); + buffer_push_tail(rb, data, g_data_length[i]); usleep(1000); } - usleep(100*1000); + usleep(100 * 1000); g_testing = 0; - pthread_join(thread, NULL); + pthread_join(thread, NULL); printf("test success\n"); return 0; diff --git a/tests/test_sdp.c b/tests/test_sdp.c index ae26405..d622fff 100644 --- a/tests/test_sdp.c +++ b/tests/test_sdp.c @@ -4,12 +4,11 @@ #include "agent.h" -void on_agent_state_changed(AgentState state, void *user_data) { - +void on_agent_state_changed(AgentState state, void* user_data) { printf("Agent state changed: %d\n", state); -} +} -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { #if 0 Agent agent; @@ -58,4 +57,3 @@ int main(int argc, char *argv[]) { #endif return 0; } - diff --git a/tests/test_stun.c b/tests/test_stun.c index 6575027..c77bd33 100644 --- a/tests/test_stun.c +++ b/tests/test_stun.c @@ -4,7 +4,5 @@ #include "stun.h" -int main(int argc, char *argv[]) { - +int main(int argc, char* argv[]) { } -