blob: ae5329e5936cd1af7e8a946c359dd0421b706ff9 [file] [log] [blame]
liubin281ac462023-07-19 14:22:54 +08001#include <stdlib.h>
2#include <unistd.h>
3#include <signal.h>
4#include <errno.h>
5#include <sys/epoll.h>
6#include <sys/socket.h>
7#include <netinet/in.h>
8#include <arpa/inet.h>
9#include <sys/un.h>
10#include <sys/time.h>
11#include <fcntl.h>
12#include <netdb.h>
b.liu9a8e82b2023-10-10 16:09:50 +080013
14#ifdef MBTK_POLARSSL_SUPPORT
liubin281ac462023-07-19 14:22:54 +080015#include <polarssl/net.h>
16#include <polarssl/ssl.h>
17#include <polarssl/entropy.h>
18#include <polarssl/ctr_drbg.h>
19#include <polarssl/certs.h>
20#include <polarssl/x509.h>
21#include <polarssl/error.h>
22#include <polarssl/debug.h>
23#include <polarssl/config.h>
b.liu9a8e82b2023-10-10 16:09:50 +080024#else
luojin8fbb3432023-10-18 09:47:46 +080025#include <resolv.h>
26#include <openssl/ssl.h>
27#include <openssl/err.h>
b.liu9a8e82b2023-10-10 16:09:50 +080028
luojin8fbb3432023-10-18 09:47:46 +080029//#define SSL_VERIFY_PEER 0x01
30//#define SSL_FILETYPE_PEM 0x01
31//#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02
32
33#define DFL_CA_FILE "/ca.crt"
34#define DFL_CRT_FILE "/client.crt"
35#define DFL_KEY_FILE "/client.key"
b.liu9a8e82b2023-10-10 16:09:50 +080036#endif
b.liu94baa7c2023-09-26 16:26:10 +080037#include <sys/ioctl.h>
liubin281ac462023-07-19 14:22:54 +080038
39#ifdef LOG_TAG
40#undef LOG_TAG
41#endif
42#define LOG_TAG "mbtk_sock"
43#include <mbtk_log.h>
44
45#include "mbtk_sock2.h"
46#include "mbtk_sock_internal.h"
47//#include "mbtk_openssl.h"
48
49#define SA struct sockaddr
50
51// Must define LOG_TAG in the first.
52//#include "mbtk_log.h"
53static int epoll_fd = -1;
54static int pipe_fds[2];
55static struct epoll_event epoll_events[20];
56static pthread_t sock_thread_id = -1;
57static bool sock_thread_running = FALSE;
58static mbtk_sock_s *mbtk_sock[MBTK_HANDLE_MAX_NUM] = {NULL};
59
60static int sock_find_first_free(const mbtk_sock_inter_info_s *inter_info)
61{
62 if(inter_info == NULL) {
63 LOGE("inter_info is NULL.");
64 return -1;
65 }
66
67 int index = 0;
68 //while((inter_info + index)->fd > 0) {
69 while(inter_info[index].fd > 0) {
70 index++;
71 }
72
73 if(index == MBTK_SOCK_MAX_NUM) {
74 LOGE("sock_infos too more.");
75 return -1;
76 }
77
78 return index;
79}
80
81static bool sock_info_check(int handle,mbtk_sock_inter_info_s *inter_info)
82{
83 if(inter_info == NULL || mbtk_sock[handle] == NULL) {
84 LOGE("internal_info is NULL.");
85 return FALSE;
86 }
87
88 int index = 0;
89 while(index < MBTK_SOCK_MAX_NUM) {
90 if(inter_info->fd ==
91 mbtk_sock[handle]->inter_infos[index].fd) {
92 return TRUE;
93 }
94 index++;
95 }
96
97 return FALSE;
98}
99
100static bool sock_is_close(int sockfd)
101{
102 char buff[32];
103 int recvBytes = recv(sockfd, buff, sizeof(buff), MSG_PEEK);
104
105 int err = errno;
106 //cout << "In close function, recv " << recvBytes << " bytes, err " << sockErr << endl;
107
108 if(recvBytes > 0) //Get data
109 return FALSE;
110
111 if((recvBytes == -1) && (err == EWOULDBLOCK)) //No receive data
112 return FALSE;
113
114 return TRUE;
115}
116
117static int sock_info_find_by_fd(int handle,int fd)
118{
119 int index = 0;
120 while(index < MBTK_SOCK_MAX_NUM) {
121 if(fd == mbtk_sock[handle]->inter_infos[index].fd) {
122 return index;
123 }
124 index++;
125 }
126
127 return -1;
128}
129
130static void* sock_thread_run(void *data)
131{
132 LOGD("socket thread is running...");
133 if(data != NULL)
134 LOGD("sock_thread_run has arg.");
135
136 int nready;
137 if (socketpair( AF_UNIX, SOCK_STREAM, 0, pipe_fds) < 0) {
138 LOGE("socketpair() error.");
139 return NULL;
140 } else {
141 struct epoll_event ev;
142 ev.data.fd = pipe_fds[1];
143 ev.events = EPOLLIN | EPOLLET;
144 epoll_ctl(epoll_fd,EPOLL_CTL_ADD,pipe_fds[1],&ev);
145 }
146
147 while(sock_thread_running) {
148 nready = epoll_wait(epoll_fd,epoll_events,20,-1);
149 int i;
150 for(i=0;i<nready;++i) {
b.liu94baa7c2023-09-26 16:26:10 +0800151 LOGV("fd[%d] event = %x",epoll_events[i].data.fd,epoll_events[i].events);
liubin281ac462023-07-19 14:22:54 +0800152 if(pipe_fds[1] == epoll_events[i].data.fd) {
153 LOGD("Get exist sig.");
154 sock_thread_running = FALSE;
155 break;
156 }
157
158 int handle = 0;
159 while(handle < MBTK_HANDLE_MAX_NUM) {
160 if(mbtk_sock[handle] != NULL) {
161 int index = sock_info_find_by_fd(handle,epoll_events[i].data.fd);
162 if(index >= 0 && mbtk_sock[handle]->init_info.sock_cb != NULL) {
163 mbtk_sock_inter_info_s *inter_info = &(mbtk_sock[handle]->inter_infos[index]);
b.liu8181e142023-09-26 10:31:10 +0800164 mbtk_sock_info *info = &(mbtk_sock[handle]->infos[index]);
liubin281ac462023-07-19 14:22:54 +0800165
166 //if(sock_is_close(epoll_events[i].data.fd)) {
167 // LOGE("Socket %d is closed.",epoll_events[i].data.fd);
168 // break;
169 //}
b.liu8181e142023-09-26 10:31:10 +0800170 mbtk_sock_cb_info_s sock_info;
171 sock_info.sock_fd = inter_info->fd;
172 sock_info.event = epoll_events[i].events;
173 sock_info.sock_type = info->type;
174 mbtk_sock[handle]->init_info.sock_cb(handle, &sock_info);
liubin281ac462023-07-19 14:22:54 +0800175
176 if(epoll_events[i].events & EPOLLERR){ // error[ UDP server can't use.]
177 LOGD("%d EPOLLERR.",epoll_events[i].data.fd);
178 }
179
180 if ((epoll_events[i].events & EPOLLIN)
181 && (epoll_events[i].events & EPOLLOUT)) {
182 LOGD("%d can read and write.",epoll_events[i].data.fd);
183 int error = -1;
184 int len = sizeof(int);
185 if(getsockopt(epoll_events[i].data.fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0){
186 LOGE("getsockopt fail.[%d]",errno);
187 }else{
188 LOGD("error = %d",error);
189 }
190 }
191
192 if (epoll_events[i].events & EPOLLOUT) { // Can write.
193 LOGD("%d can write.",epoll_events[i].data.fd);
194 }
195
196 if (epoll_events[i].events & EPOLLIN) { // Can read.
197 LOGD("%d can read.",epoll_events[i].data.fd);
198 }
199 }
200 }
201
202 handle++;
203 }
204 }
205 }
206
207 LOGD("socket thread exit.");
208 return ((void*)0);
209}
210
211static int sock_thread_start()
212{
213 sock_thread_running = TRUE;
214 if (0 != pthread_create(&sock_thread_id, NULL, sock_thread_run, NULL))
215 {
216 LOGE("error when create pthread,%d\n", errno);
217 return -1;
218 }
219
220 return 0;
221}
222
b.liueb040652023-09-25 18:50:56 +0800223void net_state_callback_func(mbtk_net_change_type_t type, const void *data)
224{
225 if(type == MBTK_NET_CHANGE_ADDR && data != NULL) {
226 int handle = 0;
227 const mbtk_net_addr_change_info_t *addr_info = (const mbtk_net_addr_change_info_t *)data;
228 while(handle < MBTK_HANDLE_MAX_NUM) {
229 if(mbtk_sock[handle] != NULL) {
230 if(mbtk_sock[handle]->init_info.net_cb != NULL) {
b.liu8181e142023-09-26 10:31:10 +0800231 mbtk_net_cb_info_s net_info;
232 net_info.state = (addr_info->type == MBTK_NET_ADDR_CHANGE_TYPE_ADD) ? 1 : 0;
233 net_info.addr = addr_info->addr;
234 net_info.if_name = addr_info->if_name;
235 mbtk_sock[handle]->init_info.net_cb(handle, &net_info);
b.liueb040652023-09-25 18:50:56 +0800236 }
237 }
238
239 handle++;
240 }
241 }
242}
243
liubin281ac462023-07-19 14:22:54 +0800244extern mbtk_sock_handle mbtk_sock_init(mbtk_init_info *info)
245{
246 mbtk_sock_handle handle = 0;
247 while(handle < MBTK_HANDLE_MAX_NUM) {
248 if(mbtk_sock[handle] == NULL)
249 break;
250
251 handle++;
252 }
253
254 if(handle == MBTK_HANDLE_MAX_NUM) {
255 LOGE("Socket handle is full.");
256 return -1;
257 }
258
259 mbtk_sock[handle] = (mbtk_sock_s*)malloc(sizeof(mbtk_sock_s));
260 memset(mbtk_sock[handle],0x0,sizeof(mbtk_sock_s));
261 if(info != NULL) {
262 mbtk_sock[handle]->init_info.net_type = info->net_type;
263 mbtk_sock[handle]->init_info.net_cb = info->net_cb;
264 mbtk_sock[handle]->init_info.sock_cb = info->sock_cb;
b.liueb040652023-09-25 18:50:56 +0800265 if(!str_empty(info->if_name)) {
266 memcpy(mbtk_sock[handle]->init_info.if_name, info->if_name, strlen(info->if_name));
267 }
liubin281ac462023-07-19 14:22:54 +0800268 } else {
269 mbtk_sock[handle]->init_info.net_type = MBTK_NET_LINUX;
270 mbtk_sock[handle]->init_info.net_cb = NULL;
271 mbtk_sock[handle]->init_info.sock_cb = NULL;
272 }
273
274 if(!sock_thread_running) {
275 epoll_fd = epoll_create(256);
276 if(sock_thread_start()) {
277 LOGE("Start thread fail.");
278 return -1;
279 }
280 }
281
b.liueb040652023-09-25 18:50:56 +0800282 if(mbtk_net_monitor_reg(str_empty(info->if_name) ? NULL : info->if_name, net_state_callback_func)) {
283 LOGE("mbtk_net_monitor_reg() fail.");
284 return -1;
285 }
286
liubin281ac462023-07-19 14:22:54 +0800287 return handle;
288}
289
b.liu9a8e82b2023-10-10 16:09:50 +0800290#ifdef MBTK_POLARSSL_SUPPORT
291static int mbtk_polarssl_open(int fd ,bool ingnore_cert,mbtk_sock_inter_info_s* inter_info)
liubin281ac462023-07-19 14:22:54 +0800292{
293 LOGE("8\n");
294 int ret = 0, len, tail_len, i, written, frags;
295 unsigned char buf[SSL_MAX_CONTENT_LEN + 1];
296 const char *pers = "ssl_client";
297 opt.server_name = DFL_SERVER_NAME;
298 opt.server_addr = DFL_SERVER_ADDR;
299 opt.server_port = DFL_SERVER_PORT;
300 opt.debug_level = DFL_DEBUG_LEVEL;
301 opt.nbio = DFL_NBIO;
302 opt.request_page = DFL_REQUEST_PAGE;
303 opt.request_size = DFL_REQUEST_SIZE;
304 opt.ca_file = DFL_CA_FILE;
305 opt.ca_path = DFL_CA_PATH;
306 opt.crt_file = DFL_CRT_FILE;
307 opt.key_file = DFL_KEY_FILE;
308 opt.psk = DFL_PSK;
309 opt.psk_identity = DFL_PSK_IDENTITY;
310 opt.force_ciphersuite[0]= DFL_FORCE_CIPHER;
311 opt.renegotiation = DFL_RENEGOTIATION;
312 opt.allow_legacy = DFL_ALLOW_LEGACY;
313 opt.renegotiate = DFL_RENEGOTIATE;
314 opt.exchanges = DFL_EXCHANGES;
315 opt.min_version = DFL_MIN_VERSION;
316 opt.max_version = DFL_MAX_VERSION;
317 opt.auth_mode = DFL_AUTH_MODE;
318 opt.mfl_code = DFL_MFL_CODE;
319 opt.trunc_hmac = DFL_TRUNC_HMAC;
320 opt.reconnect = DFL_RECONNECT;
321 opt.reco_delay = DFL_RECO_DELAY;
322 opt.tickets = DFL_TICKETS;
323 opt.alpn_string = DFL_ALPN_STRING;
324
325 entropy_context entropy;
326 ctr_drbg_context ctr_drbg;
327 ssl_context ssl;
328 ssl_session saved_session;
329 x509_crt cacert;
330 x509_crt clicert;
331 pk_context pkey;
332
333 memset( &ssl, 0, sizeof( ssl_context ) );
334 memset( &saved_session, 0, sizeof( ssl_session ) );
335 x509_crt_init( &cacert );
336 x509_crt_init( &clicert );
337 pk_init( &pkey );
338 LOGE("9\n");
339 /*
340 * 0. Initialize the RNG and the session data
341 */
342
343 entropy_init( &entropy );
344 if( ( ret = ctr_drbg_init( &ctr_drbg, entropy_func, &entropy,
345 (const unsigned char *) pers,
346 strlen( pers ) ) ) != 0 )
347 {
348 LOGE( " failed\n ! ctr_drbg_init returned -0x%x\n", -ret );
349 return -1;
350 }
351 if(!ingnore_cert)
352 {
353 LOGE("10\n");
354 /*
355 * 1.1. Load the trusted CA
356 */
357 //ret = x509_crt_parse(&cacert,ca1_cert,strlen(ca1_cert));
358 ret = x509_crt_parse_file( &cacert, opt.ca_path );
359 if( ret < 0 )
360 {
361 LOGE( " failed\n ! ca x509_crt_parse returned -0x%x\n\n", -ret );
362 return -1;
363 }
364
365 /*
366 * 1.2. Load own certificate and private key
367 *
368 * (can be skipped if client authentication is not required)
369 */
370
371 ret = x509_crt_parse_file( &clicert, opt.crt_file );
372 if( ret != 0 )
373 {
374 LOGE( " failed\n ! crt x509_crt_parse returned -0x%x\n\n", -ret );
375 return -1;
376 }
377
378 ret = pk_parse_keyfile( &pkey, opt.key_file, NULL);
379 if( ret != 0 )
380 {
381 LOGE( " failed\n ! key x509_crt_parse returned -0x%x\n\n", -ret );
382 return -1;
383 }
384 }
385 /*
386 * 2. Setup stuff
387 */
388 LOGE( " . Setting up the SSL/TLS structure..." );
389
390 if( ( ret = ssl_init( &ssl ) ) != 0 )
391 {
392 LOGE( " failed\n ! ssl_init returned -0x%x\n\n", -ret );
393 return -1;
394 }
395
396 ssl_set_endpoint( &ssl, SSL_IS_CLIENT );
397 if(ingnore_cert)
398 {
399 opt.auth_mode = SSL_VERIFY_OPTIONAL;
400 }
401 else
402 {
403 opt.auth_mode = SSL_VERIFY_REQUIRED;
404 }
405
406 ssl_set_authmode( &ssl, opt.auth_mode );
407
408 ssl_set_rng( &ssl, ctr_drbg_random, &ctr_drbg );
409
410 ssl_set_bio( &ssl, net_recv, &fd, net_send, &fd );
411
412 ssl_set_renegotiation( &ssl, opt.renegotiation );
413 ssl_legacy_renegotiation( &ssl, opt.allow_legacy );
414
415 ssl_set_ca_chain( &ssl, &cacert, NULL, NULL );
416 if(!ingnore_cert)
417 {
418 if( ( ret = ssl_set_own_cert( &ssl, &clicert, &pkey ) ) != 0 )
419 {
420 LOGE( " failed\n ! ssl_set_own_cert returned %d\n\n", ret );
421 return -1;
422 }
423 }
424 if( opt.min_version != -1 )
425 ssl_set_min_version( &ssl, SSL_MAJOR_VERSION_3, opt.min_version );
426 if( opt.max_version != -1 )
427 ssl_set_max_version( &ssl, SSL_MAJOR_VERSION_3, opt.max_version );
428 /*
429 * 3. Handshake
430 */
431 LOGE( " . Performing the SSL/TLS handshake..." );
432
433 while( ( ret = ssl_handshake( &ssl ) ) != 0 )
434 {
435 if( ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE )
436 {
437 LOGE( " failed\n ! ssl_handshake returned -0x%x\n", -ret );
438 if( ret == POLARSSL_ERR_X509_CERT_VERIFY_FAILED )
439 LOGE(
440 " Unable to verify the server's certificate. "
441 "Either it is invalid,\n"
442 " or you didn't set ca_file or ca_path "
443 "to an appropriate value.\n"
444 " Alternatively, you may want to use "
445 "auth_mode=optional for testing purposes.\n" );
446 LOGE( "\n" );
447 return -1;;
448 }
449 }
450
451 LOGE( " ok\n [ Protocol is %s ]\n [ Ciphersuite is %s ]\n",ssl_get_version( &ssl ), ssl_get_ciphersuite( &ssl ) );
452 printf( " ok\n [ Protocol is %s ]\n [ Ciphersuite is %s ]\n",ssl_get_version( &ssl ), ssl_get_ciphersuite( &ssl ) );
453
454 /*
455 * 4. Verify the server certificate
456 */
457 LOGE( " . Verifying peer X.509 certificate..." );
458
459 if( ( ret = ssl_get_verify_result( &ssl ) ) != 0 )
460 {
461 LOGE( " failed\n" );
462
463 if( ( ret & BADCERT_EXPIRED ) != 0 )
464 LOGE( " ! server certificate has expired\n" );
465
466 if( ( ret & BADCERT_REVOKED ) != 0 )
467 LOGE( " ! server certificate has been revoked\n" );
468
469 if( ( ret & BADCERT_CN_MISMATCH ) != 0 )
470 LOGE( " ! CN mismatch (expected CN=%s)\n", opt.server_name );
471
472 if( ( ret & BADCERT_NOT_TRUSTED ) != 0 )
473 LOGE( " ! self-signed or not signed by a trusted CA\n" );
474
475 }
476
477 if( ssl_get_peer_cert( &ssl ) != NULL )
478 {
479 LOGE( " . Peer certificate information ...\n" );
480 x509_crt_info( (char *) buf, sizeof( buf ) - 1, " ",
481 ssl_get_peer_cert( &ssl ) );
482 LOGE( "%s\n", buf );
483 }
484
485 inter_info->cacert = &cacert;
486 inter_info->clicert = &clicert;
487 inter_info->ctr_drbg = &ctr_drbg;
488 inter_info->entropy = &entropy;
489 inter_info->pkey = &pkey;
490 inter_info->saved_session = &saved_session;
491 inter_info->ssl = &ssl;
492
493 return 0;
494}
495
b.liu9a8e82b2023-10-10 16:09:50 +0800496static int mbtk_polarssl_close(mbtk_sock_inter_info_s *inter_info)
liubin281ac462023-07-19 14:22:54 +0800497{
498 if (inter_info == NULL)
499 {
500 return -1;
501 }
502
503 int ret = -1;
504 while( ( ret = ssl_close_notify( inter_info->ssl ) ) < 0 )
505 {
506 if( ret == POLARSSL_ERR_NET_CONN_RESET )
507 {
508 LOGE( " ok (already closed by peer)\n" );
509 ret = 0;
510 return -1;
511 }
512
513 if( ret != POLARSSL_ERR_NET_WANT_READ &&
514 ret != POLARSSL_ERR_NET_WANT_WRITE )
515 {
516 LOGE( " failed\n ! ssl_close_notify returned %d\n\n", ret );
517 return -1;
518 }
519 }
520
521 x509_crt_free( inter_info->clicert );
522 x509_crt_free( inter_info->cacert );
523 pk_free( inter_info->pkey );
524 ssl_session_free( inter_info->saved_session );
525 ssl_free( inter_info->ssl );
526 ctr_drbg_free( inter_info->ctr_drbg );
527 entropy_free( inter_info->entropy );
528 return 0;
529}
530
b.liu9a8e82b2023-10-10 16:09:50 +0800531static int mbtk_polarssl_write( ssl_context *ssl, const unsigned char *buf, size_t len )
532{
533 return ssl_write(ssl, buf, len);
534}
535
536static int mbtk_polarssl_read( ssl_context *ssl, unsigned char *buf, size_t len )
537{
538 return ssl_read(ssl, buf, len);
539}
540
541#else
542
luojin8fbb3432023-10-18 09:47:46 +0800543void ShowCerts(SSL * ssl)
544{
545 X509 *cert;
546 char *line;
b.liu9a8e82b2023-10-10 16:09:50 +0800547
luojin8fbb3432023-10-18 09:47:46 +0800548 cert = SSL_get_peer_certificate(ssl);
549 // SSL_get_verify_result()是重点,SSL_CTX_set_verify()只是配置启不启用并没有执行认证,调用该函数才会真证进行证书认证
550 // 如果验证不通过,那么程序抛出异常中止连接
551 if(SSL_get_verify_result(ssl) == X509_V_OK){
552 printf("证书验证通过\n");
553 }
554 if (cert != NULL) {
555 printf("数字证书信息:\n");
556 line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
557 printf("证书: %s\n", line);
558 free(line);
559 line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
560 printf("颁发者: %s\n", line);
561 free(line);
562 X509_free(cert);
563 } else
564 printf("无证书信息!\n");
565}
b.liu9a8e82b2023-10-10 16:09:50 +0800566
luojin8fbb3432023-10-18 09:47:46 +0800567static int mbtk_openssl_open(int fd ,bool ingnore_cert,mbtk_sock_inter_info_s* inter_info)
568{
569 SSL_CTX *ctx;
570 SSL *ssl;
b.liu9a8e82b2023-10-10 16:09:50 +0800571
luojin8fbb3432023-10-18 09:47:46 +0800572 /* SSL 库初始化,参看 ssl-server.c 代码 */
573 SSL_library_init();
574 OpenSSL_add_all_algorithms();
575 SSL_load_error_strings();
576 ctx = SSL_CTX_new(SSLv23_client_method());
577 if (ctx == NULL) {
578 ERR_print_errors_fp(stdout);
579 return -1;
580 }
581
582 if(!ingnore_cert)
583 {
584 // 双向验证
585 // SSL_VERIFY_PEER---要求对证书进行认证,没有证书也会放行
586 // SSL_VERIFY_FAIL_IF_NO_PEER_CERT---要求客户端需要提供证书,但验证发现单独使用没有证书也会放行
587 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
588 // 设置信任根证书
589 if (SSL_CTX_load_verify_locations(ctx, "/ca.crt",NULL)<=0){
590 ERR_print_errors_fp(stdout);
591 printf("fail SSL_CTX_load_verify_locations()\n");
592 return -1;
593 }
594
595 /* 载入用户的数字证书, 此证书用来发送给客户端。 证书里包含有公钥 */
596 if (SSL_CTX_use_certificate_file(ctx, DFL_CRT_FILE, SSL_FILETYPE_PEM) <= 0) {
597 ERR_print_errors_fp(stdout);
598 printf("fail SSL_CTX_use_certificate_file()\n");
599 return -1;
600 }
601 /* 载入用户私钥 */
602 if (SSL_CTX_use_PrivateKey_file(ctx, DFL_KEY_FILE, SSL_FILETYPE_PEM) <= 0) {
603 ERR_print_errors_fp(stdout);
604 printf("fail SSL_CTX_use_PrivateKey_file()\n");
605 return -1;
606 }
607 /* 检查用户私钥是否正确 */
608 if (!SSL_CTX_check_private_key(ctx)) {
609 ERR_print_errors_fp(stdout);
610 printf("fail SSL_CTX_check_private_key()\n");
611 return -1;
612 }
613
614 }
615
616 /* 基于 ctx 产生一个新的 SSL */
617 ssl = SSL_new(ctx);
618 SSL_set_fd(ssl, fd);
619 /* 建立 SSL 连接 */
620 if (SSL_connect(ssl) == -1)
621 ERR_print_errors_fp(stderr);
622 else {
623 printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
624 if(!ingnore_cert)
625 {
626 ShowCerts(ssl);
627 }
628 }
629
630 inter_info->ctx = &ctx;
631
632 inter_info->ssl = &ssl;
633
634 return 0;
635}
636
637static int mbtk_openssl_close(mbtk_sock_inter_info_s *inter_info)
638{
639 SSL_shutdown(inter_info->ssl);
640 SSL_free(inter_info->ssl);
641// close(sockfd);
642 SSL_CTX_free(inter_info->ctx);
643 return 0;
644}
645
646static int mbtk_openssl_write( SSL *ssl, const unsigned char *buf, size_t len )
647{
648 return SSL_write(ssl, buf, len);
649}
650
651static int mbtk_openssl_read( SSL *ssl, unsigned char *buf, size_t len )
652{
653 return SSL_read(ssl, buf, len);
654}
b.liu9a8e82b2023-10-10 16:09:50 +0800655
656#endif
657
liubin281ac462023-07-19 14:22:54 +0800658extern mbtk_sock_session mbtk_sock_open(mbtk_sock_handle handle,mbtk_sock_info *info,
659 unsigned int timeout,
660 int *mbtk_errno)
661{
662 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
663 || mbtk_sock[handle] == NULL) {
664 LOGE("Socket not inited.");
665 return -1;
666 }
667
668 *mbtk_errno = MBTK_SOCK_ERROR;
669 if(info == NULL) {
670 LOGE("mbtk_sock_info not be NULL.");
671 return -1;
672 }
673
674 int index_free = sock_find_first_free(mbtk_sock[handle]->inter_infos);
675 if(index_free < 0) {
676 LOGE("sock_find_first_free() fail.");
677 return -1;
678 }
679
680 memcpy(&(mbtk_sock[handle]->infos[index_free]),info,sizeof(mbtk_sock_info));
681 if(info->type == MBTK_SOCK_UDP) { // UDP
682 if((mbtk_sock[handle]->inter_infos[index_free].fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){
683 LOGE("socket() fail.[%d]",errno);
684 goto result_fail;
685 }
686 } else { // TCP
687 if((mbtk_sock[handle]->inter_infos[index_free].fd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
688 LOGE("socket() fail.[%d]",errno);
689 goto result_fail;
690 }
691 }
692 // Set O_NONBLOCK
693 int flags = fcntl(mbtk_sock[handle]->inter_infos[index_free].fd, F_GETFL, 0);
694 if (flags < 0) {
695 LOGE("Get flags error:%s\n", strerror(errno));
696 goto result_fail_with_close;
697 }
698 flags |= O_NONBLOCK;
699 if (fcntl(mbtk_sock[handle]->inter_infos[index_free].fd, F_SETFL, flags) < 0) {
700 LOGE("Set flags error:%s\n", strerror(errno));
701 goto result_fail_with_close;
702 }
703
704 // Connect
705 LOGD("Start conn:%s:%d",info->address,info->port);
706 if(strlen(info->address) > 0 && info->port > 0) {
b.liueb040652023-09-25 18:50:56 +0800707 if(strlen(info->local_address) > 0 || info->local_port > 0) {
708 // 指定本地IP和端口,不指定内核会自动指定(一般不指定)
709 struct sockaddr_in loc_addr;
710 memset(&loc_addr, 0, sizeof(struct sockaddr_in));
711 loc_addr.sin_family = AF_INET;
712
713 // 指定IP
714 if(strlen(info->local_address) > 0) {
715 if(inet_pton(AF_INET, info->local_address, &loc_addr.sin_addr) < 0) {
716 LOGE("inet_pton() error:%d", errno);
717 goto result_fail_with_close;
718 }
719 }
720
721 if(info->local_port > 0) {
722 loc_addr.sin_port = htons(info->local_port);
723 }
724 if(bind(mbtk_sock[handle]->inter_infos[index_free].fd, (struct sockaddr *)&loc_addr, sizeof(loc_addr)) < 0) {
725 LOGE("bind() error:%d", errno);
726 if(errno == EADDRINUSE) { // 地址已在使用
727 LOGE("EADDRINUSE : Local port already occupied.");
728 }
729 goto result_fail_with_close;
730 } else {
731 LOGD("Bind ip/port success.");
732 }
733 }
734
liubin281ac462023-07-19 14:22:54 +0800735 struct sockaddr_in servaddr;
736 bzero(&servaddr, sizeof(servaddr));
737 servaddr.sin_family = AF_INET;
738 servaddr.sin_port = htons(info->port);
739
740 struct hostent *he = gethostbyname(info->address);
741 if (he == NULL){
742 LOGE("gethostbyname() fail.[%d]",errno);
743 goto result_fail_with_close;
744 } else {
745 LOGD("Ip : %s",he->h_addr_list[0]);
746 }
747 memcpy(&servaddr.sin_addr, he->h_addr_list[0], sizeof(struct in_addr));
748
749 if(connect(mbtk_sock[handle]->inter_infos[index_free].fd, (SA *) &servaddr, sizeof(servaddr)) < 0){
750 if(EINPROGRESS != errno){
751 LOGE("connect() fail.[%d]",errno);
752 goto result_fail_with_close;
753 }
754 }
755
756 fd_set rset, wset;
757 FD_ZERO(&rset);
758 FD_ZERO(&wset);
759 FD_SET(mbtk_sock[handle]->inter_infos[index_free].fd, &rset);
760 FD_SET(mbtk_sock[handle]->inter_infos[index_free].fd, &wset);
761 struct timeval time_out;
762 time_out.tv_sec = timeout/1000;
763 time_out.tv_usec = timeout%1000*1000;
764 int nready = select(mbtk_sock[handle]->inter_infos[index_free].fd + 1,
765 &rset, &wset, NULL, &time_out);
766 LOGD("nready = %d",nready);
767 if(nready == 0){// Timeout
768 LOGE("Timeout.");
769 printf("Timeout.\n");
770 goto result_fail_with_close;
771 }else{
772 if (FD_ISSET(mbtk_sock[handle]->inter_infos[index_free].fd, &rset)
773 && FD_ISSET(mbtk_sock[handle]->inter_infos[index_free].fd, &wset)) {
774 int error = -1;
775 int len = sizeof(int);
776 LOGE("Can read and write.");
777 if(getsockopt(mbtk_sock[handle]->inter_infos[index_free].fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0){
778 LOGE("getsockopt fail.[%d]",errno);
779 goto result_fail_with_close;
780 }else{
781 LOGE("error = %d",error);
782 if(error != 0){ // Fail
783 goto result_fail_with_close;
784 }
785 }
786 }else if(FD_ISSET(mbtk_sock[handle]->inter_infos[index_free].fd, &wset)){
787 LOGI("Can write.");
788 printf("Can write.\n");
789 }else{
790 LOGE("Can read(Impossible).");
791 goto result_fail_with_close;
792 }
793 }
794 } else {
795 LOGE("Can not conn.");
796 goto result_fail_with_close;
797 }
798
799 if(mbtk_sock[handle]->init_info.sock_cb) {
800 struct epoll_event ev;
801 ev.data.fd = mbtk_sock[handle]->inter_infos[index_free].fd;
802 ev.events = EPOLLIN | EPOLLET;
803 epoll_ctl(epoll_fd,EPOLL_CTL_ADD,mbtk_sock[handle]->inter_infos[index_free].fd,&ev);
804 }
805#if 1
806 if(info->ftp_ssl_support)
807 {
808 if(info->is_support_ssl){
809 mbtk_sock[handle]->infos[index_free].is_support_ssl = 0;
810 unsigned char mbtk_ftp_ssl_read_buf_s[256];
811 int err_rw;
812 memset(mbtk_ftp_ssl_read_buf_s,0,sizeof(mbtk_ftp_ssl_read_buf_s));
813 mbtk_sock_read(handle,mbtk_sock[handle]->inter_infos[index_free].fd,
814 mbtk_ftp_ssl_read_buf_s,
815 sizeof(mbtk_ftp_ssl_read_buf_s),
816 60000,
817 &err_rw);
818 printf("\nmbtk_sock_read:\n%s\n",mbtk_ftp_ssl_read_buf_s);
819
820 char cmd_buff[50];
821 int len=0,code;
822 memset(cmd_buff,0,sizeof(cmd_buff));
823
824 len = snprintf(cmd_buff, 50, "AUTH TLS\r\n");
825 cmd_buff[len] = '\0';
826 //printf("\n cmd_buff = %s\n", cmd_buff);
827
828 mbtk_sock_write(handle,mbtk_sock[handle]->inter_infos[index_free].fd,
829 cmd_buff,
830 strlen(cmd_buff),
831 60000,
832 &err_rw);
833
834 memset(mbtk_ftp_ssl_read_buf_s,0,sizeof(mbtk_ftp_ssl_read_buf_s));
835 mbtk_sock_read(handle,mbtk_sock[handle]->inter_infos[index_free].fd,
836 mbtk_ftp_ssl_read_buf_s,
837 sizeof(mbtk_ftp_ssl_read_buf_s),
838 60000,
839 &err_rw);
840 printf("\nmbtk_sock_read:\n%s\n",mbtk_ftp_ssl_read_buf_s);
b.liueb040652023-09-25 18:50:56 +0800841
liubin281ac462023-07-19 14:22:54 +0800842 mbtk_sock[handle]->infos[index_free].is_support_ssl=1;
843 }else{
844 mbtk_sock[handle]->infos[index_free].is_support_ssl=1;
845 }
846 }
847#endif
848 if(info->is_support_ssl){
b.liu9a8e82b2023-10-10 16:09:50 +0800849#ifdef MBTK_POLARSSL_SUPPORT
850 if(mbtk_polarssl_open(mbtk_sock[handle]->inter_infos[index_free].fd,info->ingnore_cert,&mbtk_sock[handle]->inter_infos[index_free]) == -1){
liubin281ac462023-07-19 14:22:54 +0800851 LOGE("mbtk_openssl_init fail");
852 goto result_fail_with_close;
853 }
b.liu9a8e82b2023-10-10 16:09:50 +0800854#else
luojin8fbb3432023-10-18 09:47:46 +0800855 if(mbtk_openssl_open(mbtk_sock[handle]->inter_infos[index_free].fd,info->ingnore_cert,&mbtk_sock[handle]->inter_infos[index_free]) == -1){
856 LOGE("mbtk_openssl_init fail");
857 goto result_fail_with_close;
858 }
859
liubin281ac462023-07-19 14:22:54 +0800860
b.liu9a8e82b2023-10-10 16:09:50 +0800861#endif
liubin281ac462023-07-19 14:22:54 +0800862 }
863
864 *mbtk_errno = MBTK_SOCK_SUCCESS;
865
866 mbtk_sock[handle]->sock_num++;
867 return mbtk_sock[handle]->inter_infos[index_free].fd;
868result_fail_with_close:
869 close(mbtk_sock[handle]->inter_infos[index_free].fd);
870 mbtk_sock[handle]->inter_infos[index_free].fd = -1;
871result_fail:
872 memset(&(mbtk_sock[handle]->inter_infos[index_free]),0x0,sizeof(mbtk_sock_inter_info_s));
873 memset(&(mbtk_sock[handle]->infos[index_free]),0x0,sizeof(mbtk_sock_info));
874 LOGE("mbtk_sock_open() end:fail");
875 return -1;
876}
877extern int mbtk_ssl_init_func(mbtk_sock_handle handle ,bool ingnore_cert,mbtk_sock_session fd)
b.liueb040652023-09-25 18:50:56 +0800878{
liubin281ac462023-07-19 14:22:54 +0800879 int i=0;
880 int index_free=0;
881
882 for (i=0;i<10;i++)
883 {
884 if(mbtk_sock[handle]->inter_infos[i].fd == fd)
885 {
886 index_free = i;
887 break;
888 }
889 }
b.liu9a8e82b2023-10-10 16:09:50 +0800890#ifdef MBTK_POLARSSL_SUPPORT
891 return mbtk_polarssl_open(mbtk_sock[handle]->inter_infos[index_free].fd,ingnore_cert,&mbtk_sock[handle]->inter_infos[index_free]);
892#else
luojin8fbb3432023-10-18 09:47:46 +0800893 return mbtk_openssl_open(mbtk_sock[handle]->inter_infos[index_free].fd,ingnore_cert,&mbtk_sock[handle]->inter_infos[index_free]);
b.liu9a8e82b2023-10-10 16:09:50 +0800894#endif
liubin281ac462023-07-19 14:22:54 +0800895}
896extern int mbtk_ssl_close_func(mbtk_sock_handle handle ,bool ingnore_cert,mbtk_sock_session fd)
b.liueb040652023-09-25 18:50:56 +0800897{
liubin281ac462023-07-19 14:22:54 +0800898 int i=0;
899 int index_free=0;
900
901 for (i=0;i<10;i++)
902 {
903 if(mbtk_sock[handle]->inter_infos[i].fd == fd)
904 {
905 index_free = i;
906 break;
907 }
908 }
b.liu9a8e82b2023-10-10 16:09:50 +0800909
910#ifdef MBTK_POLARSSL_SUPPORT
liubin281ac462023-07-19 14:22:54 +0800911 if(mbtk_sock[handle]->inter_infos[index_free].ssl!=NULL);
912 printf("\nmbtk_sock[handle]->inter_infos[index_free].ssl not empty\n");
b.liu9a8e82b2023-10-10 16:09:50 +0800913 return mbtk_polarssl_close(&mbtk_sock[handle]->inter_infos[index_free]);
914#else
luojin8fbb3432023-10-18 09:47:46 +0800915 if(mbtk_sock[handle]->inter_infos[index_free].ssl!=NULL);
916 printf("\nmbtk_sock[handle]->inter_infos[index_free].ssl not empty\n");
917 return mbtk_openssl_close(&mbtk_sock[handle]->inter_infos[index_free]);
b.liu9a8e82b2023-10-10 16:09:50 +0800918#endif
liubin281ac462023-07-19 14:22:54 +0800919}
920
921extern int mbtk_sock_write(mbtk_sock_handle handle,mbtk_sock_session session,
922 void *buffer,
923 unsigned int buf_len,
924 unsigned int timeout,
925 int *mbtk_errno)
926{
927 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
928 || session < 0 || mbtk_sock[handle] == NULL) {
929 LOGE("Socket not inited.");
930 return -1;
931 }
932
933 *mbtk_errno = MBTK_SOCK_ERROR;
934 if(buffer == NULL) {
935 LOGE("mbtk_sock_write() args error.");
936 return -1;
937 }
938
939 mbtk_sock_inter_info_s *inter_info = NULL;
940 int index = 0;
941 while(index < MBTK_SOCK_MAX_NUM) {
942 if(session ==
943 mbtk_sock[handle]->inter_infos[index].fd) {
944 inter_info = &(mbtk_sock[handle]->inter_infos[index]);
945 break;
946 }
947 index++;
948 }
949
950 if(!sock_info_check(handle,inter_info)) {
951 LOGE("sock_info_check() fail.");
952 return -1;
953 }
954
955 index = sock_info_find_by_fd(handle,inter_info->fd);
956 if(index < 0) {
957 LOGE("No such socket in session list.");
958 return -1;
959 }
960
961 int len = 0;
962 unsigned int count = 0;
963 if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_TCP) {
964 while(count < buf_len){
b.liu9a8e82b2023-10-10 16:09:50 +0800965 if(mbtk_sock[handle]->infos[index].is_support_ssl) {
966#ifdef MBTK_POLARSSL_SUPPORT
967 len = mbtk_polarssl_write(inter_info->ssl,(char*)buffer + count,buf_len - count);
968#else
luojin8fbb3432023-10-18 09:47:46 +0800969 len = mbtk_openssl_write(inter_info->ssl,(char*)buffer + count,buf_len - count);
b.liu9a8e82b2023-10-10 16:09:50 +0800970
971#endif
972 } else
liubin281ac462023-07-19 14:22:54 +0800973 len = write(inter_info->fd,(char*)buffer + count,buf_len - count);
974 if(len < 0){
975 if(errno == EWOULDBLOCK){
976 usleep(50000);
977 continue;
978 } else {
979 LOGE("write error.[%d]",errno);
980 if(count <= 0)
981 count = -1;
982 break;
983 }
984 } else if(len == 0) {
985 LOGE("write error(len == 0).[%d]",errno);
986 } else {
987 count += len;
988 }
989 }
990 } else if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_UDP){
991 // Start send data
992 while(count < buf_len){
993 len = sendto(inter_info->fd,(char*)buffer + count,buf_len - count,0,NULL,0);
994 if(len < 0){
995 if(errno == EWOULDBLOCK){
996 usleep(50000);
997 continue;
998 } else {
999 LOGE("sendto error.[%d]",errno);
1000 if(ECONNREFUSED == errno) { // Disconnected.
1001 LOGD("Socket Disconnected.");
1002 }
1003 break;
1004 }
1005 } else if(len == 0) {
1006 LOGD("write error(len == 0).[%d]",errno);
1007 } else {
1008 count += len;
1009 }
1010 }
1011 } else {
1012 LOGE("Socket type error.");
1013 return -1;
1014 }
1015
1016 if(count == buf_len){
1017 LOGD("Write data[%d/%d] success.",count,buf_len);
1018 } else { // Open session fail
1019 LOGD("Write data[%d/%d] fail.",count,buf_len);
1020 }
1021
1022 *mbtk_errno = MBTK_SOCK_SUCCESS;
1023 return count;
1024}
1025
1026extern int mbtk_sock_read(mbtk_sock_handle handle,mbtk_sock_session session,
1027 void *buffer,
1028 unsigned int buf_len,
1029 unsigned int timeout,
1030 int *mbtk_errno)
1031{
1032 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
1033 || session < 0 || mbtk_sock[handle] == NULL) {
1034 LOGE("Socket not inited.");
1035 return -1;
1036 }
1037
1038 *mbtk_errno = MBTK_SOCK_ERROR;
1039 if(buffer == NULL) {
1040 LOGE("mbtk_sock_write() args error.");
1041 return -1;
1042 }
1043
1044 mbtk_sock_inter_info_s *inter_info = NULL;
1045 int index = 0;
1046 while(index < MBTK_SOCK_MAX_NUM) {
1047 if(session ==
1048 mbtk_sock[handle]->inter_infos[index].fd) {
1049 inter_info = &(mbtk_sock[handle]->inter_infos[index]);
1050 break;
1051 }
1052 index++;
1053 }
1054
1055 if(!sock_info_check(handle,inter_info)) {
1056 LOGE("sock_info_check() fail.");
1057 return -1;
1058 }
1059
1060 index = sock_info_find_by_fd(handle,inter_info->fd);
1061 if(index < 0) {
1062 LOGE("No such socket in session list.");
1063 return -1;
1064 }
1065
1066 unsigned int count = 0;
1067 if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_TCP) {
1068 int len = 0;
1069 int try_count = 0;
1070 int times = timeout / 50;
1071 memset(buffer,0x0,buf_len);
1072 while(count < buf_len){
1073 try_count++;
b.liu9a8e82b2023-10-10 16:09:50 +08001074 if(mbtk_sock[handle]->infos[index].is_support_ssl) {
1075#ifdef MBTK_POLARSSL_SUPPORT
1076 len = mbtk_polarssl_read(inter_info->ssl,(char*)buffer + count,buf_len - count);
1077#else
luojin8fbb3432023-10-18 09:47:46 +08001078 len = mbtk_openssl_read(inter_info->ssl,(char*)buffer + count,buf_len - count);
b.liu9a8e82b2023-10-10 16:09:50 +08001079
1080#endif
1081 } else
liubin281ac462023-07-19 14:22:54 +08001082 len = read(inter_info->fd,(char*)buffer + count,buf_len - count);
1083 if(len < 0){
1084 if(errno == EWOULDBLOCK){
1085 if(count > 0) // Read data
1086 break; // Read data end.
1087
1088 if(try_count >= times){ // Timeout
1089 count = -1;
1090 if(times != 0) {
1091 *mbtk_errno = MBTK_SOCK_ETIMEOUT;
1092 }
1093 LOGE("Not read enough data,return.[%d/%d]",count,buf_len);
1094 break;
1095 } else {
1096 usleep(50000);
1097 continue;
1098 }
1099 } else {
1100 LOGE("read error.[%d]",errno);
1101 if(count <= 0)
1102 count = -1;
1103 break;
1104 }
1105 } else if(len == 0) {
1106 LOGE("read error(len == 0).[%d]",errno);
1107 if(errno == EINPROGRESS) {
1108 if(close(inter_info->fd) == 0) {// Success
1109 LOGD("Socket disconnected.Close it.");
1110 }
1111 if(count <= 0)
1112 count = -1;
1113 } else {
1114 if(count <= 0)
1115 count = 0;
1116 }
1117 break;
1118 } else {
1119 count += len;
1120 }
1121 }
1122 } else if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_UDP) {
1123 // Start recv data
1124 struct sockaddr_in seraddr;
1125 socklen_t seraddr_len;
1126 int try_count = 0;
1127 int times = timeout / 50;
1128 int len = 0;
1129 memset(buffer,0x0,buf_len);
1130 while(TRUE){
1131 try_count++;
1132 seraddr_len = sizeof(struct sockaddr_in);
1133 len = recvfrom(inter_info->fd,buffer,buf_len,0,&seraddr,&seraddr_len);
1134 if(len < 0){
1135 if(errno == EWOULDBLOCK){// No data can read.
1136 if(count > 0) // Read data
1137 break; // Read data end.
1138
1139 if(try_count >= times){ // Timeout
1140 if(times == 0) {
1141 LOGE("Can not read.");
1142 } else {
1143 LOGE("Timeout");
1144 *mbtk_errno = MBTK_SOCK_ETIMEOUT;
1145 }
1146 count = -1;
1147 LOGE("Not read enough data,return.[%d/%d]",count,buf_len);
1148 break;
1149 } else {
1150 usleep(50000);
1151 continue;
1152 }
1153 } else {
1154 LOGE("recvfrom error.[%d]",errno);
1155 if(count <= 0)
1156 count = -1;
1157 break;
1158 }
1159 } else if(len == 0) {
1160 LOGE("write error(len == 0).[%d]",errno);
1161 if(count <= 0)
1162 count = 0;
1163 break;
1164 } else {
1165 count += len;
1166 }
1167 }
1168 } else {
1169 LOGE("Socket type error.");
1170 return -1;
1171 }
1172
1173// if(count == buf_len){
1174// LOGD("Read data[%d/%d] success.",count,buf_len);
1175// } else { // Open session fail
1176// LOGD("Read data[%d/%d] fail.",count,buf_len);
1177// }
1178
1179 LOGV("Read data[%d/%d].",count,buf_len);
1180
1181 *mbtk_errno = MBTK_SOCK_SUCCESS;
1182 return count;
1183}
1184extern int mbtk_sock_readline(mbtk_sock_handle handle,mbtk_sock_session session,
1185 void *buffer,
1186 unsigned int buf_len,
1187 unsigned int timeout,
1188 int *mbtk_errno,
1189 int *read_line_count,
1190 char *buf_ptr)
1191{
1192 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
1193 || session < 0 || mbtk_sock[handle] == NULL) {
1194 LOGE("Socket not inited.");
1195 return -1;
1196 }
1197
1198 *mbtk_errno = MBTK_SOCK_ERROR;
1199 if(buffer == NULL) {
1200 LOGE("mbtk_sock_write() args error.");
1201 return -1;
1202 }
1203
1204 mbtk_sock_inter_info_s *inter_info = NULL;
1205 int index = 0;
1206 while(index < MBTK_SOCK_MAX_NUM) {
1207 if(session ==
1208 mbtk_sock[handle]->inter_infos[index].fd) {
1209 inter_info = &(mbtk_sock[handle]->inter_infos[index]);
1210 break;
1211 }
1212 index++;
1213 }
1214
1215 if(!sock_info_check(handle,inter_info)) {
1216 LOGE("sock_info_check() fail.");
1217 return -1;
1218 }
1219
1220 index = sock_info_find_by_fd(handle,inter_info->fd);
1221 if(index < 0) {
1222 LOGE("No such socket in session list.");
1223 return -1;
1224 }
1225
1226 unsigned int count = 0;
1227 unsigned int read_count = 0;
1228 memset(buf_ptr, 0, buf_len);
1229 char *temp_ptr = (char *)buffer;
1230copy_angin_ssl:
1231 while(*read_line_count > 0 && *temp_ptr != '\n') {
1232 if(*temp_ptr == NULL)
1233 {
1234 printf("\n*temp_ptr is null\n");
1235 goto read_end;
1236 }
1237 *buf_ptr++ = *temp_ptr++;
1238 (*read_line_count)--;
1239 count++;
1240 }
1241 if(*read_line_count == 0)
1242 {
1243 if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_TCP) {
1244 int len = 0;
1245 int try_count = 0;
1246 int times = timeout / 50;
1247 memset(buffer,0x0,buf_len);
1248 while(count < buf_len){
1249 try_count++;
b.liu9a8e82b2023-10-10 16:09:50 +08001250 if(mbtk_sock[handle]->infos[index].is_support_ssl) {
1251#ifdef MBTK_POLARSSL_SUPPORT
1252 len = mbtk_polarssl_read(inter_info->ssl,(char*)buffer + count,buf_len - count);
1253#else
luojin8fbb3432023-10-18 09:47:46 +08001254 len = mbtk_openssl_read(inter_info->ssl,(char*)buffer + count,buf_len - count);
b.liu9a8e82b2023-10-10 16:09:50 +08001255#endif
1256 } else
liubin281ac462023-07-19 14:22:54 +08001257 len = read(inter_info->fd,(char*)buffer + count,buf_len - count);
1258 *read_line_count = len;
1259 if(len < 0){
1260 if(errno == EWOULDBLOCK){
1261 if(count > 0) // Read data
1262 {
1263 *read_line_count = count;
1264 count = 0;
1265 goto copy_angin_ssl;
1266 break; // Read data end.
1267 }
1268 else
1269 {
1270 //printf("\nread_end\n");
1271 goto read_end;
1272 }
1273 if(try_count >= times){ // Timeout
1274 count = -1;
1275 if(times != 0) {
1276 *mbtk_errno = MBTK_SOCK_ETIMEOUT;
1277 }
1278 LOGE("Not read enough data,return.[%d/%d]",count,buf_len);
1279 goto read_end;
1280 break;
1281 } else {
1282 usleep(50000);
1283 continue;
1284 }
1285 } else {
1286 LOGE("read error.[%d]",errno);
1287 if(count <= 0)
1288 count = -1;
b.liueb040652023-09-25 18:50:56 +08001289 else {
liubin281ac462023-07-19 14:22:54 +08001290 *read_line_count = count;
1291 }
1292 break;
1293 }
1294 } else if(len == 0) {
1295 LOGE("read error(len == 0).[%d]",errno);
1296 if(errno == EINPROGRESS) {
1297 if(close(inter_info->fd) == 0) {// Success
1298 LOGD("Socket disconnected.Close it.");
1299 }
1300 if(count <= 0)
1301 count = -1;
1302 } else {
1303 if(count <= 0)
1304 count = 0;
1305 else
1306 count = -1;
1307 }
1308 goto read_end;
1309 break;
1310 } else {
1311 count += len;
1312 }
1313 }
1314 } else if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_UDP) {
1315 // Start recv data
1316 struct sockaddr_in seraddr;
1317 socklen_t seraddr_len;
1318 int try_count = 0;
1319 int times = timeout / 50;
1320 int len = 0;
1321 memset(buffer,0x0,buf_len);
1322 while(TRUE){
1323 try_count++;
1324 seraddr_len = sizeof(struct sockaddr_in);
1325 len = recvfrom(inter_info->fd,buffer,buf_len,0,&seraddr,&seraddr_len);
1326 if(len < 0){
1327 if(errno == EWOULDBLOCK){// No data can read.
1328 if(count > 0) // Read data
1329 break; // Read data end.
1330
1331 if(try_count >= times){ // Timeout
1332 if(times == 0) {
1333 LOGE("Can not read.");
1334 //printf("Can not read.\n");
1335 } else {
1336 LOGE("Timeout");
1337 //printf("Timeout\n");
1338 *mbtk_errno = MBTK_SOCK_ETIMEOUT;
1339 }
1340 count = -1;
1341 LOGE("Not read enough data,return.[%d/%d]",count,buf_len);
1342 //printf("Not read enough data,return.[%d/%d]\n",count,buf_len);
1343 break;
1344 } else {
1345 usleep(50000);
1346 continue;
1347 }
1348 } else {
1349 LOGE("recvfrom error.[%d]",errno);
1350 if(count <= 0)
1351 count = -1;
1352 break;
1353 }
1354 } else if(len == 0) {
1355 LOGE("write error(len == 0).[%d]",errno);
1356 if(count <= 0)
1357 count = 0;
1358 break;
1359 } else {
1360 count += len;
1361 }
1362 }
1363 } else {
1364 LOGE("Socket type error.");
1365 //printf("Socket type error.\n");
1366 return -1;
1367 }
1368 count = 0;
1369 goto copy_angin_ssl;
1370 } else if(*temp_ptr == '\n') { // Read line.
1371 *buf_ptr++ = '\n';
1372 (*read_line_count)--;
1373 count++;
1374
1375 if(*read_line_count > 0)
1376 memcpy(buffer, temp_ptr + 1, *read_line_count);
1377 return count;
1378 }
1379 LOGV("Read data[%d/%d].",count,buf_len);
1380read_end:
1381 *mbtk_errno = MBTK_SOCK_SUCCESS;
1382 return count;
1383}
1384
1385extern int mbtk_sock_read_async(mbtk_sock_handle handle,mbtk_sock_session session,
1386 void *buffer,
1387 unsigned int buf_len)
1388{
1389 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
1390 || session < 0 || mbtk_sock[handle] == NULL) {
1391 LOGE("Socket not inited.");
1392 return -1;
1393 }
1394
1395 if(buffer == NULL) {
1396 LOGE("mbtk_sock_write() args error.");
1397 return -1;
1398 }
1399
1400 mbtk_sock_inter_info_s *inter_info = NULL;
1401 int index = 0;
1402 while(index < MBTK_SOCK_MAX_NUM) {
1403 if(session ==
1404 mbtk_sock[handle]->inter_infos[index].fd) {
1405 inter_info = &(mbtk_sock[handle]->inter_infos[index]);
1406 break;
1407 }
1408 index++;
1409 }
1410 if(!sock_info_check(handle,inter_info)) {
1411 LOGE("sock_info_check() fail.");
1412 return -1;
1413 }
1414
1415 index = sock_info_find_by_fd(handle,inter_info->fd);
1416 if(index < 0) {
1417 LOGE("No such socket in session list.");
1418 return -1;
1419 }
1420
b.liueb040652023-09-25 18:50:56 +08001421 int len = 0;
1422 int read_count = 0;
1423 if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_TCP) {
1424 memset(buffer,0x0,buf_len);
1425 while(read_count < buf_len) {
b.liu9a8e82b2023-10-10 16:09:50 +08001426 if(mbtk_sock[handle]->infos[index].is_support_ssl) {
1427#ifdef MBTK_POLARSSL_SUPPORT
b.liueb040652023-09-25 18:50:56 +08001428 len = ssl_read(inter_info->ssl,(char*)buffer + read_count,buf_len - read_count);
b.liu9a8e82b2023-10-10 16:09:50 +08001429#else
luojin8fbb3432023-10-18 09:47:46 +08001430 len = mbtk_openssl_read(inter_info->ssl,(char*)buffer + read_count,buf_len - read_count);
b.liu9a8e82b2023-10-10 16:09:50 +08001431
1432#endif
1433 } else
b.liueb040652023-09-25 18:50:56 +08001434 len = read(inter_info->fd,(char*)buffer + read_count,buf_len - read_count);
1435
1436 if(len > 0) {
1437 read_count += len;
1438 } else {
b.liu94baa7c2023-09-26 16:26:10 +08001439 if(errno == EWOULDBLOCK) { // No data
1440 break;
1441 } else {
1442 LOGE("Will retry : len = %d, errno = %d", len, errno);
1443 }
b.liueb040652023-09-25 18:50:56 +08001444 }
1445 }
1446 } else if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_UDP) {
1447 // Start recv data
1448 struct sockaddr_in seraddr;
1449 socklen_t seraddr_len;
1450 memset(buffer,0x0,buf_len);
1451 seraddr_len = sizeof(struct sockaddr_in);
1452 memset(buffer,0x0,buf_len);
1453
1454 while(read_count < buf_len) {
1455 len = recvfrom(inter_info->fd,buffer + read_count,buf_len - read_count,0,&seraddr,&seraddr_len);
1456
1457 if(len > 0) {
1458 read_count += len;
1459 } else {
b.liu94baa7c2023-09-26 16:26:10 +08001460 if(errno == EWOULDBLOCK) { // No data
1461 break;
1462 } else {
1463 LOGE("Will retry : len = %d, errno = %d", len, errno);
1464 }
b.liueb040652023-09-25 18:50:56 +08001465 }
1466 }
1467 } else {
1468 LOGE("Socket type error.");
1469 return -1;
1470 }
1471
b.liu94baa7c2023-09-26 16:26:10 +08001472 LOGV("Read data[%d/%d].",read_count,buf_len);
b.liueb040652023-09-25 18:50:56 +08001473
1474 return read_count;
1475}
1476
1477extern int mbtk_sock_read_sync(mbtk_sock_handle handle,mbtk_sock_session session,
1478 void *buffer,
1479 unsigned int buf_len)
1480{
1481 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
1482 || session < 0 || mbtk_sock[handle] == NULL) {
1483 LOGE("Socket not inited.");
1484 return -1;
1485 }
1486
1487 if(buffer == NULL) {
1488 LOGE("mbtk_sock_write() args error.");
1489 return -1;
1490 }
1491
1492 mbtk_sock_inter_info_s *inter_info = NULL;
1493 int index = 0;
1494 while(index < MBTK_SOCK_MAX_NUM) {
1495 if(session ==
1496 mbtk_sock[handle]->inter_infos[index].fd) {
1497 inter_info = &(mbtk_sock[handle]->inter_infos[index]);
1498 break;
1499 }
1500 index++;
1501 }
1502 if(!sock_info_check(handle,inter_info)) {
1503 LOGE("sock_info_check() fail.");
1504 return -1;
1505 }
1506
1507 index = sock_info_find_by_fd(handle,inter_info->fd);
1508 if(index < 0) {
1509 LOGE("No such socket in session list.");
1510 return -1;
1511 }
1512
liubin281ac462023-07-19 14:22:54 +08001513 int len;
1514 if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_TCP) {
1515TCP_READ_AGAIN:
1516 memset(buffer,0x0,buf_len);
b.liu9a8e82b2023-10-10 16:09:50 +08001517 if(mbtk_sock[handle]->infos[index].is_support_ssl) {
1518#ifdef MBTK_POLARSSL_SUPPORT
liubin281ac462023-07-19 14:22:54 +08001519 len = ssl_read(inter_info->ssl,(char*)buffer,buf_len);
b.liu9a8e82b2023-10-10 16:09:50 +08001520#else
luojin8fbb3432023-10-18 09:47:46 +08001521 len = mbtk_openssl_read(inter_info->ssl,(char*)buffer,buf_len);
b.liu9a8e82b2023-10-10 16:09:50 +08001522
1523#endif
1524 } else
liubin281ac462023-07-19 14:22:54 +08001525 len = read(inter_info->fd,(char*)buffer,buf_len);
1526 if(len < 0){
1527 if(errno == EWOULDBLOCK){
1528 usleep(100000);
b.liueb040652023-09-25 18:50:56 +08001529 LOGW("Read retry...");
liubin281ac462023-07-19 14:22:54 +08001530 goto TCP_READ_AGAIN;
1531 } else {
1532 LOGE("read error.[%d]",errno);
1533 return -1;
1534 }
1535 }
1536 } else if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_UDP) {
1537 // Start recv data
1538 struct sockaddr_in seraddr;
1539 socklen_t seraddr_len;
1540UDP_READ_AGAIN:
1541 memset(buffer,0x0,buf_len);
1542 seraddr_len = sizeof(struct sockaddr_in);
1543 len = recvfrom(inter_info->fd,buffer,buf_len,0,&seraddr,&seraddr_len);
1544 if(len < 0){
1545 if(errno == EWOULDBLOCK){
1546 usleep(100000);
1547 goto UDP_READ_AGAIN;
1548 } else {
1549 LOGE("read error.[%d]",errno);
1550 return -1;
1551 }
1552 }
1553 } else {
1554 LOGE("Socket type error.");
1555 return -1;
1556 }
1557
1558 LOGV("Read data[%d/%d].",len,buf_len);
1559
1560 return len;
1561}
1562
b.liu94baa7c2023-09-26 16:26:10 +08001563
liubin281ac462023-07-19 14:22:54 +08001564extern int mbtk_sock_close(mbtk_sock_handle handle,mbtk_sock_session session,
1565 unsigned int timeout,
1566 int *mbtk_errno)
1567{
1568 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
1569 || session < 0 || mbtk_sock[handle] == NULL) {
1570 LOGE("Socket not inited.");
1571 return -1;
1572 }
1573
1574 *mbtk_errno = MBTK_SOCK_ERROR;
1575 mbtk_sock_inter_info_s *inter_info = NULL;
1576 int index = 0;
1577 while(index < MBTK_SOCK_MAX_NUM) {
1578 if(session == mbtk_sock[handle]->inter_infos[index].fd) {
1579 inter_info = &(mbtk_sock[handle]->inter_infos[index]);
1580 break;
1581 }
1582 index++;
1583 }
1584 if(!sock_info_check(handle,inter_info)) {
1585 LOGE("sock_info_check() fail.");
1586 return -1;
1587 }
1588
1589 index = sock_info_find_by_fd(handle,inter_info->fd);
1590 if(index < 0) {
1591 LOGE("No such socket in session list.");
1592 return -1;
1593 }
1594
1595 int i;
1596 for(i = 0;i < MBTK_SOCK_MAX_NUM;i++) {
1597 if(mbtk_sock[handle]->inter_infos[i].fd == inter_info->fd){
1598 if(mbtk_sock[handle]->init_info.sock_cb) {
1599 struct epoll_event ev;
1600 ev.data.fd = inter_info->fd;
1601 ev.events = EPOLLIN | EPOLLET;
1602 epoll_ctl(epoll_fd,EPOLL_CTL_DEL,inter_info->fd,&ev);
1603 }
1604
1605 if(close(inter_info->fd) < 0) {// Success
1606 LOGE("Close socket fail[%d].",errno);
1607 //break;
1608 }
1609 mbtk_sock[handle]->inter_infos[i].fd = -1;
1610 memset(&(mbtk_sock[handle]->infos[i]),0x0,sizeof(mbtk_sock_info));
1611 mbtk_sock[handle]->sock_num--;
1612 break;
1613 }
1614 }
1615
1616 if(mbtk_sock[handle]->infos[index].is_support_ssl){
b.liu9a8e82b2023-10-10 16:09:50 +08001617#ifdef MBTK_POLARSSL_SUPPORT
1618 if(mbtk_polarssl_close(inter_info)== -1)
liubin281ac462023-07-19 14:22:54 +08001619 {
1620 LOGE("close ssl fail");
1621 return -1;
1622 }
b.liu9a8e82b2023-10-10 16:09:50 +08001623#else
luojin8fbb3432023-10-18 09:47:46 +08001624 if(mbtk_openssl_close(inter_info)== -1)
1625 {
1626 LOGE("close ssl fail");
1627 return -1;
1628 }
b.liu9a8e82b2023-10-10 16:09:50 +08001629
1630#endif
liubin281ac462023-07-19 14:22:54 +08001631 }
1632
1633 *mbtk_errno = MBTK_SOCK_SUCCESS;
1634 return 0;
1635}
1636
1637extern int mbtk_sock_deinit(mbtk_sock_handle handle)
1638{
1639 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
1640 || mbtk_sock[handle] == NULL) {
1641 LOGE("Socket not inited.");
1642 return -1;
1643 }
1644
1645 if(mbtk_sock[handle]->sock_num > 0) {
1646 LOGE("There are socket not close.");
1647 return MBTK_SOCK_ERROR;
1648 }
1649
1650 LOGD("mbtk_sock_deinit() start.");
1651#if 0
1652 sock_thread_running = FALSE;
1653 write(pipe_fds[0],"0",1);
1654
1655 // Wait for thread exist.
1656 while(sock_inited) {
1657 usleep(100);
1658 }
1659#endif
1660
1661 int i;
1662 for(i = 0;i < MBTK_SOCK_MAX_NUM;i++) {
1663 if(mbtk_sock[handle]->inter_infos[i].fd > 0){
1664 if(mbtk_sock[handle]->init_info.sock_cb) {
1665 struct epoll_event ev;
1666 ev.data.fd = mbtk_sock[handle]->inter_infos[i].fd;
1667 ev.events = EPOLLIN | EPOLLET;
1668 epoll_ctl(epoll_fd,EPOLL_CTL_DEL,mbtk_sock[handle]->inter_infos[i].fd,&ev);
1669 }
1670
1671 if(close(mbtk_sock[handle]->inter_infos[i].fd) < 0) {// Success
1672 LOGE("Close socket fail[%d].",errno);
1673 //break;
1674 }
1675 mbtk_sock[handle]->inter_infos[i].fd = -1;
1676 memset(&(mbtk_sock[handle]->infos[i]),0x0,sizeof(mbtk_sock_info));
1677 break;
1678 }
1679 }
1680
1681 //memset(&mbtk_sock,0x0,sizeof(mbtk_sock_s));
1682 free(mbtk_sock[handle]);
1683 mbtk_sock[handle] = NULL;
1684 LOGD("mbtk_sock_deinit() end.");
1685 return MBTK_SOCK_SUCCESS;
1686}
1687
b.liu94baa7c2023-09-26 16:26:10 +08001688/*
1689* Get TCP RECV buffer data length.
1690*/
1691int mbtk_sock_tcp_recv_len_get(mbtk_sock_handle handle,mbtk_sock_session session)
1692{
1693 if(handle < 0 || handle >= MBTK_HANDLE_MAX_NUM
1694 || session < 0 || mbtk_sock[handle] == NULL) {
1695 LOGE("Socket not inited.");
1696 return -1;
1697 }
1698
1699 mbtk_sock_inter_info_s *inter_info = NULL;
1700 int index = 0;
1701 while(index < MBTK_SOCK_MAX_NUM) {
1702 if(session ==
1703 mbtk_sock[handle]->inter_infos[index].fd) {
1704 inter_info = &(mbtk_sock[handle]->inter_infos[index]);
1705 break;
1706 }
1707 index++;
1708 }
1709 if(!sock_info_check(handle,inter_info)) {
1710 LOGE("sock_info_check() fail.");
1711 return -1;
1712 }
1713
1714 index = sock_info_find_by_fd(handle,inter_info->fd);
1715 if(index < 0) {
1716 LOGE("No such socket in session list.");
1717 return -1;
1718 }
1719
1720 unsigned int count = 0;
1721 int len = 0;
1722 if(mbtk_sock[handle]->infos[index].type == MBTK_SOCK_TCP) {
1723 if(ioctl(inter_info->fd, FIONREAD, &len))
1724 {
1725 LOGE("Get ioctl FIONREAD fail:%d", errno);
1726 return -1;
1727 }
1728 } else {
1729 LOGE("Only surrport for TCP.");
1730 return -1;
1731 }
1732
1733 return len;
1734}
1735
b.liubcf86c92024-08-19 19:48:28 +08001736void mbtk_net_lib_info_print()
1737{
1738 MBTK_SOURCE_INFO_PRINT("mbtk_net_lib");
1739}
liubin281ac462023-07-19 14:22:54 +08001740
luojin8fbb3432023-10-18 09:47:46 +08001741