2 // Open Service Platform
3 // Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
5 // Licensed under the Flora License, Version 1.0 (the License);
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://floralicense.org/license/
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an AS IS BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
19 * @file FNetSock_SecureSocketImpl.cpp
20 * @brief This is the implementation for the _SecureSocketImpl class.
23 #include <unique_ptr.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/ioctl.h>
30 #include <arpa/inet.h>
32 #include <netinet/in.h>
33 #include <netinet/tcp.h>
36 #include <openssl/pkcs12.h>
37 #include <openssl/crypto.h>
38 #include <openssl/pem.h>
39 #include <openssl/err.h>
40 #include <openssl/x509.h>
41 #include <openssl/bio.h>
43 #include <FNetNetTypes.h>
44 #include <FNetIp4Address.h>
45 #include <FNetNetConnectionManager.h>
46 #include <FNetSockSecureSocket.h>
47 #include <FBaseSysLog.h>
48 #include <FSecCert_CertService.h>
49 #include <FSecCert_CertServiceProxy.h>
50 #include <FBase_StringConverter.h>
51 #include <FBaseRt_EventDispatcher.h>
52 #include <FApp_AppInfo.h>
53 #include "FNet_NetEndPointImpl.h"
54 #include "FNet_Ip4AddressImpl.h"
55 #include "FNet_NetConnectionManagerImpl.h"
56 #include "FNet_ManagedNetConnectionImpl.h"
57 #include "FNet_NetConnectionInfoImpl.h"
58 #include "FNet_NetConnectionImpl.h"
59 #include "FNetSock_SecureSocketEvent.h"
60 #include "FNetSock_SecureSocketEventArg.h"
61 #include "FNetSock_SocketInternalHelp.h"
62 #include "FNetSock_SecureSocketManagedNetConnectionEventListenerImpl.h"
63 #include "FNetSock_SecureSocketCustomNetConnectionEventListenerImpl.h"
64 #include "FNetSock_SecureSocketImpl.h"
65 #include "FNetSock_SocketDeleter.h"
68 using namespace Tizen::Base;
69 using namespace Tizen::Base::Runtime;
70 using namespace Tizen::Base::Collection;
71 using namespace Tizen::Base::Utility;
72 using namespace Tizen::Security::Cert;
73 using namespace Tizen::App;
75 namespace Tizen { namespace Net { namespace Sockets
78 static const long _SECURE_SOCKET_CONNECTION_TIMEOUT = 30;
79 static const long _THREAD_SLEEP_TIMER = 2000; // 2000 milliseconds = 2 second (sleep time)
80 static const long _MAX_COUNT_THREAD_SLEEP_TIMER = 15; // 2000 * 15 = 30000 milliseconds = 30 seconds (max sleep time)
81 static const long _RSA_512_KEY = 512; // RSA Key length 512
82 static const long _RSA_1024_KEY = 1024; // RSA Key length 1024
83 static const long _SSL_VERIFY_DEPTH = 9; // certificate verification depth 9
85 pthread_mutex_t _SecureSocketImpl::__mapMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
87 bool _Singleton::__initialized = false;
88 HashMap* _Singleton::__pSslMap = null;
90 _SecureSocketImpl::_SecureSocketImpl(SecureSocket* pSocket)
91 : __socketFd(INVALID_HANDLE)
92 , __isConstructed(false)
96 , __isReadFired(false)
97 , __isConnectFired(false)
98 , __isAcceptFired(false)
100 , __isWriteFired(false)
101 , __isCloseFired(false)
102 , __isConnectFailed(false)
103 , __isAcceptFailed(false)
104 , __isCertVerifyFailed(false)
105 , __isClientNoCert(false)
106 , __isPeerNoCert(false)
107 , __isClientVerify(false)
108 , __isSslConnected(false)
109 , __isSslAccepted(false)
110 , __isRunFinished(false)
111 , __isNonblock(false)
112 , __isLoadVerify(false)
113 , __sslVerify(SECURE_SOCKET_VERIFY_NONE)
114 , __socketEventType(NET_SOCKET_EVENT_NONE)
115 , __protocolFamily(NET_SOCKET_AF_NONE)
116 , __socketType(NET_SOCKET_TYPE_NONE)
117 , __protocol(NET_SOCKET_PROTOCOL_NONE)
118 , __sslVersion(NET_SOCK_SSL_VERSION_NONE)
119 , __sslCipherSuiteId(NET_SOCK_TLS_SSL_NULL_WITH_NULL_NULL)
120 , __pNetConnectionManager(null)
121 , __pManagedNetConnection(null)
122 , __pManagedNetConnectionEventListener(null)
123 , __pCustomNetConnection(null)
124 , __pCustomNetConnectionEventListener(null)
125 , __pSecureSocketEvent(null)
126 , __pSecureSocket(pSocket)
131 , __pGMainContext(null)
132 , __pGlibSocketInfo(null)
133 , __pTimerSource(null)
139 _SecureSocketImpl::~_SecureSocketImpl(void)
143 if (__pThread != null)
150 delete __pGlibSocketInfo;
151 __pGlibSocketInfo = null;
156 pthread_mutex_lock(&__mapMutex);
157 if ((_Singleton::GetInitialized() == true) && (__pSslKey))
159 _Singleton::GetSslMap()->Remove(*__pSslKey, true);
161 pthread_mutex_unlock(&__mapMutex);
165 SSL_shutdown(__pSsl);
171 if (__pSslCtx != null)
173 SSL_CTX_free(__pSslCtx);
177 __pGMainContext = null;
179 __secureSocketEventListenerList.RemoveAll();
181 delete __pSecureSocketEvent;
182 __pSecureSocketEvent = null;
184 delete __pCustomNetConnection;
185 __pCustomNetConnection = null;
187 delete __pCustomNetConnectionEventListener;
188 __pCustomNetConnectionEventListener = null;
190 delete __pManagedNetConnection;
191 __pManagedNetConnection = null;
193 delete __pManagedNetConnectionEventListener;
194 __pManagedNetConnectionEventListener = null;
196 delete __pNetConnectionManager;
197 __pNetConnectionManager = null;
199 if (__pTimerSource != null)
201 int timerId = g_source_get_id(__pTimerSource);
202 g_source_set_callback(__pTimerSource, null, null, null);
203 SysLog(NID_NET_SOCK, "### deleted g_source_destroy(%d)", timerId);
204 g_source_destroy(__pTimerSource);
205 g_source_unref(__pTimerSource);
206 __pTimerSource = null;
207 SysLog(NID_NET_SOCK, "Canceled the TimerSource[%d].", timerId);
210 __protocol = NET_SOCKET_PROTOCOL_NONE;
211 __socketType = NET_SOCKET_TYPE_NONE;
212 __protocolFamily = NET_SOCKET_AF_NONE;
213 __socketEventType = NET_SOCKET_EVENT_NONE;
214 __isCloseFired = false;
215 __isWriteFired = false;
216 __isReadFired = false;
217 __isConnectFired = false;
218 __isAcceptFired = false;
220 __isCertVerifyFailed = false;
221 __isConnectFailed = false;
222 __isAcceptFailed = false;
223 __isClientNoCert = false;
224 __isPeerNoCert = false;
225 __isClientVerify = false;
226 __isSslConnected = false;
227 __isSslAccepted = false;
228 __isRunFinished = false;
229 __isNonblock = false;
230 __isLoadVerify = false;
231 __sslVerify = SECURE_SOCKET_VERIFY_NONE;
232 __sslVersion = NET_SOCK_SSL_VERSION_NONE;
233 __sslCipherSuiteId = NET_SOCK_TLS_SSL_NULL_WITH_NULL_NULL;
236 __isLoopback = false;
237 __isConstructed = false;
238 __socketFd = INVALID_HANDLE;
242 _SecureSocketImpl::Construct(const Tizen::Net::NetConnection& netConnection, NetSocketAddressFamily addressFamily,
243 NetSocketType socketType, NetSocketProtocol protocol)
245 SysTryReturnResult(NID_NET_SOCK, addressFamily == NET_SOCKET_AF_IPV4, E_UNSUPPORTED_FAMILY, "The AddressFamily is unsupported.");
246 SysTryReturnResult(NID_NET_SOCK, socketType == NET_SOCKET_TYPE_STREAM, E_UNSUPPORTED_TYPE, "The SocketType is unsupported.");
247 SysTryReturnResult(NID_NET_SOCK, protocol == NET_SOCKET_PROTOCOL_SSL, E_UNSUPPORTED_PROTOCOL, "The Protocol is unsupported.");
249 SysLog(NID_NET_SOCK, "Socket uses CustomNetConnection.");
251 _Singleton::InitializeSecureSocket();
253 // Add netConection null check validation
254 NetConnection* pNetConnection = const_cast <NetConnection*>(&netConnection);
255 SysTryReturnResult(NID_NET_SOCK, pNetConnection, E_INVALID_ARG, "NetConnection is invalid.");
257 result r = E_SUCCESS;
260 int sockFd = INVALID_HANDLE;
264 _NetConnectionImpl* pCustomNCImpl = null;
265 NetConnectionState connState = NET_CONNECTION_STATE_NONE;
268 char* pDeviceName = null;
269 const NetConnectionInfo* pNetConnectionInfo = null;
270 const _NetConnectionInfoImpl* pNCInfoImpl = null;
272 unique_ptr<_SecureSocketEvent> pSecureSocketEvent;
273 unique_ptr<_SecureSocketCustomNetConnectionEventListener> pCustomNetConnectionEventListener;
274 unique_ptr<NetConnection> pCustomNetConnection;
276 // Set proper inparam
277 if (addressFamily == NET_SOCKET_AF_IPV4)
280 __protocolFamily = addressFamily;
283 if (socketType == NET_SOCKET_TYPE_STREAM)
285 SysTryReturnResult(NID_NET_SOCK, protocol == NET_SOCKET_PROTOCOL_SSL, E_INVALID_ARG, "Invalid SocketType - Mismatch.");
287 __socketType = socketType;
288 __protocol = NET_SOCKET_PROTOCOL_SSL;
291 // Custom Network Check
292 connState = pNetConnection->GetConnectionState();
294 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
296 SysLog(NID_NET_SOCK, "Custom Network is available.");
300 r = E_INVALID_CONNECTION;
301 SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Custom Network is not available.");
305 __socketFd = socket(af, type, 0);
309 r = ConvertErrorToResult(errno);
310 SysLogException(NID_NET_SOCK, r, "[%s] Failed to construct the socket.", GetErrorMessage((r)));
314 flags = fcntl(__socketFd, F_GETFL);
317 if (fcntl(__socketFd, F_SETFL, flags) < 0)
319 __isNonblock = false;
321 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to construct(ioctl) the socket.");
328 __secureSocketEventListenerList.Construct();
330 pSecureSocketEvent.reset(new (std::nothrow) _SecureSocketEvent());
331 SysTryReturnResult(NID_NET_SOCK, pSecureSocketEvent != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
333 r = pSecureSocketEvent->Construct(this);
334 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Socket Event Construct is Failed.");
336 SSL_load_error_strings();
337 ERR_load_BIO_strings();
338 OpenSSL_add_all_algorithms();
339 CRYPTO_malloc_init();
340 SSLeay_add_all_algorithms();
341 ERR_load_crypto_strings();
343 __pSslMethod = (SSL_METHOD*) SSLv3_method();
344 __sslVersion = NET_SOCK_SSL_VERSION_SSLV3;
346 __pSslCtx = SSL_CTX_new(__pSslMethod);
347 SysTryCatch(NID_NET_SOCK, __pSslCtx != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create the SSL Context.");
350 // Set the device name (setsockopt)
351 pNetConnectionInfo = pNetConnection->GetNetConnectionInfo();
352 SysTryCatch(NID_NET_SOCK, pNetConnectionInfo != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get the ConnectionInfo Object.");
354 pNCInfoImpl = _NetConnectionInfoImpl::GetInstance(*pNetConnectionInfo);
355 SysTryCatch(NID_NET_SOCK, pNCInfoImpl != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get the ConnectionInfoImpl Object.");
357 deviceName = pNCInfoImpl->GetDeviceName();
359 if (deviceName.IsEmpty())
361 SysLog(NID_NET_SOCK, "DeviceName is empty string. - Emulator Case");
365 SysLog(NID_NET_SOCK, "DeviceName is not empty string.[Device Name : %ls] - Target Case", deviceName.GetPointer());
367 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
368 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
370 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
371 delete[] pDeviceName;
374 r = ConvertErrorToResult(errno);
375 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_CONNECTION, E_INVALID_CONNECTION,
376 "[E_INVALID_CONNECTION] Failed to bind(setsockopt) Device Name.");
380 // Copy New CustomNetConnection
381 pCustomNCImpl = _NetConnectionImpl::GetInstance(*pNetConnection);
383 pCustomNetConnection.reset(pCustomNCImpl->CopyInstanceN());
384 SysTryCatch(NID_NET_SOCK, pCustomNetConnection != null, r = E_INVALID_CONNECTION, E_INVALID_CONNECTION,
385 "[E_INVALID_CONNECTION] CustomNetConnection is null. Failed to copy the InstanceN.");
387 // New CustomNetConnectionEventListener
388 pCustomNetConnectionEventListener.reset(new (std::nothrow) _SecureSocketCustomNetConnectionEventListener());
389 SysTryCatch(NID_NET_SOCK, pCustomNetConnectionEventListener != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
390 "[E_OUT_OF_MEMORY] Memory allocation failed.");
392 // AddNetConnectionListener
393 r = pCustomNetConnection->AddNetConnectionListener(*pCustomNetConnectionEventListener);
394 r = TransExceptionsExclusive(r, E_INVALID_CONNECTION, E_OUT_OF_MEMORY);
395 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Failed to add the NetConnectionListener.", GetErrorMessage(r));
397 // Set the __socketFd
398 pCustomNetConnectionEventListener->SetConstructParams(pSecureSocketEvent.get(), __socketFd, this);
400 __pCustomNetConnection = pCustomNetConnection.release();
401 __pCustomNetConnectionEventListener = pCustomNetConnectionEventListener.release();
402 __pSecureSocketEvent = pSecureSocketEvent.release();
404 __isConstructed = true;
406 SysLog(NID_NET_SOCK, "Created the Secure Socket by non-blocking mode(default) [Fd: %d]", __socketFd);
411 if (__socketFd > INVALID_HANDLE)
415 SysLog(NID_NET_SOCK, "### SocketFd is closed. [Fd : %d]", sockFd);
420 SSL_CTX_free(__pSslCtx);
427 _SecureSocketImpl::Construct(NetSocketAddressFamily addressFamily, NetSocketType socketType, NetSocketProtocol protocol)
429 SysTryReturnResult(NID_NET_SOCK, addressFamily == NET_SOCKET_AF_IPV4, E_UNSUPPORTED_FAMILY,
430 "The AddressFamily is unsupported.");
431 SysTryReturnResult(NID_NET_SOCK, socketType == NET_SOCKET_TYPE_STREAM, E_UNSUPPORTED_TYPE,
432 "The SocketType is unsupported.");
433 SysTryReturnResult(NID_NET_SOCK, protocol == NET_SOCKET_PROTOCOL_SSL, E_UNSUPPORTED_PROTOCOL,
434 "The Protocol is unsupported.");
436 SysLog(NID_NET_SOCK, "Socket uses DefaultNetConnection.");
438 _Singleton::InitializeSecureSocket();
440 result r = E_SUCCESS;
444 int sockFd = INVALID_HANDLE;
446 _ManagedNetConnectionImpl* pManagedNCImpl = null;
447 NetConnectionState connState = NET_CONNECTION_STATE_NONE;
448 _SocketMethodFlag flag = FLAG_NONE;
450 unique_ptr<_SecureSocketEvent> pSecureSocketEvent;
451 unique_ptr<_SecureSocketManagedNetConnectionEventListener> pManagedNetConnectionEventListener;
452 unique_ptr<ManagedNetConnection> pManagedNetConnection;
453 unique_ptr<NetConnectionManager> pNetConnectionManager;
455 // Set proper inparam
456 if (addressFamily == NET_SOCKET_AF_IPV4)
459 __protocolFamily = addressFamily;
462 if (socketType == NET_SOCKET_TYPE_STREAM)
464 SysTryReturnResult(NID_NET_SOCK, protocol == NET_SOCKET_PROTOCOL_SSL, E_INVALID_ARG, "Invalid SocketType - Mismatch.");
467 __socketType = socketType;
468 __protocol = NET_SOCKET_PROTOCOL_SSL;
471 __socketFd = socket(af, type, 0);
475 r = ConvertErrorToResult(errno);
476 SysLogException(NID_NET_SOCK, r, "[%s] Failed to construct the socket.", GetErrorMessage((r)));
480 flags = fcntl(__socketFd, F_GETFL);
483 if (fcntl(__socketFd, F_SETFL, flags) < 0)
485 __isNonblock = false;
487 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to construct(ioctl) the socket.");
495 __secureSocketEventListenerList.Construct();
497 pSecureSocketEvent.reset(new (std::nothrow) _SecureSocketEvent());
498 SysTryReturn(NID_NET_SOCK, pSecureSocketEvent != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
500 r = pSecureSocketEvent->Construct(this);
501 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[%s] Failed to construct the SecureSocketEvent.", GetErrorMessage(r));
503 SSL_load_error_strings();
504 ERR_load_BIO_strings();
505 OpenSSL_add_all_algorithms();
506 CRYPTO_malloc_init();
507 SSLeay_add_all_algorithms();
508 ERR_load_crypto_strings();
510 __pSslMethod = (SSL_METHOD*) SSLv3_method();
511 __sslVersion = NET_SOCK_SSL_VERSION_SSLV3;
513 __pSslCtx = SSL_CTX_new(__pSslMethod);
514 SysTryCatch(NID_NET_SOCK, __pSslCtx != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create the SSL Context.");
518 if (_NetConnectionManagerImpl::IsDefaultMode() != true)
520 SysLog(NID_NET_SOCK, "Socket uses ManagedNetConnection");
522 pNetConnectionManager.reset(new (std::nothrow) NetConnectionManager());
523 SysTryCatch(NID_NET_SOCK, pNetConnectionManager != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
525 r = pNetConnectionManager->Construct();
526 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_CONNECTION, r, "[%s] Failed to construct the ManagedNetConnection.", GetErrorMessage(r));
528 pManagedNetConnection.reset(pNetConnectionManager->GetManagedNetConnectionN());
529 SysTryCatch(NID_NET_SOCK, pManagedNetConnection != null, r = E_INVALID_CONNECTION, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] ManagedNetConnection is null. Failed to the GetManagedNetConnectionN.");
531 pManagedNCImpl = _ManagedNetConnectionImpl::GetInstance(*pManagedNetConnection);
532 SysTryCatch(NID_NET_SOCK, pManagedNCImpl != null, r = E_INVALID_CONNECTION, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] ManagedNetConnectionImpl is null. Failed to the GetManagedNetConnectionN.");
534 // New ManagedNetConnectionEventListener
535 pManagedNetConnectionEventListener.reset(new (std::nothrow) _SecureSocketManagedNetConnectionEventListener());
536 SysTryCatch(NID_NET_SOCK, pManagedNetConnectionEventListener != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
538 // SetManagedNetConnectionEventListener
539 r = pManagedNetConnection->SetManagedNetConnectionEventListener(pManagedNetConnectionEventListener.get());
540 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_CONNECTION, r, "[%s] Failed to the SetManagedNetConnectionEventListener.", GetErrorMessage(r));
542 // Set the __socketFd
543 flag = FLAG_CONSTRUCT;
544 pManagedNetConnectionEventListener->SetConstructParams(pSecureSocketEvent.get(), __socketFd, flag, this);
546 // Start ManagedNetConnectionImpl
547 r = pManagedNCImpl->Start();
548 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_CONNECTION, r, "[%s] Failed to start the ManagedNetConnection.", GetErrorMessage(r));
550 connState = pManagedNCImpl->GetConnectionState();
551 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
553 pManagedNetConnectionEventListener->SetStartedFlag(true);
557 __pNetConnectionManager = pNetConnectionManager.release();
558 __pManagedNetConnection = pManagedNetConnection.release();
559 __pManagedNetConnectionEventListener = pManagedNetConnectionEventListener.release();
560 __pSecureSocketEvent = pSecureSocketEvent.release();
562 __isConstructed = true;
564 SysLog(NID_NET_SOCK, "Created the Secure Socket by non-blocking mode(default) [Fd: %d]", __socketFd);
569 if (__socketFd > INVALID_HANDLE)
573 SysLog(NID_NET_SOCK, "### SocketFd is closed. [Fd : %d]", sockFd);
578 SSL_CTX_free(__pSslCtx);
585 _SecureSocketImpl::Connect(const Tizen::Net::NetEndPoint& remoteEP)
587 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
588 SysTryReturnResult(NID_NET_SOCK, __pSslCtx != null, E_INVALID_ARG, "The SSL Context object is null.");
590 result r = E_SUCCESS;
597 unsigned long ipAddr = 0;
598 unsigned short port = 0;
599 Ip4Address* pIp4Addr = null;
600 const _NetEndPointImpl* pRemoteEPImpl = null;
602 struct sockaddr_in remoteAddr;
604 String remoteAddrString;
606 NetConnectionState connState = NET_CONNECTION_STATE_NONE;
607 _SocketMethodFlag flag = FLAG_NONE;
610 char* pDeviceName = null;
611 const _ManagedNetConnectionImpl* pMNCConnImpl = null;
612 long milliseconds = _THREAD_SLEEP_TIMER; // 2000 milliseconds (sleep time)
614 bool isConnectionStarted = false;
616 char* pCaPath = null;
619 pRemoteEPImpl = _NetEndPointImpl::GetInstance(remoteEP);
621 if (pRemoteEPImpl->IsValid() == true)
623 pIp4Addr = static_cast <Ip4Address*>(pRemoteEPImpl->GetAddress());
624 remoteAddrString = pIp4Addr->ToString();
629 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] NetEndPoint is invalid.");
633 _ApiVersion apiVersion = _AppInfo::GetApiVersion();
635 if (apiVersion == _API_VERSION_2_0 && _AppInfo::IsOspCompat())
637 if (__isLoopback == false)
639 if (remoteAddrString == LOOPBACK_ADDRESS)
642 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
648 if (remoteAddrString != LOOPBACK_ADDRESS)
651 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
657 af = pRemoteEPImpl->GetNetAddressFamily();
658 SysTryReturnResult(NID_NET_SOCK, af == NET_AF_IPV4, E_INVALID_ARG, "Address family is invalid.");
660 r = pIp4Addr->GetAddress(ipAddr);
661 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, E_INVALID_ARG, "Address is invalid.");
663 port = pRemoteEPImpl->GetPort();
665 memset(&remoteAddr, 0, sizeof(remoteAddr));
666 remoteAddr.sin_family = AF_INET;
667 remoteAddr.sin_addr.s_addr = htonl(ipAddr);
668 remoteAddr.sin_port = htons(port);
670 if (__pManagedNetConnection != null)
672 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
674 if (__isNonblock == false)
676 SysLog(NID_NET_SOCK, "This socket is blocking mode.");
678 pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
682 connState = pMNCConnImpl->QueryConnectionState(deviceName);
686 case NET_CONNECTION_STATE_STARTED:
688 case NET_CONNECTION_STATE_RESUMED:
690 case NET_CONNECTION_STATE_SUSPENDED:
691 SysLog(NID_NET_SOCK, "Network is available.");
693 if (deviceName.IsEmpty())
695 SysLog(NID_NET_SOCK, "DeviceName is empty string. - Emulator Case");
699 SysLog(NID_NET_SOCK, "DeviceName is not empty string.[Device Name : %ls] - Target Case", deviceName.GetPointer());
701 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
702 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
704 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
705 delete[] pDeviceName;
708 ConvertErrorToResult(errno);
710 SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Failed to bind the device name.");
714 err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
717 case NET_CONNECTION_STATE_STARTING:
719 case NET_CONNECTION_STATE_NONE:
721 case NET_CONNECTION_STATE_STOPPING:
723 case NET_CONNECTION_STATE_STOPPED:
724 SysLog(NID_NET_SOCK, "Network is not available.");
728 SysLog(NID_NET_SOCK, "Should not come here.");
732 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
737 if (connState == NET_CONNECTION_STATE_STOPPED)
739 r = E_INVALID_CONNECTION;
740 SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
746 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
749 SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network timeout happened. Try Again");
754 Thread::Sleep(milliseconds);
759 isConnectionStarted = __pManagedNetConnectionEventListener->GetStartedFlag();
761 if (isConnectionStarted)
763 err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
769 __pManagedNetConnectionEventListener->SetConnectParams(__socketFd, remoteAddr, flag, this);
777 err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
782 r = ConvertErrorToResult(errno);
784 if (r != E_WOULD_BLOCK)
786 SysLogException(NID_NET_SOCK, r, "[%s] Failed to connect the socket.", GetErrorMessage(r));
787 if (__isAsync == true)
789 __isConnectFired = true;
795 // Set default CA path.
796 caPath = _CertService::GetCertificateCrtFilePath();
797 SysLog(NID_NET_SOCK, "CA Path(%ls)", caPath.GetPointer());
799 pCaPath = _StringConverter::CopyToCharArrayN(caPath);
800 SysTryReturnResult(NID_NET_SOCK, pCaPath != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
802 sslError = SSL_CTX_load_verify_locations(__pSslCtx, pCaPath, null);
803 SysTryCatch(NID_NET_SOCK, sslError >= 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to verify the trusted CA list.");
805 sslError = SSL_CTX_set_default_verify_paths(__pSslCtx);
806 SysTryCatch(NID_NET_SOCK, sslError >= 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set the default verify paths.");
811 __pSsl = SSL_new(__pSslCtx);
812 SysTryCatch(NID_NET_SOCK, __pSsl != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create the SSL Object.");
814 SSL_set_fd(__pSsl, __socketFd);
816 SSL_set_options(__pSsl, SSL_OP_ALL);
818 if (__isAsync == true || __isNonblock == true)
820 SSL_CTX_set_client_cert_cb(__pSslCtx, (int (*)(SSL*, X509**, EVP_PKEY**)) _SecureSocketImpl::OnClientCertCallback);
822 SSL_set_mode(__pSsl, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
824 sslIndex = SSL_get_ex_new_index(0, (char*) "_SecureSocketImpl index", null, null, null);
825 SysLog(NID_NET_SOCK, "SSL index(%d).", sslIndex);
827 SSL_set_ex_data(__pSsl, sslIndex, this);
829 __pSslKey = new Integer((int) __pSsl);
830 pthread_mutex_lock(&__mapMutex);
831 _Singleton::GetSslMap()->Add(*(__pSslKey), *(new Integer((int) sslIndex)));
832 pthread_mutex_unlock(&__mapMutex);
833 SysLog(NID_NET_SOCK, "__pSslKey : %d ", __pSslKey);
834 // SysLog(NID_NET_SOCK, " : %d ", _Singleton::GetSslMap()->GetCount());
836 SSL_set_verify(__pSsl, SSL_VERIFY_PEER, (int (*)(int, X509_STORE_CTX*)) _SecureSocketImpl::OnVerifyPeerCallback);
837 // verify certification depth is set to _SSL_VERIFY_DEPTH.
838 // Allows level 0: peer certificates.
839 // level 1: CA certificates.
840 // level 2: higher level CA certificates.
842 __sslDepth = _SSL_VERIFY_DEPTH;
843 SSL_set_verify_depth(__pSsl, __sslDepth);
846 __pThread = new (std::nothrow) Thread();
847 SysTryCatch(NID_NET_SOCK, __pThread != null, r = E_OUT_OF_MEMORY, r, "Memory allocation failed.");
849 r = __pThread->Construct(*this);
850 SysTryCatch(NID_NET_SOCK, r != E_OUT_OF_MEMORY, , r, "[E_OUT_OF_MEMORY] Memory allocation failed.");
851 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Failed to construct the thread.", GetErrorMessage(r));
854 r = __pThread->Start();
855 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Failed to start the thread.", GetErrorMessage(r));
858 SysLogException(NID_NET_SOCK, r, "[E_WOULD_BLOCK] Returned EWOULDBLOCK to connect the socket.");
860 __isConnectFired = false;
864 if (__sslVerify == SECURE_SOCKET_VERIFY_NONE)
866 SSL_set_verify(__pSsl, SSL_VERIFY_PEER, null);
869 r = SslConnect(sslError);
870 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Failed to connect the socket.", GetErrorMessage(r));
892 _SecureSocketImpl::Send(ByteBuffer& buffer)
894 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
896 result r = E_SUCCESS;
897 result res = E_SUCCESS;
902 unsigned int offset = buffer.GetPosition();
903 unsigned int length = buffer.GetRemaining();
905 SysTryReturnResult(NID_NET_SOCK, length > 0, E_INVALID_ARG, "Address is invalid.");
906 SysTryReturnResult(NID_NET_SOCK, __pSsl != null, E_CONNECTION_FAILED, "The Secure Socket is not connected.");
908 sentLength = SSL_write(__pSsl, (char*) (buffer.GetPointer() + offset), length);
912 sslError = SSL_get_error(__pSsl, sentLength);
914 // Error code mapping
917 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
921 case SSL_ERROR_SYSCALL: // I/o Error Occurred.
925 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
926 r = E_CONNECTION_FAILED;
929 case SSL_ERROR_WANT_READ: // Operation is not completed.
930 case SSL_ERROR_WANT_WRITE:
939 if (r != E_WOULD_BLOCK)
941 SysLogException(NID_NET_SOCK, r, "[%s] Failed to send the socket.", GetErrorMessage(r));
943 if (__isAsync == true)
945 __isWriteFired = true;
951 SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to send the socket.", GetErrorMessage(r));
952 if (__isAsync == true)
954 __isWriteFired = false;
955 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
956 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
957 SysTryCatch(NID_NET_SOCK, r != E_SUCCESS, r = E_WOULD_BLOCK, E_WOULD_BLOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
963 SysLog(NID_NET_SOCK, "Actually send byte : %d byte", sentLength);
965 if (__isAsync == true)
967 __isWriteFired = false;
968 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
969 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
970 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
973 r = buffer.SetPosition(offset + sentLength);
974 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM , E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
979 res = buffer.SetPosition(offset);
980 SysTryReturnResult(NID_NET_SOCK, res == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
986 _SecureSocketImpl::Send(void* pBuffer, int length, int& sentLength)
988 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
990 result r = E_SUCCESS;
994 if (!pBuffer || length <= 0)
997 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] The buffer is null or the length is invalid.");
1001 SysTryReturnResult(NID_NET_SOCK, __pSsl != null, E_CONNECTION_FAILED, "The Secure Socket is not connected.");
1003 sentLength = SSL_write(__pSsl, static_cast <char*>(pBuffer), length);
1005 if (sentLength <= 0)
1007 sslError = SSL_get_error(__pSsl, sentLength);
1009 // error code mapping
1012 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
1016 case SSL_ERROR_SYSCALL: // I/o Error Occurred.
1020 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
1021 r = E_CONNECTION_FAILED;
1024 case SSL_ERROR_WANT_READ: // Operation is not completed.
1025 case SSL_ERROR_WANT_WRITE:
1034 if (r != E_WOULD_BLOCK)
1036 SysLogException(NID_NET_SOCK, r, "[%s] Failed to send the socket.", GetErrorMessage(r));
1037 if (__isAsync == true)
1039 __isWriteFired = true;
1045 SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to send the socket.", GetErrorMessage(r));
1046 if (__isAsync == true)
1048 __isWriteFired = false;
1049 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1050 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
1051 SysTryReturnResult(NID_NET_SOCK, r != E_SUCCESS, E_WOULD_BLOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
1057 SysLog(NID_NET_SOCK, "Actually send byte : %d byte", sentLength);
1059 if (__isAsync == true)
1061 __isWriteFired = false;
1062 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1063 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
1064 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
1074 _SecureSocketImpl::Receive(ByteBuffer& buffer)
1076 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1078 result r = E_SUCCESS;
1079 result res = E_SUCCESS;
1084 unsigned int offset = buffer.GetPosition();
1085 unsigned int length = buffer.GetRemaining();
1087 SysTryReturnResult(NID_NET_SOCK, length > 0, E_INVALID_ARG, "Address is invalid.");
1088 SysTryReturnResult(NID_NET_SOCK, __pSsl != null, E_CONNECTION_FAILED, "The Secure Socket is not connected.");
1090 rcvdLength = SSL_read(__pSsl, (char*) (buffer.GetPointer() + offset), length);
1094 sslError = SSL_get_error(__pSsl, rcvdLength);
1096 // Error code mapping
1099 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
1103 case SSL_ERROR_SYSCALL: // I/o Error Occurred.
1107 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
1108 r = E_CONNECTION_FAILED;
1111 case SSL_ERROR_WANT_READ: // Operation is not completed.
1112 case SSL_ERROR_WANT_WRITE:
1121 if (r != E_WOULD_BLOCK)
1123 SysLogException(NID_NET_SOCK, r, "[%s] Failed to receive the socket.", GetErrorMessage(r));
1124 if (__isAsync == true)
1126 __isReadFired = true;
1132 SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to receive the socket.", GetErrorMessage(r));
1133 if (__isAsync == true)
1135 __isReadFired = false;
1141 SysLog(NID_NET_SOCK, "Actually receive byte : %d byte", rcvdLength);
1143 if (__isAsync == true)
1145 __isReadFired = false;
1148 r = buffer.SetPosition(offset + rcvdLength);
1149 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
1154 res = buffer.SetPosition(offset);
1155 SysTryReturnResult(NID_NET_SOCK, res == E_SUCCESS, E_SYSTEM, "Failed to Set the position.");
1161 _SecureSocketImpl::Receive(void* pBuffer, int length, int& rcvdLength)
1163 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1165 result r = E_SUCCESS;
1169 if (!pBuffer || length <= 0)
1172 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] The buffer is null or the length is invalid.");
1176 SysTryReturnResult(NID_NET_SOCK, __pSsl != null, E_CONNECTION_FAILED, "The Secure Socket is not connected.");
1178 rcvdLength = SSL_read(__pSsl, static_cast <char*>(pBuffer), length);
1182 sslError = SSL_get_error(__pSsl, rcvdLength);
1184 // Error code mapping
1187 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
1191 case SSL_ERROR_SYSCALL: // I/O Error occurred.
1195 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
1196 r = E_CONNECTION_FAILED;
1199 case SSL_ERROR_WANT_READ: // Operation is not completed.
1200 case SSL_ERROR_WANT_WRITE:
1209 if (r != E_WOULD_BLOCK)
1211 SysLogException(NID_NET_SOCK, r, "[%s] Failed to receive the socket.", GetErrorMessage(r));
1212 if (__isAsync == true)
1214 __isReadFired = true;
1220 SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to receive the socket.", GetErrorMessage(r));
1221 if (__isAsync == true)
1223 __isReadFired = false;
1229 SysLog(NID_NET_SOCK, "Actually receive byte : %d byte", rcvdLength);
1231 if (__isAsync == true)
1233 __isReadFired = false;
1243 _SecureSocketImpl::Ioctl(NetSocketIoctlCmd cmd, unsigned long& pArg)
1245 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1246 SysTryReturnResult(NID_NET_SOCK, (cmd == NET_SOCKET_FIONBIO), E_INVALID_ARG, "IoctlCmd is invalid.");
1248 result r = E_SUCCESS;
1252 if (cmd == NET_SOCKET_FIONBIO && pArg != 0)
1254 // command = FIONBIO;
1255 flag = fcntl(__socketFd, F_GETFL);
1256 err = fcntl(__socketFd, F_SETFL, flag | O_NONBLOCK);
1257 SysLog(NID_NET_SOCK, "Changed the Socket by non-blocking mode. [Fd: %d]", __socketFd);
1258 __isNonblock = true;
1260 else if (cmd == NET_SOCKET_FIONBIO && pArg == 0)
1262 // command = FIONBIO;
1263 flag = fcntl(__socketFd, F_GETFL);
1264 err = fcntl(__socketFd, F_SETFL, flag & ~O_NONBLOCK);
1265 SysLog(NID_NET_SOCK, "Changed the Socket by blocking mode. [Fd: %d]", __socketFd);
1266 __isNonblock = false;
1271 r = ConvertErrorToResult(errno);
1272 SysLogException(NID_NET_SOCK, r, "[%s] Failed to Ioctl the socket.", GetErrorMessage(r));
1279 _SecureSocketImpl::Bind(const NetEndPoint& localEP)
1281 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1283 result r = E_SUCCESS;
1285 NetAddressFamily af;
1286 unsigned long ipAddr = 0;
1287 unsigned short port = 0;
1288 Ip4Address* pIp4Addr = null;
1289 const _NetEndPointImpl* pLocalEPImpl = null;
1291 struct sockaddr_in localAddr;
1293 pLocalEPImpl = _NetEndPointImpl::GetInstance(localEP);
1295 af = pLocalEPImpl->GetNetAddressFamily();
1296 SysTryReturnResult(NID_NET_SOCK, af == NET_AF_IPV4, E_INVALID_ARG, "Address family is invalid.");
1298 pIp4Addr = static_cast <Ip4Address*>(pLocalEPImpl->GetAddress());
1299 r = pIp4Addr->GetAddress(ipAddr);
1300 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, E_INVALID_ARG, "Address is invalid.");
1302 port = pLocalEPImpl->GetPort();
1304 memset(&localAddr, 0, sizeof(localAddr));
1305 localAddr.sin_family = AF_INET;
1306 localAddr.sin_addr.s_addr = htonl(ipAddr);
1307 localAddr.sin_port = htons(port);
1309 if (bind(__socketFd, (struct sockaddr*) &localAddr, sizeof(localAddr)) < 0)
1311 r = ConvertErrorToResult(errno);
1312 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to bind the socket.");
1315 SysLog(NID_NET_SOCK, "bind the socket. [Fd : %d]", __socketFd);
1321 _SecureSocketImpl::Listen(int backLog)
1323 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1325 result r = E_SUCCESS;
1328 _SocketMethodFlag flag = FLAG_NONE;
1329 NetConnectionState connState = NET_CONNECTION_STATE_NONE;
1332 char* pDeviceName = null;
1333 const _ManagedNetConnectionImpl* pMNCConnImpl = null;
1334 long milliseconds = _THREAD_SLEEP_TIMER; // 2000 milliseconds (sleep time)
1337 bool isConnectionStarted = false;
1339 if (__pManagedNetConnection != null)
1341 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
1343 if (__isNonblock == false)
1345 SysLog(NID_NET_SOCK, "This socket is blocking mode.");
1347 pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
1352 connState = pMNCConnImpl->QueryConnectionState(deviceName);
1356 case NET_CONNECTION_STATE_STARTED:
1358 case NET_CONNECTION_STATE_RESUMED:
1360 case NET_CONNECTION_STATE_SUSPENDED:
1361 SysLog(NID_NET_SOCK, "Network is available.");
1363 if (deviceName.IsEmpty())
1365 SysLog(NID_NET_SOCK, "DeviceName is empty string. - Emulator Case");
1369 SysLog(NID_NET_SOCK, "DeviceName is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
1371 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
1372 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1374 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
1375 delete[] pDeviceName;
1378 ConvertErrorToResult(errno);
1379 SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Device Name binding is Failed.");
1383 err = listen(__socketFd, backLog);
1386 case NET_CONNECTION_STATE_STARTING:
1388 case NET_CONNECTION_STATE_NONE:
1390 case NET_CONNECTION_STATE_STOPPING:
1392 case NET_CONNECTION_STATE_STOPPED:
1393 SysLog(NID_NET_SOCK, "Network is not available.");
1397 SysLog(NID_NET_SOCK, "Should not come here.");
1401 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
1406 if (connState == NET_CONNECTION_STATE_STOPPED)
1408 r = E_INVALID_CONNECTION;
1409 SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
1415 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
1418 SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network is timeout. Try Again");
1423 Thread::Sleep(milliseconds);
1428 SysLog(NID_NET_SOCK, "This socket is non-blocking mode.");
1430 isConnectionStarted = __pManagedNetConnectionEventListener->GetStartedFlag();
1432 if (isConnectionStarted)
1434 err = listen(__socketFd, backLog);
1440 __pManagedNetConnectionEventListener->SetListenParams(__socketFd, backLog, flag);
1446 err = listen(__socketFd, backLog);
1451 r = ConvertErrorToResult(errno);
1453 if (r != E_WOULD_BLOCK)
1455 SysLogException(NID_NET_SOCK, r, "[%s] Failed to listen the socket.", GetErrorMessage(r));
1456 if (__isAsync == true)
1458 __isAcceptFired = true;
1464 SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to listen the socket.", GetErrorMessage(r));
1466 if (__isAsync == true)
1468 __isAcceptFired = false;
1469 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1470 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
1471 SysTryReturnResult(NID_NET_SOCK, r != E_SUCCESS, E_WOULD_BLOCK, "SocketFd : [%d], Set the socketEvent to attach all condition.", __socketFd);
1477 SysLog(NID_NET_SOCK, "Socket is listening. [Fd : %d, backLog : %d]", __socketFd, backLog);
1481 if (__isAsync == true)
1483 __isAcceptFired = false;
1484 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1485 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
1486 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach All condition.", __socketFd);
1496 _SecureSocketImpl::AcceptN(void)
1500 result r = E_SUCCESS;
1501 SecureSocket* pClientSocket = null;
1502 _SecureSocketImpl* pClientSocketImpl = null;
1505 int clientFd = INVALID_HANDLE;
1506 unsigned int clientSize = 0;
1507 struct sockaddr_in clientAddr;
1508 char* pCaPath = null;
1510 SysTryReturn(NID_NET_SOCK, __isClosed == false, null, E_INVALID_STATE, "[E_INVALID_STATE] Socket is already closed.");
1512 pthread_mutex_lock(&__mapMutex);
1514 clientSize = sizeof(clientAddr);
1516 clientFd = accept(__socketFd, (struct sockaddr*) &clientAddr, &clientSize);
1520 r = ConvertErrorToResult(errno);
1522 if (r != E_WOULD_BLOCK)
1524 SysLogException(NID_NET_SOCK, r, "[%s] Failed to accept the socket.", GetErrorMessage(r));
1529 SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to accept the socket.", GetErrorMessage(r));
1534 if (__isAsync == true)
1536 __isAcceptFired = false;
1537 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1538 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
1539 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach All condition.", __socketFd);
1542 // Implementation - new Socket
1543 pClientSocket = new (std::nothrow) SecureSocket();
1544 SysTryCatch(NID_NET_SOCK, pClientSocket != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Secure Socket Memory allocation failed.");
1546 pClientSocketImpl = new (std::nothrow) _SecureSocketImpl(pClientSocket);
1547 SysTryCatch(NID_NET_SOCK, pClientSocketImpl != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1549 // Set new Socket Event
1550 pClientSocketImpl->__pSecureSocketEvent = new (std::nothrow) _SecureSocketEvent();
1551 SysTryCatch(NID_NET_SOCK, pClientSocketImpl->__pSecureSocketEvent != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1553 r = pClientSocketImpl->__pSecureSocketEvent->Construct(pClientSocketImpl);
1554 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to construct the Secure Socket event.");
1556 if (__isLoadVerify == false)
1558 // Set default CA path.
1559 String caPath = _CertService::GetCertificateCrtFilePath();
1560 SysLog(NID_NET_SOCK, "CA Path(%ls)", caPath.GetPointer());
1562 pCaPath = _StringConverter::CopyToCharArrayN(caPath);
1563 SysTryCatch(NID_NET_SOCK, pCaPath != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1565 sslError = SSL_CTX_load_verify_locations(__pSslCtx, pCaPath, null);
1566 SysTryCatch(NID_NET_SOCK, sslError >= 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to verify the trusted CA list.");
1568 sslError = SSL_CTX_set_default_verify_paths(__pSslCtx);
1569 SysTryCatch(NID_NET_SOCK, sslError >= 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set the default verify paths.");
1571 __isLoadVerify = true;
1577 pClientSocketImpl->__pSsl = SSL_new(__pSslCtx);
1578 SysTryCatch(NID_NET_SOCK, pClientSocketImpl->__pSsl != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create the SSL Object.");
1580 SSL_set_fd(pClientSocketImpl->__pSsl, clientFd);
1582 SSL_set_options(pClientSocketImpl->__pSsl, SSL_OP_ALL);
1584 SSL_set_tmp_rsa_callback(pClientSocketImpl->__pSsl, OnTmpRsaCallback);
1586 //if (__sslVerify == SECURE_SOCKET_VERIFY_NONE)
1588 // SSL_set_verify(pClientSocketImpl->__pSsl, SSL_VERIFY_PEER, null);
1591 if (__isAsync == true || __isNonblock == true)
1593 // verify certification depth is set to _SSL_VERIFY_DEPTH.
1594 // Allows level 0: peer certificates.
1595 // level 1: CA certificates.
1596 // level 2: higher level CA certificates.
1598 __sslDepth = _SSL_VERIFY_DEPTH;
1599 SSL_set_verify_depth(pClientSocketImpl->__pSsl, __sslDepth);
1601 SSL_set_mode(pClientSocketImpl->__pSsl, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1603 if ((_Singleton::GetInitialized() == true) && (__pSslKey))
1605 _Singleton::GetSslMap()->Remove(*__pSslKey, true);
1608 sslIndex = SSL_get_ex_new_index(0, (char*) "_SecureSocketImpl index", null, null, null);
1609 SysLog(NID_NET_SOCK, "SSL index(%d).", sslIndex);
1611 SSL_set_ex_data(pClientSocketImpl->__pSsl, sslIndex, this);
1613 __pSslKey = new Integer((int) pClientSocketImpl->__pSsl);
1615 _Singleton::GetSslMap()->Add(*(__pSslKey), *(new Integer((int) sslIndex)));
1618 r = SslAccept(pClientSocketImpl->__pSsl, sslError);
1619 if ((sslError == SSL_ERROR_WANT_READ) || (sslError == SSL_ERROR_WANT_WRITE))
1623 else if ((r != E_WOULD_BLOCK) && (r != E_SUCCESS))
1625 SysLogException(NID_NET_SOCK, r, "[%s] Failed to accept the socket.", GetErrorMessage(r));
1631 r = SslAccept(pClientSocketImpl->__pSsl, sslError);
1634 SysLogException(NID_NET_SOCK, r, "[%s] Failed to accept the socket.", GetErrorMessage(r));
1639 // New socket creation complete!
1640 pClientSocketImpl->__socketFd = clientFd;
1641 pClientSocketImpl->__isClosed = false;
1642 pClientSocketImpl->__isNonblock = this->__isNonblock;
1643 pClientSocketImpl->__socketEventType = this->__socketEventType;
1644 pClientSocketImpl->__isServer = false;
1645 pClientSocketImpl->__isConnectFired = true;
1646 pClientSocketImpl->__protocolFamily = this->__protocolFamily;
1647 pClientSocketImpl->__socketType = this->__socketType;
1648 pClientSocketImpl->__protocol = this->__protocol;
1649 pClientSocketImpl->__pGMainContext = this->__pGMainContext;
1650 pClientSocketImpl->__isConstructed = true;
1651 //pClientSocketImpl->__pSsl = this->__pSsl;
1652 pClientSocketImpl->__isSslConnected = true;
1653 pClientSocketImpl->__isRunFinished = true;
1655 pClientSocket->__pSecureSocketImpl = pClientSocketImpl;
1657 SysLog(NID_NET_SOCK, "New Secure Socket(Child Socket) is created by Server Secure Socket. [ServerFd : %d] [ChildFd : %d]", pClientSocket->__pSecureSocketImpl->__socketFd, __socketFd);
1659 if (__isAsync == true)
1661 pClientSocketImpl->__pGlibSocketInfo = new (std::nothrow) _GlibSecureSocketInfo();
1662 SysTryCatch(NID_NET_SOCK, __pGlibSocketInfo, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1664 r = pClientSocketImpl->__pGlibSocketInfo->SetSocketEvent(pClientSocketImpl, clientFd);
1665 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
1666 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach All condition to ClientFd.", clientFd);
1669 pthread_mutex_unlock(&__mapMutex);
1671 return pClientSocket;
1674 pthread_mutex_unlock(&__mapMutex);
1676 if (pClientSocket != null)
1678 delete pClientSocket;
1679 pClientSocket = null;
1682 if (pCaPath != null)
1693 _SecureSocketImpl::Close(void)
1695 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1697 result r = E_SUCCESS;
1699 int sockFd = __socketFd;
1700 IEnumeratorT<ISecureSocketEventListener*>* pEnum = null;
1701 ISecureSocketEventListener* pSecureSocketEventListener = null;
1703 pEnum = __secureSocketEventListenerList.GetEnumeratorN();
1707 while (pEnum->MoveNext() == E_SUCCESS)
1709 r = pEnum->GetCurrent(pSecureSocketEventListener);
1711 if (pSecureSocketEventListener != null)
1713 r = __pSecureSocketEvent->RemoveListener(*pSecureSocketEventListener);
1714 r = __secureSocketEventListenerList.Remove(const_cast<ISecureSocketEventListener*>(pSecureSocketEventListener));
1720 if (__pGlibSocketInfo != null)
1722 delete __pGlibSocketInfo;
1723 __pGlibSocketInfo = null;
1726 if (__socketFd > INVALID_HANDLE)
1728 if (close(__socketFd) < 0)
1730 r = ConvertErrorToResult(errno);
1731 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to close the socket.");
1734 SysLog(NID_NET_SOCK, "Socket is closed. [Fd : %d]", sockFd);
1737 __socketFd = INVALID_HANDLE;
1744 _SecureSocketImpl::GetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, int& optionValue) const
1746 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1748 result r = E_SUCCESS;
1753 unsigned int optLen = 0;
1755 struct timeval timeout;
1757 char* pVersion = null;
1758 char* pCipher = null;
1760 switch (optionLevel)
1762 case NET_SOCKET_IPPROTO_TCP:
1763 optLevel = IPPROTO_TCP;
1765 if (((optionName == NET_SOCKET_SO_SSLVERSION) || (optionName == NET_SOCKET_SO_SSLCIPHERSUITEID) ||
1766 (optionName == NET_SOCKET_SO_SSLCERTVERIFY) || (optionName == NET_SOCKET_SO_SSLCLIENTCERTVERIFY) || (optionName == NET_SOCKET_SO_SSLCERTID)))
1769 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1774 case NET_SOCKET_IPPROTO_IP:
1775 optLevel = IPPROTO_IP;
1777 if (((optionName == NET_SOCKET_SO_SSLVERSION) || (optionName == NET_SOCKET_SO_SSLCIPHERSUITEID) ||
1778 (optionName == NET_SOCKET_SO_SSLCERTVERIFY) || (optionName == NET_SOCKET_SO_SSLCLIENTCERTVERIFY) || (optionName == NET_SOCKET_SO_SSLCERTID)))
1781 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1786 case NET_SOCKET_SOL_SOCKET:
1787 optLevel = SOL_SOCKET;
1792 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1798 case NET_SOCKET_SO_SSLVERSION:
1802 optionValue = __sslVersion;
1806 pVersion = (char*) SSL_get_version(__pSsl);
1807 SysTryReturn(NID_NET_SOCK, pVersion != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get the option value.");
1809 if (strcmp(pVersion, "SSLv3") == 0)
1811 optionValue = NET_SOCK_SSL_VERSION_SSLV3;
1813 else if (strcmp(pVersion, "TLSv1") == 0)
1815 optionValue = NET_SOCK_SSL_VERSION_TLSV1;
1820 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to get the option value.");
1826 case NET_SOCKET_SO_SSLCIPHERSUITEID:
1830 optionValue = __sslCipherSuiteId;
1834 pCipher = (char*) SSL_get_cipher(__pSsl);
1835 SysTryReturn(NID_NET_SOCK, pCipher != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get the option value.");
1837 if (strcmp(pCipher, "RC4-MD5") == 0)
1839 optionValue = NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_MD5;
1841 else if (strcmp(pCipher, "RC4-SHA") == 0)
1843 optionValue = NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_SHA;
1845 else if (strcmp(pCipher, "DES-CBC-SHA") == 0)
1847 optionValue = NET_SOCK_TLS_SSL_RSA_WITH_DES_CBC_SHA;
1849 else if (strcmp(pCipher, "DES-CBC3-SHA") == 0)
1851 optionValue = NET_SOCK_TLS_SSL_RSA_WITH_3DES_EDE_CBC_SHA;
1853 else if (strcmp(pCipher, "AES128-SHA") == 0)
1855 optionValue = NET_SOCK_TLS_SSL_RSA_WITH_AES_128_CBC_SHA;
1857 else if (strcmp(pCipher, "EXP-DES-CBC-SHA") == 0)
1859 optionValue = NET_SOCK_TLS_SSL_RSA_EXPORT_WITH_DES40_CBC_SHA;
1864 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to get the option value.");
1870 case NET_SOCKET_TCP_NODELAY:
1871 optName = TCP_NODELAY;
1874 case NET_SOCKET_TCP_MAXSEG:
1875 optName = TCP_MAXSEG;
1878 case NET_SOCKET_IP_TTL:
1882 case NET_SOCKET_IP_TOS:
1886 case NET_SOCKET_SO_KEEPALIVE:
1887 optName = SO_KEEPALIVE;
1890 case NET_SOCKET_SO_OOBINLINE:
1891 optName = SO_OOBINLINE;
1894 case NET_SOCKET_SO_RCVBUF:
1895 optName = SO_RCVBUF;
1898 case NET_SOCKET_SO_RCVTIMEO:
1899 optName = SO_RCVTIMEO;
1902 case NET_SOCKET_SO_REUSEADDR:
1903 optName = SO_REUSEADDR;
1906 case NET_SOCKET_SO_SNDBUF:
1907 optName = SO_SNDBUF;
1910 case NET_SOCKET_SO_SNDTIMEO:
1911 optName = SO_SNDTIMEO;
1914 case NET_SOCKET_SO_TYPE:
1919 r = E_UNSUPPORTED_OPTION;
1920 SysLogException(NID_NET_SOCK, r, "[E_UNSUPPORTED_OPTION] %d is unsupported", optionName);
1924 if (optName == SO_RCVTIMEO || optName == SO_SNDTIMEO)
1926 optLen = sizeof(timeout);
1927 err = getsockopt(__socketFd, optLevel, optName, &timeout, &optLen);
1928 optionValue = (timeout.tv_sec * 1000) + (timeout.tv_usec / 1000);
1932 optLen = sizeof(optionValue);
1933 err = getsockopt(__socketFd, optLevel, optName, (int*) &optionValue, &optLen);
1938 r = ConvertErrorToResult(errno);
1939 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the option value.", GetErrorMessage(r));
1946 _SecureSocketImpl::SetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, int optionValue)
1948 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1949 SysTryReturnResult(NID_NET_SOCK, __pSslCtx != null, E_INVALID_ARG, "The SSL context is null.");
1951 result r = E_SUCCESS;
1954 int optLevel = NET_SOCKET_OPTLEVEL_NONE;
1955 int optName = NET_SOCKET_OPTNAME_NONE;
1956 unsigned int optLen = 0;
1958 struct timeval timeout;
1960 char* pCipher = null;
1962 switch (optionLevel)
1964 case NET_SOCKET_IPPROTO_TCP:
1965 optLevel = IPPROTO_TCP;
1967 if (((optionName == NET_SOCKET_SO_SSLVERSION) || (optionName == NET_SOCKET_SO_SSLCIPHERSUITEID) ||
1968 (optionName == NET_SOCKET_SO_SSLCERTVERIFY) || (optionName == NET_SOCKET_SO_SSLCLIENTCERTVERIFY) || (optionName == NET_SOCKET_SO_SSLCERTID)))
1971 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1976 case NET_SOCKET_IPPROTO_IP:
1977 optLevel = IPPROTO_IP;
1979 if (((optionName == NET_SOCKET_SO_SSLVERSION) || (optionName == NET_SOCKET_SO_SSLCIPHERSUITEID) ||
1980 (optionName == NET_SOCKET_SO_SSLCERTVERIFY) || (optionName == NET_SOCKET_SO_SSLCLIENTCERTVERIFY) || (optionName == NET_SOCKET_SO_SSLCERTID)))
1983 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1988 case NET_SOCKET_SOL_SOCKET:
1989 optLevel = SOL_SOCKET;
1994 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
2000 case NET_SOCKET_SO_SSLVERSION:
2002 SSL_CTX_free(__pSslCtx);
2005 SSL_load_error_strings();
2006 ERR_load_BIO_strings();
2007 OpenSSL_add_all_algorithms();
2008 CRYPTO_malloc_init();
2009 SSLeay_add_all_algorithms();
2010 ERR_load_crypto_strings();
2012 if (optionValue == NET_SOCK_SSL_VERSION_SSLV3)
2014 __pSslMethod = (SSL_METHOD*) SSLv3_method();
2015 __sslVersion = NET_SOCK_SSL_VERSION_SSLV3;
2017 else if (optionValue == NET_SOCK_SSL_VERSION_TLSV1)
2019 __pSslMethod = (SSL_METHOD*) TLSv1_method();
2020 __sslVersion = NET_SOCK_SSL_VERSION_TLSV1;
2023 __pSslCtx = SSL_CTX_new(__pSslMethod);
2024 SysTryCatch(NID_NET_SOCK, __pSslCtx != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create the SSL Context.");
2028 case NET_SOCKET_SO_SSLCIPHERSUITEID:
2029 if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_MD5)
2031 pCipher = (char*) "RC4-MD5";
2032 __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_MD5;
2034 else if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_SHA)
2036 pCipher = (char*) "RC4-SHA";
2037 __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_SHA;
2039 else if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_DES_CBC_SHA)
2041 pCipher = (char*) "DES-CBC-SHA";
2042 __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_DES_CBC_SHA;
2044 else if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_3DES_EDE_CBC_SHA)
2046 pCipher = (char*) "DES-CBC3-SHA";
2047 __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_3DES_EDE_CBC_SHA;
2049 else if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_AES_128_CBC_SHA)
2051 pCipher = (char*) "AES128-SHA";
2052 __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_AES_128_CBC_SHA;
2054 else if (optionValue == NET_SOCK_TLS_SSL_RSA_EXPORT_WITH_DES40_CBC_SHA)
2056 pCipher = (char*) "EXP-DES-CBC-SHA";
2057 __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_EXPORT_WITH_DES40_CBC_SHA;
2059 else if (optionValue == NET_SOCK_TLS_SSL_SYSTEM_DEFAULT_CIPHERSUITES)
2061 pCipher = (char*) "RC4-MD5:RC4-SHA:DES-CBC-SHA:DES-CBC3-SHA:AES128-SHA:EXP-DES-CBC-SHA";
2062 __sslCipherSuiteId = NET_SOCK_TLS_SSL_SYSTEM_DEFAULT_CIPHERSUITES;
2065 if (SSL_CTX_set_cipher_list(__pSslCtx, pCipher) <= 0)
2067 __sslCipherSuiteId = NET_SOCK_TLS_SSL_NULL_WITH_NULL_NULL;
2068 SysLog(NID_NET_SOCK, "Failed to the Setting Cipher.");
2074 case NET_SOCKET_SO_SSLCLIENTCERTVERIFY:
2076 if (__isAsync == true || __isNonblock == true)
2078 SSL_CTX_set_verify(__pSslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE,
2079 (int (*)(int, X509_STORE_CTX*)) _SecureSocketImpl::OnVerifyClientCallback);
2083 SSL_CTX_set_verify(__pSslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, null);
2086 __sslVerify = SECURE_SOCKET_VERIFY_ENABLE;
2089 case NET_SOCKET_SO_SSLCERTVERIFY:
2091 if (__isAsync == true || __isNonblock == true)
2093 if (optionValue > 0) // Enable SSL Verification
2095 __sslVerify = SECURE_SOCKET_VERIFY_ENABLE;
2097 else if (optionValue == 0) // Disable SSL Verification
2099 __sslVerify = SECURE_SOCKET_VERIFY_DISABLE;
2104 if (optionValue > 0) // Enable SSL Verification
2106 __sslVerify = SECURE_SOCKET_VERIFY_ENABLE;
2107 SSL_CTX_set_verify(__pSslCtx, SSL_VERIFY_PEER, null);
2109 else if (optionValue == 0) // Disable SSL Verification
2111 __sslVerify = SECURE_SOCKET_VERIFY_DISABLE;
2112 SSL_CTX_set_verify(__pSslCtx, SSL_VERIFY_NONE, null);
2117 case NET_SOCKET_SO_SSLCERTID:
2120 EVP_PKEY* pKey = null;
2122 _CertServiceProxy* pCertProxy = null;
2123 pCertProxy = _CertServiceProxy::GetInstance();
2124 SysTryReturnResult(NID_NET_SOCK, pCertProxy != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
2126 unique_ptr<_CertInfo, _CertInfoDeleter> pCertInfo(pCertProxy->GetUserCertificateByCertIdN(optionValue, _CERT_ENC_TYPE_PEM));
2127 r = GetLastResult();
2128 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS && pCertInfo != null, E_SYSTEM, "Certificate(%d) is not found.", optionValue);
2130 BIO* pNewBIoCert = BIO_new(BIO_s_mem());
2131 unique_ptr<BIO, _BIoDeleter> pBIoCert(pNewBIoCert);
2132 SysTryReturnResult(NID_NET_SOCK, pBIoCert != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
2134 BIO_write(pNewBIoCert, (const void*)pCertInfo->certificate, pCertInfo->certLength);
2135 pCert = PEM_read_bio_X509(pNewBIoCert, null, 0, null);
2136 SysTryReturnResult(NID_NET_SOCK, pCert != null, E_SYSTEM, "Failed to read Certificate(%d).", optionValue);
2138 if (SSL_CTX_use_certificate(__pSslCtx, pCert) <= 0)
2141 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to load the certificate.");
2145 BIO* pNewBIoKey = BIO_new(BIO_s_mem());
2146 unique_ptr<BIO, _BIoDeleter> pBIoKey(pNewBIoKey);
2147 SysTryReturnResult(NID_NET_SOCK, pBIoKey != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
2149 BIO_write(pNewBIoKey, (const void*)pCertInfo->privatekey, pCertInfo->privateKeyLen);
2150 pKey = PEM_read_bio_PrivateKey(pNewBIoKey, null, 0, null);
2151 SysTryReturnResult(NID_NET_SOCK, pKey != null, E_SYSTEM, "Failed to read Private Key.");
2153 if (SSL_CTX_use_PrivateKey(__pSslCtx, pKey) <= 0)
2156 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to load the private key.");
2160 if (SSL_CTX_check_private_key(__pSslCtx) <= 0)
2163 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to check the private key.");
2167 SysLog(NID_NET_SOCK, "### Certificate loaded successfully. ###");
2171 case NET_SOCKET_TCP_NODELAY:
2172 optName = TCP_NODELAY;
2175 case NET_SOCKET_TCP_MAXSEG:
2176 optName = TCP_MAXSEG;
2179 case NET_SOCKET_IP_TTL:
2183 case NET_SOCKET_IP_TOS:
2187 case NET_SOCKET_SO_KEEPALIVE:
2188 optName = SO_KEEPALIVE;
2191 case NET_SOCKET_SO_OOBINLINE:
2192 optName = SO_OOBINLINE;
2195 case NET_SOCKET_SO_RCVBUF:
2196 optName = SO_RCVBUF;
2199 case NET_SOCKET_SO_RCVTIMEO:
2200 optName = SO_RCVTIMEO;
2202 timeout.tv_sec = optionValue / 1000;
2203 timeout.tv_usec = (optionValue % 1000) * 1000;
2206 case NET_SOCKET_SO_REUSEADDR:
2207 optName = SO_REUSEADDR;
2210 case NET_SOCKET_SO_SNDBUF:
2211 optName = SO_SNDBUF;
2214 case NET_SOCKET_SO_SNDTIMEO:
2215 optName = SO_SNDTIMEO;
2217 timeout.tv_sec = optionValue / 1000;
2218 timeout.tv_usec = (optionValue % 1000) * 1000;
2222 r = E_UNSUPPORTED_OPTION;
2223 SysLogException(NID_NET_SOCK, r, "[E_UNSUPPORTED_OPTION] %d is unsupported", optionName);
2227 if (optName == SO_RCVTIMEO || optName == SO_SNDTIMEO)
2229 optLen = sizeof(timeout);
2230 err = setsockopt(__socketFd, optLevel, optName, (struct timeval*) &timeout, optLen);
2234 optLen = sizeof(optionValue);
2235 err = setsockopt(__socketFd, optLevel, optName, (int*) &optionValue, optLen);
2240 r = ConvertErrorToResult(errno);
2241 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the linger option value.", GetErrorMessage(r));
2251 _SecureSocketImpl::AsyncSelectByListener(unsigned long socketEventType)
2253 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2255 result r = E_SUCCESS;
2257 if (__pGlibSocketInfo == null)
2259 __pGlibSocketInfo = new (std::nothrow) _GlibSecureSocketInfo();
2260 SysTryReturnResult(NID_NET_SOCK, __pGlibSocketInfo, E_OUT_OF_MEMORY, "Memory allocation failed.");
2263 SysLog(NID_NET_SOCK, "Socket set the socketEvent by AsyncSelectByListener. [Fd : %d]", __socketFd);
2265 __socketEventType = socketEventType;
2266 __isNonblock = true;
2273 _SecureSocketImpl::AddSecureSocketListener(ISecureSocketEventListener& listener)
2275 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2277 result r = E_SUCCESS;
2279 _EventDispatcher* pEventDispatcher = _EventDispatcher::GetCurrentEventDispatcher();
2280 SysTryReturnResult(NID_NET_SOCK, pEventDispatcher, E_SYSTEM, "GetCurrentEventDispatcher is null.");
2282 __pGMainContext = pEventDispatcher->GetGMainContext();
2283 SysTryReturnResult(NID_NET_SOCK, __pGMainContext, E_SYSTEM, "GetGMainContext is null.");
2285 r = __pSecureSocketEvent->AddListener(listener, true);
2286 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to add the listener.");
2288 r = __secureSocketEventListenerList.Add(&listener);
2289 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to add the listener to the list.");
2295 _SecureSocketImpl::RemoveSecureSocketListener(ISecureSocketEventListener& listener)
2297 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2299 result r = E_SUCCESS;
2301 r = __pSecureSocketEvent->RemoveListener(listener);
2302 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to remove the listener.");
2304 r = __secureSocketEventListenerList.Remove(&listener);
2305 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to remove the listener to the list.");
2311 _SecureSocketImpl::GetSecureSocketFd(void)
2313 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2319 _SecureSocketImpl::Run(void)
2321 result r = E_SUCCESS;
2326 r = SslConnect(sslError);
2327 if ((sslError == SSL_ERROR_WANT_READ) || (sslError == SSL_ERROR_WANT_WRITE) || (sslError == SSL_ERROR_WANT_CONNECT))
2332 SysLog(NID_NET_SOCK, "Worker thread finished. - SslConnect::Run()");
2334 if (__isAsync == true)
2336 __isRunFinished = true;
2337 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
2338 SysTryReturn(NID_NET_SOCK, r == E_SUCCESS, null, E_OUT_OF_MEMORY, "Memory allocation failed.");
2339 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach All condition.", __socketFd);
2346 _SecureSocketImpl::GetSecureSocket(void) const
2348 return __pSecureSocket;
2352 _SecureSocketImpl::GetInstance(SecureSocket& secureSocket)
2354 return secureSocket.__pSecureSocketImpl;
2357 const _SecureSocketImpl*
2358 _SecureSocketImpl::GetInstance(const SecureSocket& secureSocket)
2360 return secureSocket.__pSecureSocketImpl;
2364 _SecureSocketImpl::Dispose(void)
2366 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2368 result r = E_SUCCESS;
2371 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to close the socket.");
2380 _SecureSocketImpl::OnGioEventCallback(GIOChannel* pSource, GIOCondition condition, gpointer pUserData)
2382 SysLog(NID_NET_SOCK, "### OnGioEventCallback ###");
2384 result errorCode = E_SUCCESS;
2385 GIOStatus status = G_IO_STATUS_NORMAL;
2387 gsize bytes_read = 0;
2389 char peekBuf = '\0';
2392 int timerId = INVALID_HANDLE;
2395 _SecureUserData* pRecvUserData = (_SecureUserData*) pUserData;
2397 _SecureSocketEventArg* pEventArg = null;
2399 _SecureSocketImpl* pSecureSocketImpl = static_cast <_SecureSocketImpl*>(pRecvUserData->pSecureSocketImpl);
2400 GSource* pGSource = static_cast <GSource*>(pRecvUserData->pGSource);
2402 SysLog(NID_NET_SOCK, "====> [Event] OnGioEventCallback : All GIO event is received.(%d).", condition);
2404 if (condition & G_IO_ERR)
2406 SysLog(NID_NET_SOCK, "====> [Event] Socket event is received.(G_IO_ERR)");
2408 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSecureSocketImpl->__isCloseFired == false))
2410 // Fire the event(NET_SOCKET_EVENT_CLOSE)
2411 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2412 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2413 // G_IO_ERROR Converting
2414 status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
2415 errorCode = ConvertGioStatus(status);
2416 pEventArg->SetError(errorCode);
2417 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2419 g_source_set_callback(pGSource, null, null, null);
2420 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
2426 if (pSecureSocketImpl->__isServer) // For Server
2428 SysLog(NID_NET_SOCK, "====> [Event] This is secure socket server");
2430 if (condition & G_IO_IN)
2432 SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received(G_IO_IN).");
2434 struct pollfd fds[1];
2435 fds[0].fd = pSecureSocketImpl->__socketFd;
2436 fds[0].events = POLLRDHUP;
2438 error = poll(fds, 1, 0);
2439 SysTryCatch(NID_NET_SOCK, error != -1, , null, "Failed to the poll");
2441 if (fds[0].revents & POLLRDHUP)
2443 SysLog(NID_NET_SOCK, "====> Socket is not available.(POLLRDHUP)");
2445 ioctl(pSecureSocketImpl->__socketFd, FIONREAD, &readSize);
2446 SysLog(NID_NET_SOCK, "Amount of data that can be read : %d bytes. [Fd: %d]", readSize, pSecureSocketImpl->__socketFd);
2450 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSecureSocketImpl->__isCloseFired == false))
2452 //Fire the event(NET_SOCKET_EVENT_CLOSE)
2453 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2454 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2455 // G_IO_ERROR Converting
2456 status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
2457 errorCode = ConvertGioStatus(status);
2458 pEventArg->SetError(errorCode);
2459 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2461 g_source_set_callback(pGSource, null, null, null);
2462 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
2469 connStatus = SSL_peek(pSecureSocketImpl->__pSsl, (char*) &peekBuf, 1);
2470 SysLog(NID_NET_SOCK, "Connection Status : %d.", connStatus);
2472 sslError = SSL_get_error(pSecureSocketImpl->__pSsl, connStatus);
2474 // Error code mapping
2477 case SSL_ERROR_ZERO_RETURN:
2478 SysLog(NID_NET_SOCK, "Connection closed by peer : %d.", sslError);
2482 SysLog(NID_NET_SOCK, "Connection is active : %d.", sslError);
2486 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2487 (pSecureSocketImpl->__isCloseFired == false) && (connStatus == 0))
2489 // Fire the event(NET_SOCKET_EVENT_CLOSE)
2490 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2491 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2492 // G_IO_ERROR Converting
2493 //status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
2494 //errorCode = ConvertGioStatus(status);
2495 pEventArg->SetError(E_SUCCESS);
2496 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2498 g_source_set_callback(pGSource, null, null, null);
2499 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
2507 SysLog(NID_NET_SOCK, "====> SOCKET is available.(Not POLLRDHUP)");
2509 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_ACCEPT) && (pSecureSocketImpl->__isAcceptFired == false) &&
2510 (pSecureSocketImpl->__isCloseFired == false))
2512 //Fire the event(NET_SOCKET_EVENT_ACCEPT)
2513 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_ACCEPT);
2514 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2515 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2522 if (condition & G_IO_OUT)
2524 SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_OUT).");
2530 SysLog(NID_NET_SOCK, "====> [Event] This is Secure socket client");
2532 if (condition & G_IO_IN)
2534 SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_IN).");
2536 if (pSecureSocketImpl->__isRunFinished == true)
2538 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2539 (pSecureSocketImpl->__isConnectFailed == true) && (pSecureSocketImpl->__isCloseFired == false))
2541 // Fire the event(NET_SOCKET_EVENT_CLOSE)
2542 errorCode = E_SYSTEM;
2543 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2544 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2545 pEventArg->SetError(errorCode);
2546 pSecureSocketImpl->__isConnectFailed = false;
2547 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2549 g_source_set_callback(pGSource, null, null, null);
2550 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
2555 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2556 (pSecureSocketImpl->__isClientNoCert == true) && (pSecureSocketImpl->__isCloseFired == false))
2558 //Fire the event(NET_SOCKET_EVENT_CLOSE)
2559 errorCode = E_NO_CERTIFICATE;
2560 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2561 pEventArg->SetError(errorCode);
2562 pSecureSocketImpl->__isClientNoCert = false;
2563 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2565 g_source_set_callback(pGSource, null, null, null);
2566 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
2571 struct pollfd fds[1];
2572 fds[0].fd = pSecureSocketImpl->__socketFd;
2573 fds[0].events = POLLRDHUP;
2575 error = poll(fds, 1, 0);
2576 SysTryCatch(NID_NET_SOCK, error != -1, , null, "Failed to the poll");
2578 if (fds[0].revents & POLLRDHUP)
2580 SysLog(NID_NET_SOCK, "====> Socket is not available.(POLLRDHUP)");
2582 ioctl(pSecureSocketImpl->__socketFd, FIONREAD, &readSize);
2583 SysLog(NID_NET_SOCK, "Amount of data that can be read : %d bytes. [Fd: %d]", readSize,
2584 pSecureSocketImpl->__socketFd);
2588 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2589 (pSecureSocketImpl->__isCloseFired == false))
2591 //Fire the event(NET_SOCKET_EVENT_CLOSE)
2592 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2593 // G_IO_ERROR Converting
2594 status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
2595 errorCode = ConvertGioStatus(status);
2596 pEventArg->SetError(errorCode);
2597 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2599 g_source_set_callback(pGSource, null, null, null);
2600 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
2607 connStatus = SSL_peek(pSecureSocketImpl->__pSsl, (char*) &peekBuf, 1);
2608 SysLog(NID_NET_SOCK, "Connection Status : %d.", connStatus);
2610 sslError = SSL_get_error(pSecureSocketImpl->__pSsl, connStatus);
2612 // Error code mapping
2615 case SSL_ERROR_ZERO_RETURN:
2616 SysLog(NID_NET_SOCK, "Connection closed by peer : %d.", sslError);
2620 SysLog(NID_NET_SOCK, "Connection is active : %d.", sslError);
2624 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_READ) &&
2625 (pSecureSocketImpl->__isConnectFired == true) && (pSecureSocketImpl->__isReadFired == false) &&
2626 (pSecureSocketImpl->__isCloseFired == false) && (connStatus > 0))
2628 // Fire the event(NET_SOCKET_EVENT_READ)
2629 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_READ);
2630 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2631 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2636 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2637 (pSecureSocketImpl->__isCloseFired == false) && (connStatus == 0))
2639 // Fire the event(NET_SOCKET_EVENT_CLOSE)
2640 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2641 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2642 // G_IO_ERROR Converting
2643 //status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
2644 //errorCode = ConvertGioStatus(status);
2645 pEventArg->SetError(E_SUCCESS);
2646 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2648 g_source_set_callback(pGSource, null, null, null);
2649 SysLog(NID_NET_SOCK, "### set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
2657 SysLog(NID_NET_SOCK, "====> Socket is available.(Not POLLRDHUP)");
2659 connStatus = SSL_peek(pSecureSocketImpl->__pSsl, (char*) &peekBuf, 1);
2660 SysLog(NID_NET_SOCK, "Connection Status : %d.", connStatus);
2662 sslError = SSL_get_error(pSecureSocketImpl->__pSsl, connStatus);
2664 // Error code mapping
2667 case SSL_ERROR_ZERO_RETURN:
2668 SysLog(NID_NET_SOCK, "Connection closed by peer : %d.", sslError);
2672 SysLog(NID_NET_SOCK, "Connection is active : %d.", sslError);
2676 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_READ) &&
2677 (pSecureSocketImpl->__isConnectFired == true) && (pSecureSocketImpl->__isReadFired == false) &&
2678 (pSecureSocketImpl->__isCloseFired == false) && (connStatus > 0))
2680 //Fire the event(NET_SOCKET_EVENT_READ)
2681 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_READ);
2682 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2683 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2688 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2689 (pSecureSocketImpl->__isCloseFired == false) && (connStatus == 0))
2691 // Fire the event(NET_SOCKET_EVENT_CLOSE)
2692 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2693 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2694 // G_IO_ERROR Converting
2695 //status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
2696 //errorCode = ConvertGioStatus(status);
2697 pEventArg->SetError(E_SUCCESS);
2698 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2700 g_source_set_callback(pGSource, null, null, null);
2701 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
2709 if (condition & G_IO_OUT)
2711 SysLog(NID_NET_SOCK, "====> [Evesnt] Secure socket event is Received.(G_IO_OUT).");
2713 if (pSecureSocketImpl->__isWriteFired == true)
2715 errorCode = pSecureSocketImpl->__pGlibSocketInfo->SetSocketEvent(pSecureSocketImpl, pSecureSocketImpl->__socketFd);
2716 SysTryReturn(NID_NET_SOCK, errorCode == E_SUCCESS, true, errorCode, "[%s] Memory allocation failed.", GetErrorMessage(errorCode));
2717 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to release G_IO_OUT condition in OnGioEventCallback.", pSecureSocketImpl->__socketFd);
2722 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CONNECT) && (pSecureSocketImpl->__isRunFinished == true) &&
2723 (pSecureSocketImpl->__isConnectFired == false) && (pSecureSocketImpl->__isSslConnected == true) &&
2724 (((pSecureSocketImpl->__isCertVerifyFailed == true) && (pSecureSocketImpl->__sslVerify == SECURE_SOCKET_VERIFY_DISABLE)) ||
2725 (pSecureSocketImpl->__isCertVerifyFailed == false)) && (pSecureSocketImpl->__isCloseFired == false))
2727 timerId = g_source_get_id(pSecureSocketImpl->__pTimerSource);
2728 g_source_set_callback(pSecureSocketImpl->__pTimerSource, null, null, null);
2729 pSecureSocketImpl->__pTimerSource = null;
2730 SysLog(NID_NET_SOCK, "### Deleted g_source_destroy(%d)", timerId);
2732 // Fire the event(NET_SOCKET_EVENT_CONNECT)
2733 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CONNECT);
2734 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2735 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2740 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_WRITE) && (pSecureSocketImpl->__isRunFinished == true) &&
2741 (pSecureSocketImpl->__isConnectFired == true) && (pSecureSocketImpl->__isSslConnected == true) &&
2742 (pSecureSocketImpl->__isWriteFired == false) && (pSecureSocketImpl->__isCloseFired == false))
2744 // Fire the event(NET_SOCKET_EVENT_WRITE)
2745 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_WRITE);
2746 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2747 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2754 if (condition & G_IO_PRI)
2756 SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_PRI).");
2759 if (condition & G_IO_HUP)
2761 SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_HUP).");
2764 if (condition & G_IO_NVAL)
2766 SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_NVAL).");
2776 _SecureSocketImpl::SetTimer(void)
2779 GMainContext* pGMainContext = __pGMainContext;
2780 __pTimerSource = g_timeout_source_new(_SECURE_SOCKET_CONNECTION_TIMEOUT * 1000);
2781 g_source_set_callback(__pTimerSource, _SecureSocketImpl::OnTimerExpiredEvent, this, null);
2782 g_source_attach(__pTimerSource, pGMainContext);
2784 timerId = g_source_get_id(__pTimerSource);
2785 SysLog(NID_NET_SOCK, "Created the TimerSource[%d], timeout[%d].", timerId, _SECURE_SOCKET_CONNECTION_TIMEOUT * 1000);
2789 _SecureSocketImpl::OnTimerExpiredEvent(gpointer data)
2791 SysLog(NID_NET_SOCK, "### OnTimerExpiredEvent ###");
2793 _SecureSocketImpl* pSecureSocketImpl = null;
2794 _SecureSocketEventArg* pEventArg = null;
2798 pSecureSocketImpl = static_cast <_SecureSocketImpl*>(data);
2800 if (pSecureSocketImpl->__pTimerSource != null)
2802 timerId = g_source_get_id(pSecureSocketImpl->__pTimerSource);
2803 g_source_set_callback(pSecureSocketImpl->__pTimerSource, null, null, null);
2804 pSecureSocketImpl->__pTimerSource = null;
2805 SysLog(NID_NET_SOCK, "### Deleted g_source_destroy(%d)", timerId);
2807 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSecureSocketImpl->__isCloseFired == false))
2809 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
2810 SysTryReturn(NID_NET_SOCK, pEventArg, false, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2811 // Fire the event(NET_SOCKET_EVENT_CLOSE)
2812 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2820 _SecureSocketImpl::OnVerifyPeerCallback(int preverify_ok, X509_STORE_CTX* pX509Ctx)
2822 SysLog(NID_NET_SOCK, "### OnVerifyPeerCallback ###");
2824 _SecureSocketImpl* pSecureSocketImpl = null;
2825 _SecureSocketEventArg* pEventArg = null;
2826 X509* pServerCert = null;
2828 char* pX509Field = null;
2829 Integer* pSslTemp = null;
2830 Integer* pVal = null;
2835 pServerCert = X509_STORE_CTX_get_current_cert(pX509Ctx);
2837 if (pServerCert != null)
2839 pX509Field = X509_NAME_oneline(X509_get_subject_name(pServerCert), 0, 0);
2840 SysLog(NID_NET_SOCK, "Certificate: [Subject: %s]", pX509Field);
2842 OPENSSL_free(pX509Field);
2844 pX509Field = X509_NAME_oneline(X509_get_issuer_name(pServerCert), 0, 0);
2845 SysLog(NID_NET_SOCK, "Certificate: [Issuer: %s]", pX509Field);
2847 OPENSSL_free(pX509Field);
2850 sslIndex = SSL_get_ex_data_X509_STORE_CTX_idx();
2851 SysLog(NID_NET_SOCK, "SSL index(%d).", sslIndex);
2853 pSsl = (SSL*) X509_STORE_CTX_get_ex_data(pX509Ctx, sslIndex);
2856 SysLog(NID_NET_SOCK, "Failed to get the SSL object.");
2860 pSslTemp = new (std::nothrow) Integer((int)pSsl);
2862 pthread_mutex_lock(&__mapMutex);
2864 pVal = static_cast<Integer*>(_Singleton::GetSslMap()->GetValue(*pSslTemp));
2867 SysLog(NID_NET_SOCK, "Failed to get the SSL Object.");
2868 pthread_mutex_unlock(&__mapMutex);
2872 sslIndex = pVal->ToInt();
2873 SysLog(NID_NET_SOCK, "Application index(%d).", sslIndex);
2875 pthread_mutex_unlock(&__mapMutex);
2879 pSecureSocketImpl = static_cast <_SecureSocketImpl*>(SSL_get_ex_data((SSL*) pSsl, sslIndex));
2880 if (pSecureSocketImpl == null)
2882 SysLog(NID_NET_SOCK, "Failed to get the _SecureSocketImpl object.");
2886 depth = X509_STORE_CTX_get_error_depth(pX509Ctx);
2887 if (depth > pSecureSocketImpl->__sslDepth)
2889 sslError = X509_V_ERR_CERT_CHAIN_TOO_LONG;
2890 X509_STORE_CTX_set_error(pX509Ctx, sslError);
2894 sslError = X509_STORE_CTX_get_error(pX509Ctx);
2895 if (sslError == X509_V_OK)
2897 pSecureSocketImpl->__isCertVerifyFailed = false;
2898 SysLog(NID_NET_SOCK, "Verification is success.");
2902 SysLog(NID_NET_SOCK, "Failed to the peer certificate validation(%d).", sslError);
2904 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_SERVCERT_FAIL) && (pSecureSocketImpl->__isCloseFired == false)
2905 && (pSecureSocketImpl->__isCertVerifyFailed == false))
2907 pEventArg = new (std::nothrow) _SecureSocketEventArg(pSecureSocketImpl->__socketFd, NET_SOCKET_EVENT_SERVCERT_FAIL);
2908 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2910 // Fire the event(NET_SOCKET_EVENT_SERVCERT_FAIL)
2911 pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2913 pSecureSocketImpl->__isCertVerifyFailed = true;
2915 pSecureSocketImpl->SetTimer();
2917 else if (!(pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_SERVCERT_FAIL) && (pSecureSocketImpl->__sslVerify == SECURE_SOCKET_VERIFY_DISABLE))
2921 else if (!(pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_SERVCERT_FAIL))
2934 _SecureSocketImpl::OnVerifyClientCallback(int preverify_ok, X509_STORE_CTX* pX509Ctx)
2936 SysLog(NID_NET_SOCK, "### OnVerifyClientCallback ###");
2938 _SecureSocketImpl* pSecureSocketImpl = null;
2939 X509* pClientCert = null;
2941 char* pX509Field = null;
2942 Integer* pSslTemp = null;
2943 Integer* pVal = null;
2948 pClientCert = X509_STORE_CTX_get_current_cert(pX509Ctx);
2950 if (pClientCert != null)
2952 pX509Field = X509_NAME_oneline(X509_get_subject_name(pClientCert), 0, 0);
2953 SysLog(NID_NET_SOCK, "Certificate: [Subject: %s]", pX509Field);
2955 OPENSSL_free(pX509Field);
2957 pX509Field = X509_NAME_oneline(X509_get_issuer_name(pClientCert), 0, 0);
2958 SysLog(NID_NET_SOCK, "Certificate: [Issuer: %s]", pX509Field);
2960 OPENSSL_free(pX509Field);
2963 sslIndex = SSL_get_ex_data_X509_STORE_CTX_idx();
2964 SysLog(NID_NET_SOCK, "SSL index(%d).", sslIndex);
2966 pSsl = (SSL*) X509_STORE_CTX_get_ex_data(pX509Ctx, sslIndex);
2969 SysLog(NID_NET_SOCK, "Failed to get the SSL object.");
2973 pSslTemp = new Integer((int)pSsl);
2975 pthread_mutex_lock(&__mapMutex);
2977 pVal = static_cast<Integer*>(_Singleton::GetSslMap()->GetValue(*pSslTemp));
2980 SysLog(NID_NET_SOCK, "Failed to get the SSL Object.");
2981 pthread_mutex_unlock(&__mapMutex);
2985 sslIndex = pVal->ToInt();
2986 SysLog(NID_NET_SOCK, "Application index(%d).", sslIndex);
2988 pthread_mutex_unlock(&__mapMutex);
2992 pSecureSocketImpl = static_cast <_SecureSocketImpl*>(SSL_get_ex_data((SSL*) pSsl, sslIndex));
2993 if (pSecureSocketImpl == null)
2995 SysLog(NID_NET_SOCK, "Failed to get the _SecureSocketImpl object.");
2999 depth = X509_STORE_CTX_get_error_depth(pX509Ctx);
3000 if (depth > pSecureSocketImpl->__sslDepth)
3002 sslError = X509_V_ERR_CERT_CHAIN_TOO_LONG;
3003 X509_STORE_CTX_set_error(pX509Ctx, sslError);
3007 sslError = X509_STORE_CTX_get_error(pX509Ctx);
3008 if (sslError == X509_V_OK)
3010 SysLog(NID_NET_SOCK, "Verification of client certificate is success.");
3014 SysLog(NID_NET_SOCK, "Failed to the client certificate validation(%d).", sslError);
3025 _SecureSocketImpl::OnClientCertCallback(SSL* pSsl, X509** ppX509, EVP_PKEY** ppKey)
3027 SysLog(NID_NET_SOCK, "### OnClientCertCallback ###");
3029 _SecureSocketImpl* pSecureSocketImpl = null;
3032 Integer* pSslTemp = null;
3033 Integer* pVal = null;
3035 pSslTemp = new (std::nothrow) Integer((int)pSsl);
3037 pthread_mutex_lock(&__mapMutex);
3039 pVal = static_cast<Integer*>(_Singleton::GetSslMap()->GetValue(*pSslTemp));
3042 SysLog(NID_NET_SOCK, "Failed to get the SSL Object.");
3043 pthread_mutex_unlock(&__mapMutex);
3047 sslIndex = pVal->ToInt();
3048 SysLog(NID_NET_SOCK, "Application index(%d).", sslIndex);
3050 pthread_mutex_unlock(&__mapMutex);
3054 pSecureSocketImpl = static_cast <_SecureSocketImpl*>(SSL_get_ex_data((SSL*) pSsl, sslIndex));
3055 if (pSecureSocketImpl == null)
3057 SysLog(NID_NET_SOCK, "Failed to get the _SecureSocketImpl object.");
3061 pSecureSocketImpl->__isClientNoCert = true;
3068 _SecureSocketImpl::OnTmpRsaCallback(SSL* pSsl, int isexport, int keylength)
3070 SysLog(NID_NET_SOCK, "### OnTmpRsaCallback ###");
3077 pRsa = RSA_generate_key(512, RSA_F4, null, null);
3080 pRsa = RSA_generate_key(1024, RSA_F4, null, null);
3090 _SecureSocketImpl::SslConnect(int& sslError)
3092 result r = E_SUCCESS;
3094 // char* pErrReason = null;
3095 unsigned long errCode = 0;
3097 // Perform the SSL Handshake
3098 sslError = SSL_connect(__pSsl);
3102 sslError = SSL_get_error(__pSsl, sslError);
3104 // sslv3 alert handshake failure
3105 // pErrReason = (char*) ERR_reason_error_string(ERR_get_error());
3107 errCode = ERR_GET_REASON(ERR_get_error());
3111 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
3112 SysLog(NID_NET_SOCK, "SslConnect - SSL_ERROR_SSL");
3113 r = ConvertSslError(errCode);
3114 if (!((errCode == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) || (errCode == SSL_R_SSLV3_ALERT_NO_CERTIFICATE)))
3116 __isConnectFailed = true;
3121 case SSL_ERROR_SYSCALL: // I/O Error Occurred.
3122 SysLog(NID_NET_SOCK, "SslConnect - SSL_ERROR_SYSCALL");
3123 __isConnectFailed = true;
3127 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
3128 SysLog(NID_NET_SOCK, "SslConnect - SSL_ERROR_ZERO_RETURN");
3129 __isConnectFailed = true;
3133 case SSL_ERROR_WANT_CONNECT: // Operation is not completed.
3134 case SSL_ERROR_WANT_READ:
3135 case SSL_ERROR_WANT_WRITE:
3136 // SysLog(NID_NET_SOCK, "SslConnect - SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE");
3141 SysLog(NID_NET_SOCK, "SslConnect - default");
3142 __isConnectFailed = true;
3147 if (r != E_WOULD_BLOCK)
3149 SysLogException(NID_NET_SOCK, r, "[%s] Failed to perform the handshake.", GetErrorMessage(r));
3156 SysLog(NID_NET_SOCK, "SslConnect - SSL_connect is success.");
3158 if (__isAsync == true)
3160 __isSslConnected = true;
3167 if (__isAsync == true)
3169 __isSslConnected = false;
3175 _SecureSocketImpl::SslAccept(SSL* pSsl, int& sslError)
3177 result r = E_SUCCESS;
3179 //char* pErrReason = null;
3180 unsigned long errCode = 0;
3182 sslError = SSL_accept(pSsl);
3186 sslError = SSL_get_error(pSsl, sslError);
3188 //sslv3 alert handshake failure
3189 //pErrReason = (char*) ERR_reason_error_string(ERR_get_error());
3191 errCode = ERR_GET_REASON(ERR_get_error());
3195 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
3196 SysLog(NID_NET_SOCK, "SslAccept - SSL_ERROR_SSL");
3197 r = ConvertSslError(errCode);
3198 if (!((errCode == SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE) || (errCode == SSL_R_PEER_ERROR_NO_CERTIFICATE)
3199 || (errCode == SSL_R_NO_CERTIFICATE_RETURNED)))
3201 __isAcceptFailed = true;
3206 case SSL_ERROR_SYSCALL: // I/O Error Occurred.
3207 SysLog(NID_NET_SOCK, "SslAccept - SSL_ERROR_SYSCALL");
3208 __isAcceptFailed = true;
3212 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
3213 SysLog(NID_NET_SOCK, "SslAccept - SSL_ERROR_ZERO_RETURN");
3214 __isAcceptFailed = true;
3218 case SSL_ERROR_WANT_READ:
3219 case SSL_ERROR_WANT_WRITE:
3220 // SysLog(NID_NET_SOCK, "SslAccept - SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE");
3225 SysLog(NID_NET_SOCK, "SslAccept - default");
3226 __isAcceptFailed = true;
3232 if (r != E_WOULD_BLOCK)
3234 SysLogException(NID_NET_SOCK, r, "[%s] Failed to perform the handshake.", GetErrorMessage(r));
3241 SysLog(NID_NET_SOCK, "SslAccept - SSL_accept is success.");
3243 if (__isAsync == true)
3245 __isSslAccepted = true;
3252 if (__isAsync == true)
3254 __isSslAccepted = false;
3260 _SecureSocketImpl::ConvertSslError(int sslError)
3262 result r = E_SUCCESS;
3264 SysLog(NID_NET_SOCK, "SSL error code (%d).", sslError);
3268 case SSL_R_READ_TIMEOUT_EXPIRED:
3271 case SSL_R_BAD_RESPONSE_ARGUMENT:
3274 case SSL_R_BAD_RSA_MODULUS_LENGTH:
3275 case SSL_R_BAD_RSA_E_LENGTH:
3276 case SSL_R_BAD_SSL_FILETYPE:
3277 case SSL_R_BAD_SSL_SESSION_ID_LENGTH:
3278 case SSL_R_BAD_STATE:
3279 case SSL_R_BAD_MESSAGE_TYPE:
3280 case SSL_R_BIO_NOT_SET:
3281 r = E_INVALID_STATE;
3283 case SSL_R_UNKNOWN_CERTIFICATE_TYPE:
3284 case SSL_R_UNKNOWN_CIPHER_TYPE:
3285 case SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:
3286 case SSL_R_UNKNOWN_PKEY_TYPE:
3287 case SSL_R_UNKNOWN_REMOTE_ERROR_TYPE:
3288 case SSL_R_UNKNOWN_SSL_VERSION:
3289 r = E_RESOURCE_UNAVAILABLE;
3291 case SSL_R_UNSUPPORTED_SSL_VERSION:
3292 case SSL_R_NO_CIPHER_MATCH:
3293 case SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY:
3294 case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
3295 r = E_UNSUPPORTED_OPTION;
3297 case SSL_R_NO_SHARED_CIPHER: // Host(server) has no certificate in server side. Certificates are not loaded to ssl.
3300 case SSL_R_CERTIFICATE_VERIFY_FAILED: // Failed to the verification of server certificate in client side.
3301 r = E_CERTIFICATE_VERIFICATION_FAILED;
3303 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
3304 case SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE:
3305 case SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED:
3306 case SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED:
3307 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
3308 case SSL_R_TLSV1_ALERT_ACCESS_DENIED:
3309 case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
3310 r = E_INVALID_CERTIFICATE;
3312 case SSL_R_BAD_DECOMPRESSION:
3313 case SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE:
3316 case SSL_R_SSLV3_ALERT_BAD_RECORD_MAC:
3317 r = E_INVALID_STATE;
3319 case SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
3322 case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
3325 case SSL_R_UNKNOWN_PROTOCOL:
3326 case SSL_R_SSL_HANDSHAKE_FAILURE:
3327 case SSL_R_DECRYPTION_FAILED:
3328 case SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:
3329 case SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:
3330 case SSL_R_DIGEST_CHECK_FAILED:
3331 case SSL_R_DUPLICATE_COMPRESSION_ID:
3332 case SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER:
3333 case SSL_R_ENCRYPTED_LENGTH_TOO_LONG:
3334 case SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:
3335 case SSL_R_EXCESSIVE_MESSAGE_SIZE:
3336 case SSL_R_EXTRA_DATA_IN_MESSAGE:
3337 case SSL_R_GOT_A_FIN_BEFORE_A_CCS:
3338 case SSL_R_ILLEGAL_PADDING:
3339 case SSL_R_INVALID_CHALLENGE_LENGTH:
3340 case SSL_R_INVALID_COMMAND:
3341 case SSL_R_INVALID_PURPOSE:
3342 case SSL_R_INVALID_STATUS_RESPONSE:
3343 case SSL_R_INVALID_TICKET_KEYS_LENGTH:
3344 case SSL_R_KEY_ARG_TOO_LONG:
3345 case SSL_R_READ_WRONG_PACKET_TYPE:
3346 case SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE:
3347 case SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER:
3348 case SSL_R_TLSV1_ALERT_DECODE_ERROR:
3349 case SSL_R_TLSV1_ALERT_DECRYPTION_FAILED:
3350 case SSL_R_TLSV1_ALERT_DECRYPT_ERROR:
3351 case SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION:
3352 case SSL_R_TLSV1_ALERT_INTERNAL_ERROR:
3353 case SSL_R_TLSV1_ALERT_NO_RENEGOTIATION:
3354 case SSL_R_TLSV1_ALERT_RECORD_OVERFLOW:
3355 case SSL_R_TLSV1_ALERT_USER_CANCELLED:
3356 case SSL_R_UNEXPECTED_RECORD:
3357 r = E_INVALID_STATE;
3359 case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
3360 case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
3361 r = E_NO_CERTIFICATE;
3363 case SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE: // Response that peer doesnt have certificate.
3364 case SSL_R_PEER_ERROR_NO_CERTIFICATE:
3365 case SSL_R_NO_CERTIFICATE_RETURNED:
3366 r = E_NO_CERTIFICATE;
3367 __isPeerNoCert = true;
3369 case SSL_R_WRONG_VERSION_NUMBER:
3370 case SSL_R_WRONG_SSL_VERSION:
3371 r = E_UNSUPPORTED_VERSION;
3381 _GlibSecureSocketInfo::_GlibSecureSocketInfo(void)
3382 : __pSocketChannel(null)
3383 , __pSocketSource(null)
3384 , __socketFd(INVALID_HANDLE)
3389 _GlibSecureSocketInfo::~_GlibSecureSocketInfo(void)
3391 if (__pSocketSource != null)
3393 g_source_set_callback(__pSocketSource, null, null, null);
3394 SysLog(NID_NET_SOCK, "### Deleted g_source_destroy(%d)", g_source_get_id(__pSocketSource));
3395 g_source_destroy(__pSocketSource);
3396 g_source_unref(__pSocketSource);
3397 __pSocketSource = null;
3400 if (__pSocketChannel != null)
3402 g_io_channel_unref(__pSocketChannel);
3403 __pSocketChannel = null;
3414 _GlibSecureSocketInfo::SetSocketEvent(_SecureSocketImpl* pSecureSocketImpl, HSocket socketFd)
3416 result r = E_SUCCESS;
3418 GIOCondition condition = (GIOCondition)0;
3420 if (__pSocketChannel == null)
3422 __pUserData = new (std::nothrow) _SecureUserData;
3423 SysTryReturnResult(NID_NET_SOCK, __pUserData, E_OUT_OF_MEMORY, "Memory allocation failed.");
3425 __pSocketChannel = g_io_channel_unix_new(socketFd);
3426 SysLog(NID_NET_SOCK, "Created the SocketChannel. [Fd : %d]", socketFd);
3429 // Set masking of wanted socket Event
3430 if (pSecureSocketImpl->__isWriteFired == false)
3432 condition = static_cast <GIOCondition>(G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3436 condition = static_cast <GIOCondition>(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3439 // G_IO_IN : There is data to read. 1
3440 // G_IO_OUT : Data can be written (without blocking). 4
3441 // G_IO_PRI : There is urgent data to read. 2
3442 // G_IO_ERR : Error condition. 8
3443 // G_IO_HUP : Hung up (the connection has been broken, usually for pipes and sockets). 16
3444 // G_IO_NVAL : Invalid request. The file descriptor is not open. 32
3446 if (__pSocketSource != null)
3448 g_source_set_callback(__pSocketSource, null, null, null);
3449 SysLog(NID_NET_SOCK, "### Deleted g_source_destroy. (%d)", g_source_get_id(__pSocketSource));
3450 g_source_destroy(__pSocketSource);
3451 g_source_unref(__pSocketSource);
3452 __pSocketSource = null;
3453 SysLog(NID_NET_SOCK, "Unref the SocketSource.");
3456 __pSocketSource = g_io_create_watch(__pSocketChannel, condition);
3458 __pUserData->pSecureSocketImpl = (_SecureSocketImpl*) pSecureSocketImpl;
3459 __pUserData->pGSource = (GSource*) __pSocketSource;
3461 g_source_set_callback(__pSocketSource, (GSourceFunc) _SecureSocketImpl::OnGioEventCallback, __pUserData, null);
3462 g_source_attach(__pSocketSource, pSecureSocketImpl->__pGMainContext);
3464 SysLog(NID_NET_SOCK, "Created the GSource Id : [%d]", g_source_get_id(__pSocketSource));
3465 SysLog(NID_NET_SOCK, "Created the SocketSource for receiving the event. [%d]", condition);
3470 } } } // Tizen::Net::Sockets