merge with master
[framework/osp/net.git] / src / sockets / FNetSock_SecureSocketImpl.cpp
1 //
2 // Open Service Platform
3 // Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
4 //
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
8 //
9 //     http://floralicense.org/license/
10 //
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.
16 //
17
18 /**
19  * @file                FNetSock_SecureSocketImpl.cpp
20  * @brief               This is the implementation for the _SecureSocketImpl class.
21  */
22
23 #include <unique_ptr.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/ioctl.h>
28 #include <fcntl.h>
29 #include <netdb.h>
30 #include <arpa/inet.h>
31 #include <unistd.h>
32 #include <netinet/in.h>
33 #include <netinet/tcp.h>
34 #include <errno.h>
35 #include <sys/poll.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>
42 #include <FAppApp.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"
66
67 using namespace std;
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;
74
75 namespace Tizen { namespace Net { namespace Sockets
76 {
77
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
84
85 pthread_mutex_t _SecureSocketImpl::__mapMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
86
87 bool _Singleton::__initialized = false;
88 HashMap* _Singleton::__pSslMap = null;
89
90 _SecureSocketImpl::_SecureSocketImpl(SecureSocket* pSocket)
91         : __socketFd(INVALID_HANDLE)
92         , __isConstructed(false)
93         , __isClosed(false)
94         , __isLoopback(false)
95         , __isAsync(false)
96         , __isReadFired(false)
97         , __isConnectFired(false)
98         , __isAcceptFired(false)
99         , __isServer(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)
127         , __pThread(null)
128         , __pSsl(null)
129         , __pSslMethod(null)
130         , __pSslCtx(null)
131         , __pGMainContext(null)
132         , __pGlibSocketInfo(null)
133         , __pTimerSource(null)
134         , __pSslKey(null)
135         , __sslDepth(0)
136 {
137 }
138
139 _SecureSocketImpl::~_SecureSocketImpl(void)
140 {
141         Dispose();
142
143         if (__pThread != null)
144         {
145                 __pThread->Join();
146                 delete __pThread;
147                 __pThread = null;
148         }
149
150         delete __pGlibSocketInfo;
151         __pGlibSocketInfo = null;
152
153         ERR_free_strings();
154         ERR_clear_error();
155
156         pthread_mutex_lock(&__mapMutex);
157         if ((_Singleton::GetInitialized() == true) && (__pSslKey))
158         {
159             _Singleton::GetSslMap()->Remove(*__pSslKey, true);
160         }
161         pthread_mutex_unlock(&__mapMutex);
162
163         if (__pSsl != null)
164         {
165                 SSL_shutdown(__pSsl);
166
167                 SSL_free(__pSsl);
168                 __pSsl = null;
169         }
170
171         if (__pSslCtx != null)
172         {
173                 SSL_CTX_free(__pSslCtx);
174                 __pSslCtx = null;
175         }
176
177         __pGMainContext = null;
178
179         __secureSocketEventListenerList.RemoveAll();
180
181         delete __pSecureSocketEvent;
182         __pSecureSocketEvent = null;
183
184         delete __pCustomNetConnection;
185         __pCustomNetConnection = null;
186
187         delete __pCustomNetConnectionEventListener;
188         __pCustomNetConnectionEventListener = null;
189
190         delete __pManagedNetConnection;
191         __pManagedNetConnection = null;
192
193         delete __pManagedNetConnectionEventListener;
194         __pManagedNetConnectionEventListener = null;
195
196         delete __pNetConnectionManager;
197         __pNetConnectionManager = null;
198
199         if (__pTimerSource != null)
200         {
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);
208         }
209
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;
219         __isServer = 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;
234         __isAsync = false;
235         __isClosed = false;
236         __isLoopback = false;
237         __isConstructed = false;
238         __socketFd = INVALID_HANDLE;
239 }
240
241 result
242 _SecureSocketImpl::Construct(const Tizen::Net::NetConnection& netConnection, NetSocketAddressFamily addressFamily,
243                                                          NetSocketType socketType, NetSocketProtocol protocol)
244 {
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.");
248
249         SysLog(NID_NET_SOCK, "Socket uses CustomNetConnection.");
250
251         _Singleton::InitializeSecureSocket();
252
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.");
256
257         result r = E_SUCCESS;
258         int af = 0;
259         int type = 0;
260         int sockFd = INVALID_HANDLE;
261         int flags = 0;
262         int err = 0;
263
264         _NetConnectionImpl* pCustomNCImpl = null;
265         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
266
267         String deviceName;
268         char* pDeviceName = null;
269         const NetConnectionInfo* pNetConnectionInfo = null;
270         const _NetConnectionInfoImpl* pNCInfoImpl = null;
271
272         unique_ptr<_SecureSocketEvent> pSecureSocketEvent;
273         unique_ptr<_SecureSocketCustomNetConnectionEventListener> pCustomNetConnectionEventListener;
274         unique_ptr<NetConnection> pCustomNetConnection;
275
276         // Set proper inparam
277         if (addressFamily == NET_SOCKET_AF_IPV4)
278         {
279                 af = AF_INET;
280                 __protocolFamily = addressFamily;
281         }
282
283         if (socketType == NET_SOCKET_TYPE_STREAM)
284         {
285             SysTryReturnResult(NID_NET_SOCK, protocol == NET_SOCKET_PROTOCOL_SSL, E_INVALID_ARG, "Invalid SocketType - Mismatch.");
286         type = SOCK_STREAM;
287         __socketType = socketType;
288         __protocol = NET_SOCKET_PROTOCOL_SSL;
289         }
290
291         // Custom Network Check
292         connState = pNetConnection->GetConnectionState();
293
294         if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
295         {
296                 SysLog(NID_NET_SOCK, "Custom Network is available.");
297         }
298         else
299         {
300                 r = E_INVALID_CONNECTION;
301                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Custom Network is not available.");
302                 return r;
303         }
304
305         __socketFd = socket(af, type, 0);
306
307         if (__socketFd < 0)
308         {
309                 r = ConvertErrorToResult(errno);
310                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to construct the socket.", GetErrorMessage((r)));
311                 goto CATCH;
312         }
313
314         flags = fcntl(__socketFd, F_GETFL);
315         flags |= O_NONBLOCK;
316
317         if (fcntl(__socketFd, F_SETFL, flags) < 0)
318         {
319                 __isNonblock = false;
320                 r = E_SYSTEM;
321                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to construct(ioctl) the socket.");
322                 goto CATCH;
323         }
324         else
325         {
326                 __isNonblock = true;
327
328                 __secureSocketEventListenerList.Construct();
329
330                 pSecureSocketEvent.reset(new (std::nothrow) _SecureSocketEvent());
331                 SysTryReturnResult(NID_NET_SOCK, pSecureSocketEvent != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
332
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.");
335
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();
342
343                 __pSslMethod = (SSL_METHOD*) SSLv3_method();
344                 __sslVersion = NET_SOCK_SSL_VERSION_SSLV3;
345
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.");
348         }
349
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.");
353
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.");
356
357         deviceName = pNCInfoImpl->GetDeviceName();
358
359         if (deviceName.IsEmpty())
360         {
361                 SysLog(NID_NET_SOCK, "DeviceName is empty string. - Emulator Case");
362         }
363         else
364         {
365                 SysLog(NID_NET_SOCK, "DeviceName is not empty string.[Device Name : %ls] - Target Case", deviceName.GetPointer());
366
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.");
369
370                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
371                 delete[] pDeviceName;
372                 if (err < 0)
373                 {
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.");
377                 }
378         }
379
380         // Copy New CustomNetConnection
381         pCustomNCImpl = _NetConnectionImpl::GetInstance(*pNetConnection);
382
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.");
386
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.");
391
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));
396
397         // Set the __socketFd
398         pCustomNetConnectionEventListener->SetConstructParams(pSecureSocketEvent.get(), __socketFd, this);
399
400         __pCustomNetConnection = pCustomNetConnection.release();
401         __pCustomNetConnectionEventListener = pCustomNetConnectionEventListener.release();
402         __pSecureSocketEvent = pSecureSocketEvent.release();
403
404         __isConstructed = true;
405
406         SysLog(NID_NET_SOCK, "Created the Secure Socket by non-blocking mode(default) [Fd: %d]", __socketFd);
407
408         return r;
409
410 CATCH:
411         if (__socketFd > INVALID_HANDLE)
412         {
413                 sockFd = __socketFd;
414                 close(__socketFd);
415                 SysLog(NID_NET_SOCK, "### SocketFd is closed. [Fd : %d]", sockFd);
416         }
417
418         if (__pSslCtx)
419         {
420                 SSL_CTX_free(__pSslCtx);
421                 __pSslCtx = null;
422         }
423         return r;
424 }
425
426 result
427 _SecureSocketImpl::Construct(NetSocketAddressFamily addressFamily, NetSocketType socketType, NetSocketProtocol protocol)
428 {
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.");
435
436         SysLog(NID_NET_SOCK, "Socket uses DefaultNetConnection.");
437
438         _Singleton::InitializeSecureSocket();
439
440         result r = E_SUCCESS;
441         int af = 0;
442         int type = 0;
443         int flags = 0;
444         int sockFd = INVALID_HANDLE;
445
446         _ManagedNetConnectionImpl* pManagedNCImpl = null;
447         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
448         _SocketMethodFlag flag = FLAG_NONE;
449
450         unique_ptr<_SecureSocketEvent> pSecureSocketEvent;
451         unique_ptr<_SecureSocketManagedNetConnectionEventListener> pManagedNetConnectionEventListener;
452         unique_ptr<ManagedNetConnection> pManagedNetConnection;
453         unique_ptr<NetConnectionManager> pNetConnectionManager;
454
455         // Set proper inparam
456         if (addressFamily == NET_SOCKET_AF_IPV4)
457         {
458                 af = AF_INET;
459                 __protocolFamily = addressFamily;
460         }
461
462         if (socketType == NET_SOCKET_TYPE_STREAM)
463         {
464             SysTryReturnResult(NID_NET_SOCK, protocol == NET_SOCKET_PROTOCOL_SSL, E_INVALID_ARG, "Invalid SocketType - Mismatch.");
465
466                 type = SOCK_STREAM;
467                 __socketType = socketType;
468                 __protocol = NET_SOCKET_PROTOCOL_SSL;
469         }
470
471         __socketFd = socket(af, type, 0);
472
473         if (__socketFd < 0)
474         {
475                 r = ConvertErrorToResult(errno);
476                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to construct the socket.", GetErrorMessage((r)));
477         }
478         else
479         {
480                 flags = fcntl(__socketFd, F_GETFL);
481                 flags |= O_NONBLOCK;
482
483                 if (fcntl(__socketFd, F_SETFL, flags) < 0)
484                 {
485                         __isNonblock = false;
486                         r = E_SYSTEM;
487                         SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to construct(ioctl) the socket.");
488                         close(__socketFd);
489                         return r;
490                 }
491                 else
492                 {
493                         __isNonblock = true;
494
495                         __secureSocketEventListenerList.Construct();
496
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.");
499
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));
502
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();
509
510                         __pSslMethod = (SSL_METHOD*) SSLv3_method();
511                         __sslVersion = NET_SOCK_SSL_VERSION_SSLV3;
512
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.");
515                 }
516         }
517
518         if (_NetConnectionManagerImpl::IsDefaultMode() != true)
519         {
520                 SysLog(NID_NET_SOCK, "Socket uses ManagedNetConnection");
521
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.");
524
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));
527
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.");
530
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.");
533
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.");
537
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));
541
542                 // Set the __socketFd
543                 flag = FLAG_CONSTRUCT;
544                 pManagedNetConnectionEventListener->SetConstructParams(pSecureSocketEvent.get(), __socketFd, flag, this);
545
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));
549
550                 connState = pManagedNCImpl->GetConnectionState();
551                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
552                 {
553                         pManagedNetConnectionEventListener->SetStartedFlag(true);
554                 }
555         }
556
557         __pNetConnectionManager = pNetConnectionManager.release();
558         __pManagedNetConnection = pManagedNetConnection.release();
559         __pManagedNetConnectionEventListener = pManagedNetConnectionEventListener.release();
560         __pSecureSocketEvent = pSecureSocketEvent.release();
561
562         __isConstructed = true;
563
564         SysLog(NID_NET_SOCK, "Created the Secure Socket by non-blocking mode(default) [Fd: %d]", __socketFd);
565
566         return r;
567
568 CATCH:
569         if (__socketFd > INVALID_HANDLE)
570         {
571                 sockFd = __socketFd;
572                 close(__socketFd);
573                 SysLog(NID_NET_SOCK, "### SocketFd is closed. [Fd : %d]", sockFd);
574         }
575
576         if (__pSslCtx)
577         {
578                 SSL_CTX_free(__pSslCtx);
579                 __pSslCtx = null;
580         }
581         return r;
582 }
583
584 result
585 _SecureSocketImpl::Connect(const Tizen::Net::NetEndPoint& remoteEP)
586 {
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.");
589
590         result r = E_SUCCESS;
591
592         int err = 0;
593         int sslError = 0;
594         int sslIndex = 0;
595
596         NetAddressFamily af;
597         unsigned long ipAddr = 0;
598         unsigned short port = 0;
599         Ip4Address* pIp4Addr = null;
600         const _NetEndPointImpl* pRemoteEPImpl = null;
601
602         struct sockaddr_in remoteAddr;
603
604         String remoteAddrString;
605
606         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
607         _SocketMethodFlag flag = FLAG_NONE;
608
609         String deviceName;
610         char* pDeviceName = null;
611         const _ManagedNetConnectionImpl* pMNCConnImpl = null;
612         long milliseconds = _THREAD_SLEEP_TIMER; // 2000 milliseconds (sleep time)
613         int tryCount = 0;
614         bool isConnectionStarted = false;
615
616         char* pCaPath = null;
617         String caPath;
618
619         pRemoteEPImpl = _NetEndPointImpl::GetInstance(remoteEP);
620
621         if (pRemoteEPImpl->IsValid() == true)
622         {
623                 pIp4Addr = static_cast <Ip4Address*>(pRemoteEPImpl->GetAddress());
624                 remoteAddrString = pIp4Addr->ToString();
625         }
626         else
627         {
628                 r = E_INVALID_ARG;
629                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] NetEndPoint is invalid.");
630                 return r;
631         }
632
633         _ApiVersion apiVersion = _AppInfo::GetApiVersion();
634
635         if (apiVersion == _API_VERSION_2_0 && _AppInfo::IsOspCompat())
636         {
637                 if (__isLoopback == false)
638                 {
639                         if (remoteAddrString == LOOPBACK_ADDRESS)
640                         {
641                                 r = E_SYSTEM;
642                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
643                                 return r;
644                         }
645                 }
646                 else
647                 {
648                         if (remoteAddrString != LOOPBACK_ADDRESS)
649                         {
650                                 r = E_SYSTEM;
651                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
652                                 return r;
653                         }
654                 }
655         }
656
657         af = pRemoteEPImpl->GetNetAddressFamily();
658         SysTryReturnResult(NID_NET_SOCK, af == NET_AF_IPV4, E_INVALID_ARG, "Address family is invalid.");
659
660         r = pIp4Addr->GetAddress(ipAddr);
661         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, E_INVALID_ARG, "Address is invalid.");
662
663         port = pRemoteEPImpl->GetPort();
664
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);
669
670         if (__pManagedNetConnection != null)
671         {
672                 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
673
674                 if (__isNonblock == false)
675                 {
676                         SysLog(NID_NET_SOCK, "This socket is blocking mode.");
677
678                         pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
679
680                         while (1)
681                         {
682                                 connState = pMNCConnImpl->QueryConnectionState(deviceName);
683
684                                 switch (connState)
685                                 {
686                                 case NET_CONNECTION_STATE_STARTED:
687
688                                 case NET_CONNECTION_STATE_RESUMED:
689
690                                 case NET_CONNECTION_STATE_SUSPENDED:
691                                         SysLog(NID_NET_SOCK, "Network is available.");
692
693                                         if (deviceName.IsEmpty())
694                                         {
695                                                 SysLog(NID_NET_SOCK, "DeviceName is empty string. - Emulator Case");
696                                         }
697                                         else
698                                         {
699                                                 SysLog(NID_NET_SOCK, "DeviceName is not empty string.[Device Name : %ls] - Target Case", deviceName.GetPointer());
700
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.");
703
704                                                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
705                                                 delete[] pDeviceName;
706                                                 if (err < 0)
707                                                 {
708                                                         ConvertErrorToResult(errno);
709
710                                                         SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Failed to bind the device name.");
711                                                 }
712                                         }
713
714                                         err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
715                                         break;
716
717                                 case NET_CONNECTION_STATE_STARTING:
718
719                                 case NET_CONNECTION_STATE_NONE:
720
721                                 case NET_CONNECTION_STATE_STOPPING:
722
723                                 case NET_CONNECTION_STATE_STOPPED:
724                                         SysLog(NID_NET_SOCK, "Network is not available.");
725                                         break;
726
727                                 default:
728                                         SysLog(NID_NET_SOCK, "Should not come here.");
729                                         break;
730                                 }
731
732                                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
733                                 {
734                                         break;
735                                 }
736
737                                 if (connState == NET_CONNECTION_STATE_STOPPED)
738                                 {
739                                         r = E_INVALID_CONNECTION;
740                                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
741                                         break;
742                                 }
743
744                                 tryCount++;
745
746                                 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
747                                 {
748                                         r = E_TIMEOUT;
749                                         SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network timeout happened. Try Again");
750                                         tryCount = 0;
751                                         break;
752                                 }
753
754                                 Thread::Sleep(milliseconds);
755                         }
756                 }
757                 else
758                 {
759                         isConnectionStarted = __pManagedNetConnectionEventListener->GetStartedFlag();
760
761                         if (isConnectionStarted)
762                         {
763                                 err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
764                         }
765                         else
766                         {
767                                 r = E_WOULD_BLOCK;
768                                 flag = FLAG_CONNECT;
769                                 __pManagedNetConnectionEventListener->SetConnectParams(__socketFd, remoteAddr, flag, this);
770
771                                 return r;
772                         }
773                 }
774         }
775         else
776         {
777                 err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
778         }
779
780         if (err < 0)
781         {
782                 r = ConvertErrorToResult(errno);
783
784                 if (r != E_WOULD_BLOCK)
785                 {
786                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to connect the socket.", GetErrorMessage(r));
787                         if (__isAsync == true)
788                         {
789                                 __isConnectFired = true;
790                         }
791                         goto CATCH;
792                 }
793         }
794
795         // Set default CA path.
796         caPath = _CertService::GetCertificateCrtFilePath();
797         SysLog(NID_NET_SOCK, "CA Path(%ls)", caPath.GetPointer());
798
799         pCaPath = _StringConverter::CopyToCharArrayN(caPath);
800         SysTryReturnResult(NID_NET_SOCK, pCaPath != null, E_OUT_OF_MEMORY, "The memory is insufficient.");
801
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.");
804
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.");
807
808         delete[] pCaPath;
809     pCaPath = null;
810
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.");
813
814         SSL_set_fd(__pSsl, __socketFd);
815
816         SSL_set_options(__pSsl, SSL_OP_ALL);
817
818         if (__isAsync == true || __isNonblock == true)
819         {
820                 SSL_CTX_set_client_cert_cb(__pSslCtx, (int (*)(SSL*, X509**, EVP_PKEY**)) _SecureSocketImpl::OnClientCertCallback);
821
822                 SSL_set_mode(__pSsl, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
823
824                 sslIndex = SSL_get_ex_new_index(0, (char*) "_SecureSocketImpl index", null, null, null);
825                 SysLog(NID_NET_SOCK, "SSL index(%d).", sslIndex);
826
827                 SSL_set_ex_data(__pSsl, sslIndex, this);
828
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());
835
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.
841                 //                and so on.
842                 __sslDepth = _SSL_VERIFY_DEPTH;
843                 SSL_set_verify_depth(__pSsl, __sslDepth);
844
845                 // Create thread
846                 __pThread = new (std::nothrow) Thread();
847                 SysTryCatch(NID_NET_SOCK, __pThread != null, r = E_OUT_OF_MEMORY, r, "Memory allocation failed.");
848
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));
852
853                 // Start thread
854                 r = __pThread->Start();
855         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Failed to start the thread.", GetErrorMessage(r));
856
857                 r = E_WOULD_BLOCK;
858                 SysLogException(NID_NET_SOCK, r, "[E_WOULD_BLOCK] Returned EWOULDBLOCK to connect the socket.");
859
860                 __isConnectFired = false;
861         }
862         else
863         {
864                 if (__sslVerify == SECURE_SOCKET_VERIFY_NONE)
865                 {
866                         SSL_set_verify(__pSsl, SSL_VERIFY_PEER, null);
867                 }
868
869                 r = SslConnect(sslError);
870                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Failed to connect the socket.", GetErrorMessage(r));
871         }
872
873         return r;
874
875 CATCH:
876         if (__pThread)
877         {
878                 delete __pThread;
879                 __pThread = null;
880         }
881
882     if (pCaPath != null)
883     {
884         delete[] pCaPath;
885         pCaPath = null;
886     }
887
888         return r;
889 }
890
891 result
892 _SecureSocketImpl::Send(ByteBuffer& buffer)
893 {
894     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
895
896         result r = E_SUCCESS;
897         result res = E_SUCCESS;
898
899         int sentLength = 0;
900         int sslError = 0;
901
902         unsigned int offset = buffer.GetPosition();
903         unsigned int length = buffer.GetRemaining();
904
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.");
907
908         sentLength = SSL_write(__pSsl, (char*) (buffer.GetPointer() + offset), length);
909
910         if (sentLength <= 0)
911         {
912                 sslError = SSL_get_error(__pSsl, sentLength);
913
914                 // Error code mapping
915                 switch (sslError)
916                 {
917                 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
918                         r = E_SYSTEM;
919                         break;
920
921                 case SSL_ERROR_SYSCALL: // I/o Error Occurred.
922                         r = E_SYSTEM;
923                         break;
924
925                 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
926                         r = E_CONNECTION_FAILED;
927                         break;
928
929                 case SSL_ERROR_WANT_READ:  // Operation is not completed.
930                 case SSL_ERROR_WANT_WRITE:
931                         r = E_WOULD_BLOCK;
932                         break;
933
934                 default:
935                         r = E_SYSTEM;
936                         break;
937                 }
938
939                 if (r != E_WOULD_BLOCK)
940                 {
941                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to send the socket.", GetErrorMessage(r));
942
943                         if (__isAsync == true)
944                         {
945                                 __isWriteFired = true;
946                         }
947                         goto CATCH;
948                 }
949                 else
950                 {
951                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to send the socket.", GetErrorMessage(r));
952                         if (__isAsync == true)
953                         {
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);
958                         }
959                         goto CATCH;
960                 }
961         }
962
963         SysLog(NID_NET_SOCK, "Actually send byte : %d byte", sentLength);
964
965         if (__isAsync == true)
966         {
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);
971         }
972
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.");
975
976         return r;
977
978 CATCH:
979         res = buffer.SetPosition(offset);
980     SysTryReturnResult(NID_NET_SOCK, res == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
981
982         return r;
983 }
984
985 result
986 _SecureSocketImpl::Send(void* pBuffer, int length, int& sentLength)
987 {
988     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
989
990         result r = E_SUCCESS;
991
992         int sslError = 0;
993
994         if (!pBuffer || length <= 0)
995         {
996                 r = E_INVALID_ARG;
997                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] The buffer is null or the length is invalid.");
998                 return r;
999         }
1000
1001         SysTryReturnResult(NID_NET_SOCK, __pSsl != null, E_CONNECTION_FAILED, "The Secure Socket is not connected.");
1002
1003         sentLength = SSL_write(__pSsl, static_cast <char*>(pBuffer), length);
1004
1005         if (sentLength <= 0)
1006         {
1007                 sslError = SSL_get_error(__pSsl, sentLength);
1008
1009                 // error code mapping
1010                 switch (sslError)
1011                 {
1012                 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
1013                         r = E_SYSTEM;
1014                         break;
1015
1016                 case SSL_ERROR_SYSCALL: // I/o Error Occurred.
1017                         r = E_SYSTEM;
1018                         break;
1019
1020                 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
1021                         r = E_CONNECTION_FAILED;
1022                         break;
1023
1024                 case SSL_ERROR_WANT_READ: // Operation is not completed.
1025                 case SSL_ERROR_WANT_WRITE:
1026                         r = E_WOULD_BLOCK;
1027                         break;
1028
1029                 default:
1030                         r = E_SYSTEM;
1031                         break;
1032                 }
1033
1034                 if (r != E_WOULD_BLOCK)
1035                 {
1036                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to send the socket.", GetErrorMessage(r));
1037                         if (__isAsync == true)
1038                         {
1039                                 __isWriteFired = true;
1040                         }
1041                         goto CATCH;
1042                 }
1043                 else
1044                 {
1045                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to send the socket.", GetErrorMessage(r));
1046                         if (__isAsync == true)
1047                         {
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);
1052                         }
1053                         goto CATCH;
1054                 }
1055         }
1056
1057         SysLog(NID_NET_SOCK, "Actually send byte : %d byte", sentLength);
1058
1059         if (__isAsync == true)
1060         {
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);
1065         }
1066
1067         return r;
1068
1069 CATCH:
1070         return r;
1071 }
1072
1073 result
1074 _SecureSocketImpl::Receive(ByteBuffer& buffer)
1075 {
1076     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1077
1078         result r = E_SUCCESS;
1079         result res = E_SUCCESS;
1080
1081         int rcvdLength = 0;
1082         int sslError = 0;
1083
1084         unsigned int offset = buffer.GetPosition();
1085         unsigned int length = buffer.GetRemaining();
1086
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.");
1089
1090         rcvdLength = SSL_read(__pSsl, (char*) (buffer.GetPointer() + offset), length);
1091
1092         if (rcvdLength < 0)
1093         {
1094                 sslError = SSL_get_error(__pSsl, rcvdLength);
1095
1096                 // Error code mapping
1097                 switch (sslError)
1098                 {
1099                 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
1100                         r = E_SYSTEM;
1101                         break;
1102
1103                 case SSL_ERROR_SYSCALL: // I/o Error Occurred.
1104                         r = E_SYSTEM;
1105                         break;
1106
1107                 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
1108                         r = E_CONNECTION_FAILED;
1109                         break;
1110
1111                 case SSL_ERROR_WANT_READ: // Operation is not completed.
1112                 case SSL_ERROR_WANT_WRITE:
1113                         r = E_WOULD_BLOCK;
1114                         break;
1115
1116                 default:
1117                         r = E_SYSTEM;
1118                         break;
1119                 }
1120
1121                 if (r != E_WOULD_BLOCK)
1122                 {
1123                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to receive the socket.", GetErrorMessage(r));
1124                         if (__isAsync == true)
1125                         {
1126                                 __isReadFired = true;
1127                         }
1128                         goto CATCH;
1129                 }
1130                 else
1131                 {
1132                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to receive the socket.", GetErrorMessage(r));
1133                         if (__isAsync == true)
1134                         {
1135                                 __isReadFired = false;
1136                         }
1137                         goto CATCH;
1138                 }
1139         }
1140
1141         SysLog(NID_NET_SOCK, "Actually receive byte : %d byte", rcvdLength);
1142
1143         if (__isAsync == true)
1144         {
1145                 __isReadFired = false;
1146         }
1147
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.");
1150
1151         return r;
1152
1153 CATCH:
1154         res = buffer.SetPosition(offset);
1155         SysTryReturnResult(NID_NET_SOCK, res == E_SUCCESS, E_SYSTEM, "Failed to Set the position.");
1156
1157         return r;
1158 }
1159
1160 result
1161 _SecureSocketImpl::Receive(void* pBuffer, int length, int& rcvdLength)
1162 {
1163 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1164
1165         result r = E_SUCCESS;
1166
1167         int sslError = 0;
1168
1169         if (!pBuffer || length <= 0)
1170         {
1171                 r = E_INVALID_ARG;
1172                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] The buffer is null or the length is invalid.");
1173                 return r;
1174         }
1175
1176         SysTryReturnResult(NID_NET_SOCK, __pSsl != null, E_CONNECTION_FAILED, "The Secure Socket is not connected.");
1177
1178         rcvdLength = SSL_read(__pSsl, static_cast <char*>(pBuffer), length);
1179
1180         if (rcvdLength < 0)
1181         {
1182                 sslError = SSL_get_error(__pSsl, rcvdLength);
1183
1184                 // Error code mapping
1185                 switch (sslError)
1186                 {
1187                 case SSL_ERROR_SSL: // Error occurred in SSL library or protocol error.
1188                         r = E_SYSTEM;
1189                         break;
1190
1191                 case SSL_ERROR_SYSCALL: // I/O Error occurred.
1192                         r = E_SYSTEM;
1193                         break;
1194
1195                 case SSL_ERROR_ZERO_RETURN: // TLS/SSL connection has been closed.
1196                         r = E_CONNECTION_FAILED;
1197                         break;
1198
1199                 case SSL_ERROR_WANT_READ: // Operation is not completed.
1200                 case SSL_ERROR_WANT_WRITE:
1201                         r = E_WOULD_BLOCK;
1202                         break;
1203
1204                 default:
1205                         r = E_SYSTEM;
1206                         break;
1207                 }
1208
1209                 if (r != E_WOULD_BLOCK)
1210                 {
1211                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to receive the socket.", GetErrorMessage(r));
1212                         if (__isAsync == true)
1213                         {
1214                                 __isReadFired = true;
1215                         }
1216                         goto CATCH;
1217                 }
1218                 else
1219                 {
1220                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to receive the socket.", GetErrorMessage(r));
1221                         if (__isAsync == true)
1222                         {
1223                                 __isReadFired = false;
1224                         }
1225                         goto CATCH;
1226                 }
1227         }
1228
1229         SysLog(NID_NET_SOCK, "Actually receive byte : %d byte", rcvdLength);
1230
1231         if (__isAsync == true)
1232         {
1233                 __isReadFired = false;
1234         }
1235
1236         return r;
1237
1238 CATCH:
1239         return r;
1240 }
1241
1242 result
1243 _SecureSocketImpl::Ioctl(NetSocketIoctlCmd cmd, unsigned long& pArg)
1244 {
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.");
1247
1248         result r = E_SUCCESS;
1249         int err = 0;
1250         int flag = 0;
1251
1252         if (cmd == NET_SOCKET_FIONBIO && pArg != 0)
1253         {
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;
1259         }
1260         else if (cmd == NET_SOCKET_FIONBIO && pArg == 0)
1261         {
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;
1267         }
1268
1269         if (err < 0)
1270         {
1271                 r = ConvertErrorToResult(errno);
1272                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to Ioctl the socket.", GetErrorMessage(r));
1273         }
1274
1275         return r;
1276 }
1277
1278 result
1279 _SecureSocketImpl::Bind(const NetEndPoint& localEP)
1280 {
1281     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1282
1283         result r = E_SUCCESS;
1284
1285         NetAddressFamily af;
1286         unsigned long ipAddr = 0;
1287         unsigned short port = 0;
1288         Ip4Address* pIp4Addr = null;
1289         const _NetEndPointImpl* pLocalEPImpl = null;
1290
1291         struct sockaddr_in localAddr;
1292
1293         pLocalEPImpl = _NetEndPointImpl::GetInstance(localEP);
1294
1295         af = pLocalEPImpl->GetNetAddressFamily();
1296         SysTryReturnResult(NID_NET_SOCK, af == NET_AF_IPV4, E_INVALID_ARG, "Address family is invalid.");
1297
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.");
1301
1302         port = pLocalEPImpl->GetPort();
1303
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);
1308
1309         if (bind(__socketFd, (struct sockaddr*) &localAddr, sizeof(localAddr)) < 0)
1310         {
1311                 r = ConvertErrorToResult(errno);
1312                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to bind the socket.");
1313         }
1314
1315         SysLog(NID_NET_SOCK, "bind the socket. [Fd : %d]", __socketFd);
1316
1317         return r;
1318 }
1319
1320 result
1321 _SecureSocketImpl::Listen(int backLog)
1322 {
1323 SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1324
1325         result r = E_SUCCESS;
1326         int err = 0;
1327
1328         _SocketMethodFlag flag = FLAG_NONE;
1329         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
1330
1331         String deviceName;
1332         char* pDeviceName = null;
1333         const _ManagedNetConnectionImpl* pMNCConnImpl = null;
1334         long milliseconds = _THREAD_SLEEP_TIMER; // 2000 milliseconds (sleep time)
1335         int tryCount = 0;
1336
1337         bool isConnectionStarted = false;
1338
1339         if (__pManagedNetConnection != null)
1340         {
1341                 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
1342
1343                 if (__isNonblock == false)
1344                 {
1345                         SysLog(NID_NET_SOCK, "This socket is blocking mode.");
1346
1347                         pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
1348
1349                         // Blocking mode
1350                         while (1)
1351                         {
1352                                 connState = pMNCConnImpl->QueryConnectionState(deviceName);
1353
1354                                 switch (connState)
1355                                 {
1356                                 case NET_CONNECTION_STATE_STARTED:
1357
1358                                 case NET_CONNECTION_STATE_RESUMED:
1359
1360                                 case NET_CONNECTION_STATE_SUSPENDED:
1361                                         SysLog(NID_NET_SOCK, "Network is available.");
1362
1363                                         if (deviceName.IsEmpty())
1364                                         {
1365                                                 SysLog(NID_NET_SOCK, "DeviceName is empty string. - Emulator Case");
1366                                         }
1367                                         else
1368                                         {
1369                                                 SysLog(NID_NET_SOCK, "DeviceName is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
1370
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.");
1373
1374                                                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
1375                                                 delete[] pDeviceName;
1376                                                 if (err < 0)
1377                                                 {
1378                                                         ConvertErrorToResult(errno);
1379                                                         SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Device Name binding is Failed.");
1380                                                 }
1381                                         }
1382
1383                                         err = listen(__socketFd, backLog);
1384                                         break;
1385
1386                                 case NET_CONNECTION_STATE_STARTING:
1387
1388                                 case NET_CONNECTION_STATE_NONE:
1389
1390                                 case NET_CONNECTION_STATE_STOPPING:
1391
1392                                 case NET_CONNECTION_STATE_STOPPED:
1393                                         SysLog(NID_NET_SOCK, "Network is not available.");
1394                                         break;
1395
1396                                 default:
1397                                         SysLog(NID_NET_SOCK, "Should not come here.");
1398                                         break;
1399                                 }
1400
1401                                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
1402                                 {
1403                                         break;
1404                                 }
1405
1406                                 if (connState == NET_CONNECTION_STATE_STOPPED)
1407                                 {
1408                                         r = E_INVALID_CONNECTION;
1409                                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
1410                                         break;
1411                                 }
1412
1413                                 tryCount++;
1414
1415                                 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
1416                                 {
1417                                         r = E_TIMEOUT;
1418                                         SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network is timeout. Try Again");
1419                                         tryCount = 0;
1420                                         break;
1421                                 }
1422
1423                                 Thread::Sleep(milliseconds);
1424                         }
1425                 }
1426                 else
1427                 {
1428                         SysLog(NID_NET_SOCK, "This socket is non-blocking mode.");
1429
1430                         isConnectionStarted = __pManagedNetConnectionEventListener->GetStartedFlag();
1431
1432                         if (isConnectionStarted)
1433                         {
1434                                 err = listen(__socketFd, backLog);
1435                         }
1436                         else
1437                         {
1438                                 r = E_WOULD_BLOCK;
1439                                 flag = FLAG_LISTEN;
1440                                 __pManagedNetConnectionEventListener->SetListenParams(__socketFd, backLog, flag);
1441                         }
1442                 }
1443         }
1444         else
1445         {
1446                 err = listen(__socketFd, backLog);
1447         }
1448
1449         if (err < 0)
1450         {
1451                 r = ConvertErrorToResult(errno);
1452
1453                 if (r != E_WOULD_BLOCK)
1454                 {
1455                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to listen the socket.", GetErrorMessage(r));
1456                         if (__isAsync == true)
1457                         {
1458                                 __isAcceptFired = true;
1459                         }
1460                         goto CATCH;
1461                 }
1462                 else
1463                 {
1464                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to listen the socket.", GetErrorMessage(r));
1465                         __isServer = true;
1466                         if (__isAsync == true)
1467                         {
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);
1472                         }
1473                         goto CATCH;
1474                 }
1475         }
1476
1477         SysLog(NID_NET_SOCK, "Socket is listening. [Fd : %d, backLog : %d]", __socketFd, backLog);
1478
1479         __isServer = true;
1480
1481         if (__isAsync == true)
1482         {
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);
1487         }
1488
1489         return r;
1490
1491 CATCH:
1492         return r;
1493 }
1494
1495 SecureSocket*
1496 _SecureSocketImpl::AcceptN(void)
1497 {
1498         ClearLastResult();
1499
1500         result r = E_SUCCESS;
1501         SecureSocket* pClientSocket = null;
1502         _SecureSocketImpl* pClientSocketImpl = null;
1503         int sslError = 0;
1504         int sslIndex = 0;
1505         int clientFd = INVALID_HANDLE;
1506         unsigned int clientSize = 0;
1507         struct sockaddr_in clientAddr;
1508         char* pCaPath = null;
1509
1510         SysTryReturn(NID_NET_SOCK, __isClosed == false, null, E_INVALID_STATE, "[E_INVALID_STATE] Socket is already closed.");
1511
1512         pthread_mutex_lock(&__mapMutex);
1513
1514         clientSize = sizeof(clientAddr);
1515
1516         clientFd = accept(__socketFd, (struct sockaddr*) &clientAddr, &clientSize);
1517
1518         if (clientFd < 0)
1519         {
1520                 r = ConvertErrorToResult(errno);
1521
1522                 if (r != E_WOULD_BLOCK)
1523                 {
1524                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to accept the socket.", GetErrorMessage(r));
1525                         goto CATCH;
1526                 }
1527                 else
1528                 {
1529                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to accept the socket.", GetErrorMessage(r));
1530                         goto CATCH;
1531                 }
1532         }
1533
1534         if (__isAsync == true)
1535         {
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);
1540         }
1541
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.");
1545
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.");
1548
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.");
1552
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.");
1555
1556         if (__isLoadVerify == false)
1557         {
1558                 // Set default CA path.
1559                 String caPath = _CertService::GetCertificateCrtFilePath();
1560                 SysLog(NID_NET_SOCK, "CA Path(%ls)", caPath.GetPointer());
1561
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.");
1564
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.");
1567
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.");
1570
1571                 __isLoadVerify = true;
1572
1573                 delete[] pCaPath;
1574                 pCaPath = null;
1575         }
1576
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.");
1579
1580         SSL_set_fd(pClientSocketImpl->__pSsl, clientFd);
1581
1582         SSL_set_options(pClientSocketImpl->__pSsl, SSL_OP_ALL);
1583
1584         SSL_set_tmp_rsa_callback(pClientSocketImpl->__pSsl, OnTmpRsaCallback);
1585
1586         //if (__sslVerify == SECURE_SOCKET_VERIFY_NONE)
1587         //{
1588         //      SSL_set_verify(pClientSocketImpl->__pSsl, SSL_VERIFY_PEER, null);
1589         //}
1590
1591         if (__isAsync == true || __isNonblock == true)
1592         {
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.
1597                 //        and so on.
1598                 __sslDepth = _SSL_VERIFY_DEPTH;
1599                 SSL_set_verify_depth(pClientSocketImpl->__pSsl, __sslDepth);
1600
1601                 SSL_set_mode(pClientSocketImpl->__pSsl, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1602
1603                 if ((_Singleton::GetInitialized() == true) && (__pSslKey))
1604                 {
1605                     _Singleton::GetSslMap()->Remove(*__pSslKey, true);
1606                 }
1607
1608                 sslIndex = SSL_get_ex_new_index(0, (char*) "_SecureSocketImpl index", null, null, null);
1609                 SysLog(NID_NET_SOCK, "SSL index(%d).", sslIndex);
1610
1611                 SSL_set_ex_data(pClientSocketImpl->__pSsl, sslIndex, this);
1612
1613                 __pSslKey = new Integer((int) pClientSocketImpl->__pSsl);
1614
1615                 _Singleton::GetSslMap()->Add(*(__pSslKey), *(new Integer((int) sslIndex)));
1616
1617 ssl_accept:
1618                 r = SslAccept(pClientSocketImpl->__pSsl, sslError);
1619                 if ((sslError == SSL_ERROR_WANT_READ) || (sslError == SSL_ERROR_WANT_WRITE))
1620                 {
1621                         goto ssl_accept;
1622                 }
1623                 else if ((r != E_WOULD_BLOCK) && (r != E_SUCCESS))
1624                 {
1625                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to accept the socket.", GetErrorMessage(r));
1626                         goto CATCH;
1627                 }
1628         }
1629         else
1630         {
1631                 r = SslAccept(pClientSocketImpl->__pSsl, sslError);
1632                 if (r != E_SUCCESS)
1633                 {
1634                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to accept the socket.", GetErrorMessage(r));
1635                         goto CATCH;
1636                 }
1637         }
1638
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;
1654
1655         pClientSocket->__pSecureSocketImpl = pClientSocketImpl;
1656
1657         SysLog(NID_NET_SOCK, "New Secure Socket(Child Socket) is created by Server Secure Socket. [ServerFd : %d] [ChildFd : %d]", pClientSocket->__pSecureSocketImpl->__socketFd, __socketFd);
1658
1659         if (__isAsync == true)
1660         {
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.");
1663
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);
1667         }
1668
1669         pthread_mutex_unlock(&__mapMutex);
1670
1671         return pClientSocket;
1672
1673 CATCH:
1674         pthread_mutex_unlock(&__mapMutex);
1675
1676         if (pClientSocket != null)
1677         {
1678                 delete pClientSocket;
1679                 pClientSocket = null;
1680         }
1681
1682         if (pCaPath != null)
1683         {
1684             delete[] pCaPath;
1685             pCaPath = null;
1686         }
1687
1688         SetLastResult(r);
1689         return null;
1690 }
1691
1692 result
1693 _SecureSocketImpl::Close(void)
1694 {
1695     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1696
1697         result r = E_SUCCESS;
1698
1699         int sockFd = __socketFd;
1700         IEnumeratorT<ISecureSocketEventListener*>* pEnum = null;
1701         ISecureSocketEventListener* pSecureSocketEventListener = null;
1702
1703         pEnum = __secureSocketEventListenerList.GetEnumeratorN();
1704
1705         if (pEnum != null)
1706         {
1707                 while (pEnum->MoveNext() == E_SUCCESS)
1708                 {
1709                         r = pEnum->GetCurrent(pSecureSocketEventListener);
1710
1711                         if (pSecureSocketEventListener != null)
1712                         {
1713                                 r = __pSecureSocketEvent->RemoveListener(*pSecureSocketEventListener);
1714                                 r = __secureSocketEventListenerList.Remove(const_cast<ISecureSocketEventListener*>(pSecureSocketEventListener));
1715                         }
1716                 }
1717                 delete pEnum;
1718         }
1719
1720         if (__pGlibSocketInfo != null)
1721         {
1722                 delete __pGlibSocketInfo;
1723                 __pGlibSocketInfo = null;
1724         }
1725
1726         if (__socketFd > INVALID_HANDLE)
1727         {
1728                 if (close(__socketFd) < 0)
1729                 {
1730                         r = ConvertErrorToResult(errno);
1731                         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to close the socket.");
1732                 }
1733
1734                 SysLog(NID_NET_SOCK, "Socket is closed. [Fd : %d]", sockFd);
1735         }
1736
1737         __socketFd = INVALID_HANDLE;
1738         __isClosed = true;
1739
1740         return r;
1741 }
1742
1743 result
1744 _SecureSocketImpl::GetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, int& optionValue) const
1745 {
1746     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1747
1748         result r = E_SUCCESS;
1749         int err = 0;
1750
1751         int optLevel = 0;
1752         int optName = 0;
1753         unsigned int optLen = 0;
1754
1755         struct timeval timeout;
1756
1757         char* pVersion = null;
1758         char* pCipher = null;
1759
1760         switch (optionLevel)
1761         {
1762         case NET_SOCKET_IPPROTO_TCP:
1763                 optLevel = IPPROTO_TCP;
1764
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)))
1767                 {
1768                         r = E_INVALID_ARG;
1769                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1770                         return r;
1771                 }
1772                 break;
1773
1774         case NET_SOCKET_IPPROTO_IP:
1775                 optLevel = IPPROTO_IP;
1776
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)))
1779                 {
1780                         r = E_INVALID_ARG;
1781                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1782                         return r;
1783                 }
1784                 break;
1785
1786         case NET_SOCKET_SOL_SOCKET:
1787                 optLevel = SOL_SOCKET;
1788                 break;
1789
1790         default:
1791                 r = E_INVALID_ARG;
1792                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1793                 return r;
1794         }
1795
1796         switch (optionName)
1797         {
1798         case NET_SOCKET_SO_SSLVERSION:
1799
1800                 if (__pSsl == null)
1801                 {
1802                         optionValue = __sslVersion;
1803                         return r;
1804                 }
1805
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.");
1808
1809                 if (strcmp(pVersion, "SSLv3") == 0)
1810                 {
1811                         optionValue = NET_SOCK_SSL_VERSION_SSLV3;
1812                 }
1813                 else if (strcmp(pVersion, "TLSv1") == 0)
1814                 {
1815                         optionValue = NET_SOCK_SSL_VERSION_TLSV1;
1816                 }
1817                 else
1818                 {
1819                         r = E_SYSTEM;
1820                         SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to get the option value.");
1821                         return r;
1822                 }
1823
1824                 return r;
1825
1826         case NET_SOCKET_SO_SSLCIPHERSUITEID:
1827
1828                 if (__pSsl == null)
1829                 {
1830                         optionValue = __sslCipherSuiteId;
1831                         return r;
1832                 }
1833
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.");
1836
1837                 if (strcmp(pCipher, "RC4-MD5") == 0)
1838                 {
1839                         optionValue = NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_MD5;
1840                 }
1841                 else if (strcmp(pCipher, "RC4-SHA") == 0)
1842                 {
1843                         optionValue = NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_SHA;
1844                 }
1845                 else if (strcmp(pCipher, "DES-CBC-SHA") == 0)
1846                 {
1847                         optionValue = NET_SOCK_TLS_SSL_RSA_WITH_DES_CBC_SHA;
1848                 }
1849                 else if (strcmp(pCipher, "DES-CBC3-SHA") == 0)
1850                 {
1851                         optionValue = NET_SOCK_TLS_SSL_RSA_WITH_3DES_EDE_CBC_SHA;
1852                 }
1853                 else if (strcmp(pCipher, "AES128-SHA") == 0)
1854                 {
1855                         optionValue = NET_SOCK_TLS_SSL_RSA_WITH_AES_128_CBC_SHA;
1856                 }
1857                 else if (strcmp(pCipher, "EXP-DES-CBC-SHA") == 0)
1858                 {
1859                         optionValue = NET_SOCK_TLS_SSL_RSA_EXPORT_WITH_DES40_CBC_SHA;
1860                 }
1861                 else
1862                 {
1863                         r = E_SYSTEM;
1864                         SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to get the option value.");
1865                         return r;
1866                 }
1867
1868                 return r;
1869
1870         case NET_SOCKET_TCP_NODELAY:
1871                 optName = TCP_NODELAY;
1872                 break;
1873
1874         case NET_SOCKET_TCP_MAXSEG:
1875                 optName = TCP_MAXSEG;
1876                 break;
1877
1878         case NET_SOCKET_IP_TTL:
1879                 optName = IP_TTL;
1880                 break;
1881
1882         case NET_SOCKET_IP_TOS:
1883                 optName = IP_TOS;
1884                 break;
1885
1886         case NET_SOCKET_SO_KEEPALIVE:
1887                 optName = SO_KEEPALIVE;
1888                 break;
1889
1890         case NET_SOCKET_SO_OOBINLINE:
1891                 optName = SO_OOBINLINE;
1892                 break;
1893
1894         case NET_SOCKET_SO_RCVBUF:
1895                 optName = SO_RCVBUF;
1896                 break;
1897
1898         case NET_SOCKET_SO_RCVTIMEO:
1899                 optName = SO_RCVTIMEO;
1900                 break;
1901
1902         case NET_SOCKET_SO_REUSEADDR:
1903                 optName = SO_REUSEADDR;
1904                 break;
1905
1906         case NET_SOCKET_SO_SNDBUF:
1907                 optName = SO_SNDBUF;
1908                 break;
1909
1910         case NET_SOCKET_SO_SNDTIMEO:
1911                 optName = SO_SNDTIMEO;
1912                 break;
1913
1914         case NET_SOCKET_SO_TYPE:
1915                 optName = SO_TYPE;
1916                 break;
1917
1918         default:
1919                 r = E_UNSUPPORTED_OPTION;
1920                 SysLogException(NID_NET_SOCK, r, "[E_UNSUPPORTED_OPTION] %d is unsupported", optionName);
1921                 return r;
1922         }
1923
1924         if (optName == SO_RCVTIMEO || optName == SO_SNDTIMEO)
1925         {
1926                 optLen = sizeof(timeout);
1927                 err = getsockopt(__socketFd, optLevel, optName, &timeout, &optLen);
1928                 optionValue = (timeout.tv_sec * 1000) + (timeout.tv_usec / 1000);
1929         }
1930         else
1931         {
1932                 optLen = sizeof(optionValue);
1933                 err = getsockopt(__socketFd, optLevel, optName, (int*) &optionValue, &optLen);
1934         }
1935
1936         if (err < 0)
1937         {
1938                 r = ConvertErrorToResult(errno);
1939                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the option value.", GetErrorMessage(r));
1940         }
1941
1942         return r;
1943 }
1944
1945 result
1946 _SecureSocketImpl::SetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, int optionValue)
1947 {
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.");
1950
1951         result r = E_SUCCESS;
1952         int err = 0;
1953
1954         int optLevel = NET_SOCKET_OPTLEVEL_NONE;
1955         int optName = NET_SOCKET_OPTNAME_NONE;
1956         unsigned int optLen = 0;
1957
1958         struct timeval timeout;
1959
1960         char* pCipher = null;
1961
1962         switch (optionLevel)
1963         {
1964         case NET_SOCKET_IPPROTO_TCP:
1965                 optLevel = IPPROTO_TCP;
1966
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)))
1969                 {
1970                         r = E_INVALID_ARG;
1971                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1972                         return r;
1973                 }
1974                 break;
1975
1976         case NET_SOCKET_IPPROTO_IP:
1977                 optLevel = IPPROTO_IP;
1978
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)))
1981                 {
1982                         r = E_INVALID_ARG;
1983             SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1984                         return r;
1985                 }
1986                 break;
1987
1988         case NET_SOCKET_SOL_SOCKET:
1989                 optLevel = SOL_SOCKET;
1990                 break;
1991
1992         default:
1993                 r = E_INVALID_ARG;
1994         SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used.");
1995                 return r;
1996         }
1997
1998         switch (optionName)
1999         {
2000         case NET_SOCKET_SO_SSLVERSION:
2001
2002                 SSL_CTX_free(__pSslCtx);
2003                 __pSslCtx = null;
2004
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();
2011
2012                 if (optionValue == NET_SOCK_SSL_VERSION_SSLV3)
2013                 {
2014                         __pSslMethod = (SSL_METHOD*) SSLv3_method();
2015                         __sslVersion = NET_SOCK_SSL_VERSION_SSLV3;
2016                 }
2017                 else if (optionValue == NET_SOCK_SSL_VERSION_TLSV1)
2018                 {
2019                         __pSslMethod = (SSL_METHOD*) TLSv1_method();
2020                         __sslVersion = NET_SOCK_SSL_VERSION_TLSV1;
2021                 }
2022
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.");
2025
2026                 return r;
2027
2028         case NET_SOCKET_SO_SSLCIPHERSUITEID:
2029                 if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_MD5)
2030                 {
2031                         pCipher = (char*) "RC4-MD5";
2032                         __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_MD5;
2033                 }
2034                 else if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_SHA)
2035                 {
2036                         pCipher = (char*) "RC4-SHA";
2037                         __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_RC4_128_SHA;
2038                 }
2039                 else if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_DES_CBC_SHA)
2040                 {
2041                         pCipher = (char*) "DES-CBC-SHA";
2042                         __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_DES_CBC_SHA;
2043                 }
2044                 else if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_3DES_EDE_CBC_SHA)
2045                 {
2046                         pCipher = (char*) "DES-CBC3-SHA";
2047                         __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_3DES_EDE_CBC_SHA;
2048                 }
2049                 else if (optionValue == NET_SOCK_TLS_SSL_RSA_WITH_AES_128_CBC_SHA)
2050                 {
2051                         pCipher = (char*) "AES128-SHA";
2052                         __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_WITH_AES_128_CBC_SHA;
2053                 }
2054                 else if (optionValue == NET_SOCK_TLS_SSL_RSA_EXPORT_WITH_DES40_CBC_SHA)
2055                 {
2056                         pCipher = (char*) "EXP-DES-CBC-SHA";
2057                         __sslCipherSuiteId = NET_SOCK_TLS_SSL_RSA_EXPORT_WITH_DES40_CBC_SHA;
2058                 }
2059                 else if (optionValue == NET_SOCK_TLS_SSL_SYSTEM_DEFAULT_CIPHERSUITES)
2060                 {
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;
2063                 }
2064
2065                 if (SSL_CTX_set_cipher_list(__pSslCtx, pCipher) <= 0)
2066                 {
2067                         __sslCipherSuiteId = NET_SOCK_TLS_SSL_NULL_WITH_NULL_NULL;
2068                         SysLog(NID_NET_SOCK, "Failed to the Setting Cipher.");
2069                         r = E_SYSTEM;
2070                 }
2071
2072                 return r;
2073
2074         case NET_SOCKET_SO_SSLCLIENTCERTVERIFY:
2075
2076                 if (__isAsync == true || __isNonblock == true)
2077                 {
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);
2080                 }
2081                 else
2082                 {
2083                         SSL_CTX_set_verify(__pSslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, null);
2084                 }
2085
2086                 __sslVerify = SECURE_SOCKET_VERIFY_ENABLE;
2087
2088                 return r;
2089         case NET_SOCKET_SO_SSLCERTVERIFY:
2090
2091                 if (__isAsync == true || __isNonblock == true)
2092                 {
2093                         if (optionValue > 0)   // Enable SSL Verification
2094                         {
2095                                 __sslVerify = SECURE_SOCKET_VERIFY_ENABLE;
2096                         }
2097                         else if (optionValue == 0) // Disable SSL Verification
2098                         {
2099                                 __sslVerify = SECURE_SOCKET_VERIFY_DISABLE;
2100                         }
2101                 }
2102                 else
2103                 {
2104                         if (optionValue > 0) // Enable SSL Verification
2105                         {
2106                                 __sslVerify = SECURE_SOCKET_VERIFY_ENABLE;
2107                                 SSL_CTX_set_verify(__pSslCtx, SSL_VERIFY_PEER, null);
2108                         }
2109                         else if (optionValue == 0) // Disable SSL Verification
2110                         {
2111                                 __sslVerify = SECURE_SOCKET_VERIFY_DISABLE;
2112                                 SSL_CTX_set_verify(__pSslCtx, SSL_VERIFY_NONE, null);
2113                         }
2114                 }
2115                 return r;
2116
2117         case NET_SOCKET_SO_SSLCERTID:
2118         {
2119                 X509* pCert = null;
2120                 EVP_PKEY* pKey = null;
2121
2122                 _CertServiceProxy* pCertProxy = null;
2123                 pCertProxy = _CertServiceProxy::GetInstance();
2124                 SysTryReturnResult(NID_NET_SOCK, pCertProxy != null, E_OUT_OF_MEMORY, "Memory allocation failed.");
2125
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);
2129
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.");
2133
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);
2137
2138                 if (SSL_CTX_use_certificate(__pSslCtx, pCert) <= 0)
2139                 {
2140                         r = E_SYSTEM;
2141                         SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to load the certificate.");
2142                         goto CATCH;
2143                 }
2144
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.");
2148
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.");
2152
2153                 if (SSL_CTX_use_PrivateKey(__pSslCtx, pKey) <= 0)
2154                 {
2155                         r = E_SYSTEM;
2156                         SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to load the private key.");
2157                         goto CATCH;
2158                 }
2159
2160                 if (SSL_CTX_check_private_key(__pSslCtx) <= 0)
2161                 {
2162                         r = E_SYSTEM;
2163                         SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to check the private key.");
2164                         goto CATCH;
2165                 }
2166
2167                 SysLog(NID_NET_SOCK, "### Certificate loaded successfully. ###");
2168         }
2169                 return r;
2170
2171         case NET_SOCKET_TCP_NODELAY:
2172                 optName = TCP_NODELAY;
2173                 break;
2174
2175         case NET_SOCKET_TCP_MAXSEG:
2176                 optName = TCP_MAXSEG;
2177                 break;
2178
2179         case NET_SOCKET_IP_TTL:
2180                 optName = IP_TTL;
2181                 break;
2182
2183         case NET_SOCKET_IP_TOS:
2184                 optName = IP_TOS;
2185                 break;
2186
2187         case NET_SOCKET_SO_KEEPALIVE:
2188                 optName = SO_KEEPALIVE;
2189                 break;
2190
2191         case NET_SOCKET_SO_OOBINLINE:
2192                 optName = SO_OOBINLINE;
2193                 break;
2194
2195         case NET_SOCKET_SO_RCVBUF:
2196                 optName = SO_RCVBUF;
2197                 break;
2198
2199         case NET_SOCKET_SO_RCVTIMEO:
2200                 optName = SO_RCVTIMEO;
2201                 // milliseconds
2202                 timeout.tv_sec = optionValue / 1000;
2203                 timeout.tv_usec = (optionValue % 1000) * 1000;
2204                 break;
2205
2206         case NET_SOCKET_SO_REUSEADDR:
2207                 optName = SO_REUSEADDR;
2208                 break;
2209
2210         case NET_SOCKET_SO_SNDBUF:
2211                 optName = SO_SNDBUF;
2212                 break;
2213
2214         case NET_SOCKET_SO_SNDTIMEO:
2215                 optName = SO_SNDTIMEO;
2216                 // milliseconds
2217                 timeout.tv_sec = optionValue / 1000;
2218                 timeout.tv_usec = (optionValue % 1000) * 1000;
2219                 break;
2220
2221         default:
2222                 r = E_UNSUPPORTED_OPTION;
2223                 SysLogException(NID_NET_SOCK, r, "[E_UNSUPPORTED_OPTION] %d is unsupported", optionName);
2224                 return r;
2225         }
2226
2227         if (optName == SO_RCVTIMEO || optName == SO_SNDTIMEO)
2228         {
2229                 optLen = sizeof(timeout);
2230                 err = setsockopt(__socketFd, optLevel, optName, (struct timeval*) &timeout, optLen);
2231         }
2232         else
2233         {
2234                 optLen = sizeof(optionValue);
2235                 err = setsockopt(__socketFd, optLevel, optName, (int*) &optionValue, optLen);
2236         }
2237
2238         if (err < 0)
2239         {
2240                 r = ConvertErrorToResult(errno);
2241                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the linger option value.", GetErrorMessage(r));
2242         }
2243
2244         return r;
2245
2246 CATCH:
2247         return r;
2248 }
2249
2250 result
2251 _SecureSocketImpl::AsyncSelectByListener(unsigned long socketEventType)
2252 {
2253     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2254
2255         result r = E_SUCCESS;
2256
2257         if (__pGlibSocketInfo == null)
2258         {
2259                 __pGlibSocketInfo = new (std::nothrow) _GlibSecureSocketInfo();
2260                 SysTryReturnResult(NID_NET_SOCK, __pGlibSocketInfo, E_OUT_OF_MEMORY, "Memory allocation failed.");
2261         }
2262
2263         SysLog(NID_NET_SOCK, "Socket set the socketEvent by AsyncSelectByListener. [Fd : %d]", __socketFd);
2264
2265         __socketEventType = socketEventType;
2266         __isNonblock = true;
2267         __isAsync = true;
2268
2269         return r;
2270 }
2271
2272 result
2273 _SecureSocketImpl::AddSecureSocketListener(ISecureSocketEventListener& listener)
2274 {
2275     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2276
2277         result r = E_SUCCESS;
2278
2279         _EventDispatcher* pEventDispatcher = _EventDispatcher::GetCurrentEventDispatcher();
2280         SysTryReturnResult(NID_NET_SOCK, pEventDispatcher, E_SYSTEM, "GetCurrentEventDispatcher is null.");
2281
2282         __pGMainContext = pEventDispatcher->GetGMainContext();
2283     SysTryReturnResult(NID_NET_SOCK, __pGMainContext, E_SYSTEM, "GetGMainContext is null.");
2284
2285         r = __pSecureSocketEvent->AddListener(listener, true);
2286         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to add the listener.");
2287
2288         r = __secureSocketEventListenerList.Add(&listener);
2289         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to add the listener to the list.");
2290
2291         return r;
2292 }
2293
2294 result
2295 _SecureSocketImpl::RemoveSecureSocketListener(ISecureSocketEventListener& listener)
2296 {
2297         SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2298
2299         result r = E_SUCCESS;
2300
2301         r = __pSecureSocketEvent->RemoveListener(listener);
2302         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to remove the listener.");
2303
2304         r = __secureSocketEventListenerList.Remove(&listener);
2305         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to remove the listener to the list.");
2306
2307         return r;
2308 }
2309
2310 int
2311 _SecureSocketImpl::GetSecureSocketFd(void)
2312 {
2313         SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2314
2315         return __socketFd;
2316 }
2317
2318 Object*
2319 _SecureSocketImpl::Run(void)
2320 {
2321         result r = E_SUCCESS;
2322
2323         int sslError = 0;
2324
2325 ssl_connect:
2326         r = SslConnect(sslError);
2327         if ((sslError == SSL_ERROR_WANT_READ) || (sslError == SSL_ERROR_WANT_WRITE) || (sslError == SSL_ERROR_WANT_CONNECT))
2328         {
2329                         goto ssl_connect;
2330         }
2331
2332         SysLog(NID_NET_SOCK, "Worker thread finished. - SslConnect::Run()");
2333
2334         if (__isAsync == true)
2335         {
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);
2340         }
2341
2342         return null;
2343 }
2344
2345 SecureSocket*
2346 _SecureSocketImpl::GetSecureSocket(void) const
2347 {
2348         return __pSecureSocket;
2349 }
2350
2351 _SecureSocketImpl*
2352 _SecureSocketImpl::GetInstance(SecureSocket& secureSocket)
2353 {
2354         return secureSocket.__pSecureSocketImpl;
2355 }
2356
2357 const _SecureSocketImpl*
2358 _SecureSocketImpl::GetInstance(const SecureSocket& secureSocket)
2359 {
2360         return secureSocket.__pSecureSocketImpl;
2361 }
2362
2363 result
2364 _SecureSocketImpl::Dispose(void)
2365 {
2366         SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2367
2368         result r = E_SUCCESS;
2369
2370         r = Close();
2371         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to close the socket.");
2372
2373         __isClosed = true;
2374
2375         return r;
2376 }
2377
2378 // glib event
2379 gboolean
2380 _SecureSocketImpl::OnGioEventCallback(GIOChannel* pSource, GIOCondition condition, gpointer pUserData)
2381 {
2382         SysLog(NID_NET_SOCK, "### OnGioEventCallback ###");
2383
2384         result errorCode = E_SUCCESS;
2385         GIOStatus status = G_IO_STATUS_NORMAL;
2386         gchar buffer[1024];
2387         gsize bytes_read = 0;
2388         int readSize = 0;
2389         char peekBuf = '\0';
2390         int connStatus = 0;
2391         int sslError = 0;
2392         int timerId = INVALID_HANDLE;
2393         int error = 0;
2394
2395         _SecureUserData* pRecvUserData = (_SecureUserData*) pUserData;
2396
2397         _SecureSocketEventArg* pEventArg = null;
2398
2399         _SecureSocketImpl* pSecureSocketImpl = static_cast <_SecureSocketImpl*>(pRecvUserData->pSecureSocketImpl);
2400         GSource* pGSource = static_cast <GSource*>(pRecvUserData->pGSource);
2401
2402         SysLog(NID_NET_SOCK, "====> [Event] OnGioEventCallback : All GIO event is received.(%d).", condition);
2403
2404         if (condition & G_IO_ERR)
2405         {
2406             SysLog(NID_NET_SOCK, "====> [Event] Socket event is received.(G_IO_ERR)");
2407
2408                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSecureSocketImpl->__isCloseFired == false))
2409                 {
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);
2418
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));
2421
2422                         goto CATCH;
2423                 }
2424         }
2425
2426         if (pSecureSocketImpl->__isServer)  // For Server
2427         {
2428                 SysLog(NID_NET_SOCK, "====> [Event] This is secure socket server");
2429
2430                 if (condition & G_IO_IN)
2431                 {
2432                         SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received(G_IO_IN).");
2433
2434                         struct pollfd fds[1];
2435                         fds[0].fd = pSecureSocketImpl->__socketFd;
2436                         fds[0].events = POLLRDHUP;
2437
2438                         error = poll(fds, 1, 0);
2439                         SysTryCatch(NID_NET_SOCK, error != -1, , null, "Failed to the poll");
2440
2441                         if (fds[0].revents & POLLRDHUP)
2442                         {
2443                                 SysLog(NID_NET_SOCK, "====> Socket is not available.(POLLRDHUP)");
2444
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);
2447
2448                                 if (readSize <= 0)
2449                                 {
2450                                         if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSecureSocketImpl->__isCloseFired == false))
2451                                         {
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);
2460
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));
2463
2464                                                 goto CATCH;
2465                                         }
2466                                 }
2467                                 else
2468                                 {
2469                                         connStatus = SSL_peek(pSecureSocketImpl->__pSsl, (char*) &peekBuf, 1);
2470                                         SysLog(NID_NET_SOCK, "Connection Status : %d.", connStatus);
2471
2472                                         sslError = SSL_get_error(pSecureSocketImpl->__pSsl, connStatus);
2473
2474                                         // Error code mapping
2475                                         switch (sslError)
2476                                         {
2477                                         case SSL_ERROR_ZERO_RETURN:
2478                                                 SysLog(NID_NET_SOCK, "Connection closed by peer : %d.", sslError);
2479                                                 break;
2480
2481                                         default:
2482                                                 SysLog(NID_NET_SOCK, "Connection is active : %d.", sslError);
2483                                                 break;
2484                                         }
2485
2486                                         if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2487                                                         (pSecureSocketImpl->__isCloseFired == false) && (connStatus == 0))
2488                                         {
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);
2497
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));
2500
2501                                                 goto CATCH;
2502                                         }
2503                                 }
2504                         }
2505                         else
2506                         {
2507                                 SysLog(NID_NET_SOCK, "====> SOCKET is available.(Not POLLRDHUP)");
2508
2509                                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_ACCEPT) && (pSecureSocketImpl->__isAcceptFired == false) &&
2510                                                 (pSecureSocketImpl->__isCloseFired == false))
2511                                 {
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);
2516
2517                                         goto CATCH;
2518                                 }
2519                         }
2520                 }
2521
2522                 if (condition & G_IO_OUT)
2523                 {
2524                     SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_OUT).");
2525                 }
2526
2527         }
2528         else  // For Client
2529         {
2530                 SysLog(NID_NET_SOCK, "====> [Event] This is Secure socket client");
2531
2532                 if (condition & G_IO_IN)
2533                 {
2534                     SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_IN).");
2535
2536                         if (pSecureSocketImpl->__isRunFinished == true)
2537                         {
2538                                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2539                                                 (pSecureSocketImpl->__isConnectFailed == true) && (pSecureSocketImpl->__isCloseFired == false))
2540                                 {
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);
2548
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));
2551
2552                                         goto CATCH;
2553                                 }
2554
2555                                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2556                                                 (pSecureSocketImpl->__isClientNoCert == true) && (pSecureSocketImpl->__isCloseFired == false))
2557                                 {
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);
2564
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));
2567
2568                                         goto CATCH;
2569                                 }
2570
2571                                 struct pollfd fds[1];
2572                                 fds[0].fd = pSecureSocketImpl->__socketFd;
2573                                 fds[0].events = POLLRDHUP;
2574
2575                     error = poll(fds, 1, 0);
2576                     SysTryCatch(NID_NET_SOCK, error != -1, , null, "Failed to the poll");
2577
2578                                 if (fds[0].revents & POLLRDHUP)
2579                                 {
2580                                         SysLog(NID_NET_SOCK, "====> Socket is not available.(POLLRDHUP)");
2581
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);
2585
2586                                         if (readSize <= 0)
2587                                         {
2588                                                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2589                                                                 (pSecureSocketImpl->__isCloseFired == false))
2590                                                 {
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);
2598
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));
2601
2602                                                         goto CATCH;
2603                                                 }
2604                                         }
2605                                         else
2606                                         {
2607                                                 connStatus = SSL_peek(pSecureSocketImpl->__pSsl, (char*) &peekBuf, 1);
2608                                                 SysLog(NID_NET_SOCK, "Connection Status : %d.", connStatus);
2609
2610                                                 sslError = SSL_get_error(pSecureSocketImpl->__pSsl, connStatus);
2611
2612                                                 // Error code mapping
2613                                                 switch (sslError)
2614                                                 {
2615                                                 case SSL_ERROR_ZERO_RETURN:
2616                                                         SysLog(NID_NET_SOCK, "Connection closed by peer : %d.", sslError);
2617                                                         break;
2618
2619                                                 default:
2620                                                         SysLog(NID_NET_SOCK, "Connection is active : %d.", sslError);
2621                                                         break;
2622                                                 }
2623
2624                                                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_READ) &&
2625                                                                 (pSecureSocketImpl->__isConnectFired == true) && (pSecureSocketImpl->__isReadFired == false) &&
2626                                                                 (pSecureSocketImpl->__isCloseFired == false) && (connStatus > 0))
2627                                                 {
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);
2632
2633                                                         goto CATCH;
2634                                                 }
2635
2636                                                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2637                                                                 (pSecureSocketImpl->__isCloseFired == false) && (connStatus == 0))
2638                                                 {
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);
2647
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));
2650
2651                                                         goto CATCH;
2652                                                 }
2653                                         }
2654                                 }
2655                                 else
2656                                 {
2657                                         SysLog(NID_NET_SOCK, "====> Socket is available.(Not POLLRDHUP)");
2658
2659                                         connStatus = SSL_peek(pSecureSocketImpl->__pSsl, (char*) &peekBuf, 1);
2660                                         SysLog(NID_NET_SOCK, "Connection Status : %d.", connStatus);
2661
2662                                         sslError = SSL_get_error(pSecureSocketImpl->__pSsl, connStatus);
2663
2664                                         // Error code mapping
2665                                         switch (sslError)
2666                                         {
2667                                         case SSL_ERROR_ZERO_RETURN:
2668                                                 SysLog(NID_NET_SOCK, "Connection closed by peer : %d.", sslError);
2669                                                 break;
2670
2671                                         default:
2672                                                 SysLog(NID_NET_SOCK, "Connection is active : %d.", sslError);
2673                                                 break;
2674                                         }
2675
2676                                         if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_READ) &&
2677                                                         (pSecureSocketImpl->__isConnectFired == true) && (pSecureSocketImpl->__isReadFired == false) &&
2678                                                         (pSecureSocketImpl->__isCloseFired == false) && (connStatus > 0))
2679                                         {
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);
2684
2685                                                 goto CATCH;
2686                                         }
2687
2688                                         if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) &&
2689                                                         (pSecureSocketImpl->__isCloseFired == false) && (connStatus == 0))
2690                                         {
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);
2699
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));
2702
2703                                                 goto CATCH;
2704                                         }
2705                                 }
2706                         }
2707                 }
2708
2709                 if (condition & G_IO_OUT)
2710                 {
2711                     SysLog(NID_NET_SOCK, "====> [Evesnt] Secure socket event is Received.(G_IO_OUT).");
2712
2713                         if (pSecureSocketImpl->__isWriteFired == true)
2714                         {
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);
2718
2719                                 goto CATCH;
2720                         }
2721
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))
2726                         {
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);
2731
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);
2736
2737                                 goto CATCH;
2738                         }
2739
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))
2743                         {
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);
2748
2749                                 goto CATCH;
2750                         }
2751                 }
2752         }
2753
2754         if (condition & G_IO_PRI)
2755         {
2756                 SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_PRI).");
2757         }
2758
2759         if (condition & G_IO_HUP)
2760         {
2761         SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_HUP).");
2762         }
2763
2764         if (condition & G_IO_NVAL)
2765         {
2766         SysLog(NID_NET_SOCK, "====> [Event] Secure socket event is received.(G_IO_NVAL).");
2767         }
2768
2769         return true;
2770
2771 CATCH:
2772         return true;
2773 }
2774
2775 void
2776 _SecureSocketImpl::SetTimer(void)
2777 {
2778         int timerId = -1;
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);
2783
2784         timerId = g_source_get_id(__pTimerSource);
2785         SysLog(NID_NET_SOCK, "Created the TimerSource[%d], timeout[%d].", timerId, _SECURE_SOCKET_CONNECTION_TIMEOUT * 1000);
2786 }
2787
2788 gboolean
2789 _SecureSocketImpl::OnTimerExpiredEvent(gpointer data)
2790 {
2791         SysLog(NID_NET_SOCK, "### OnTimerExpiredEvent ###");
2792
2793         _SecureSocketImpl* pSecureSocketImpl = null;
2794         _SecureSocketEventArg* pEventArg = null;
2795
2796         int timerId = -1;
2797
2798         pSecureSocketImpl = static_cast <_SecureSocketImpl*>(data);
2799
2800         if (pSecureSocketImpl->__pTimerSource != null)
2801         {
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);
2806
2807                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSecureSocketImpl->__isCloseFired == false))
2808                 {
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);
2813                 }
2814         }
2815
2816         return true;
2817 }
2818
2819 int
2820 _SecureSocketImpl::OnVerifyPeerCallback(int preverify_ok, X509_STORE_CTX* pX509Ctx)
2821 {
2822         SysLog(NID_NET_SOCK, "### OnVerifyPeerCallback ###");
2823
2824         _SecureSocketImpl* pSecureSocketImpl = null;
2825         _SecureSocketEventArg* pEventArg = null;
2826         X509* pServerCert = null;
2827         SSL* pSsl = null;
2828         char* pX509Field = null;
2829         Integer* pSslTemp = null;
2830         Integer* pVal = null;
2831         int sslIndex = 0;
2832         int sslError = 0;
2833         int depth = 0;
2834
2835         pServerCert = X509_STORE_CTX_get_current_cert(pX509Ctx);
2836
2837         if (pServerCert != null)
2838         {
2839                 pX509Field = X509_NAME_oneline(X509_get_subject_name(pServerCert), 0, 0);
2840                 SysLog(NID_NET_SOCK, "Certificate: [Subject: %s]", pX509Field);
2841
2842                 OPENSSL_free(pX509Field);
2843
2844                 pX509Field = X509_NAME_oneline(X509_get_issuer_name(pServerCert), 0, 0);
2845                 SysLog(NID_NET_SOCK, "Certificate: [Issuer: %s]", pX509Field);
2846
2847                 OPENSSL_free(pX509Field);
2848         }
2849
2850         sslIndex = SSL_get_ex_data_X509_STORE_CTX_idx();
2851         SysLog(NID_NET_SOCK, "SSL index(%d).", sslIndex);
2852
2853         pSsl = (SSL*) X509_STORE_CTX_get_ex_data(pX509Ctx, sslIndex);
2854         if (pSsl == null)
2855         {
2856                 SysLog(NID_NET_SOCK, "Failed to get the SSL object.");
2857                 goto CATCH;
2858         }
2859
2860         pSslTemp = new (std::nothrow) Integer((int)pSsl);
2861
2862         pthread_mutex_lock(&__mapMutex);
2863
2864         pVal = static_cast<Integer*>(_Singleton::GetSslMap()->GetValue(*pSslTemp));
2865         if (pVal == null)
2866         {
2867                 SysLog(NID_NET_SOCK, "Failed to get the SSL Object.");
2868                 pthread_mutex_unlock(&__mapMutex);
2869                 goto CATCH;
2870         }
2871
2872         sslIndex = pVal->ToInt();
2873         SysLog(NID_NET_SOCK, "Application index(%d).", sslIndex);
2874
2875         pthread_mutex_unlock(&__mapMutex);
2876
2877         delete pSslTemp;
2878
2879         pSecureSocketImpl = static_cast <_SecureSocketImpl*>(SSL_get_ex_data((SSL*) pSsl, sslIndex));
2880         if (pSecureSocketImpl == null)
2881         {
2882                 SysLog(NID_NET_SOCK, "Failed to get the _SecureSocketImpl object.");
2883                 goto CATCH;
2884         }
2885
2886         depth = X509_STORE_CTX_get_error_depth(pX509Ctx);
2887         if (depth > pSecureSocketImpl->__sslDepth)
2888         {
2889                 sslError = X509_V_ERR_CERT_CHAIN_TOO_LONG;
2890                 X509_STORE_CTX_set_error(pX509Ctx, sslError);
2891                 goto CATCH;
2892         }
2893
2894         sslError = X509_STORE_CTX_get_error(pX509Ctx);
2895         if (sslError == X509_V_OK)
2896         {
2897                 pSecureSocketImpl->__isCertVerifyFailed = false;
2898                 SysLog(NID_NET_SOCK, "Verification is success.");
2899         }
2900         else
2901         {
2902                 SysLog(NID_NET_SOCK, "Failed to the peer certificate validation(%d).", sslError);
2903
2904                 if ((pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_SERVCERT_FAIL) && (pSecureSocketImpl->__isCloseFired == false)
2905                                 && (pSecureSocketImpl->__isCertVerifyFailed == false))
2906                 {
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.");
2909
2910                         // Fire the event(NET_SOCKET_EVENT_SERVCERT_FAIL)
2911                         pSecureSocketImpl->__pSecureSocketEvent->Fire(*pEventArg);
2912
2913                         pSecureSocketImpl->__isCertVerifyFailed = true;
2914
2915                         pSecureSocketImpl->SetTimer();
2916                 }
2917                 else if (!(pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_SERVCERT_FAIL) && (pSecureSocketImpl->__sslVerify == SECURE_SOCKET_VERIFY_DISABLE))
2918                 {
2919                         return 1;
2920                 }
2921                 else if (!(pSecureSocketImpl->__socketEventType & NET_SOCKET_EVENT_SERVCERT_FAIL))
2922                 {
2923                         goto CATCH;
2924                 }
2925         }
2926
2927         return 1;
2928
2929 CATCH:
2930         return 0;
2931 }
2932
2933 int
2934 _SecureSocketImpl::OnVerifyClientCallback(int preverify_ok, X509_STORE_CTX* pX509Ctx)
2935 {
2936         SysLog(NID_NET_SOCK, "### OnVerifyClientCallback ###");
2937
2938         _SecureSocketImpl* pSecureSocketImpl = null;
2939         X509* pClientCert = null;
2940         SSL* pSsl = null;
2941         char* pX509Field = null;
2942         Integer* pSslTemp = null;
2943         Integer* pVal = null;
2944         int sslIndex = 0;
2945         int sslError = 0;
2946         int depth = 0;
2947
2948         pClientCert = X509_STORE_CTX_get_current_cert(pX509Ctx);
2949
2950         if (pClientCert != null)
2951         {
2952                 pX509Field = X509_NAME_oneline(X509_get_subject_name(pClientCert), 0, 0);
2953                 SysLog(NID_NET_SOCK, "Certificate: [Subject: %s]", pX509Field);
2954
2955                 OPENSSL_free(pX509Field);
2956
2957                 pX509Field = X509_NAME_oneline(X509_get_issuer_name(pClientCert), 0, 0);
2958                 SysLog(NID_NET_SOCK, "Certificate: [Issuer: %s]", pX509Field);
2959
2960                 OPENSSL_free(pX509Field);
2961         }
2962
2963         sslIndex = SSL_get_ex_data_X509_STORE_CTX_idx();
2964         SysLog(NID_NET_SOCK, "SSL index(%d).", sslIndex);
2965
2966         pSsl = (SSL*) X509_STORE_CTX_get_ex_data(pX509Ctx, sslIndex);
2967         if (pSsl == null)
2968         {
2969                 SysLog(NID_NET_SOCK, "Failed to get the SSL object.");
2970                 goto CATCH;
2971         }
2972
2973         pSslTemp = new Integer((int)pSsl);
2974
2975         pthread_mutex_lock(&__mapMutex);
2976
2977         pVal = static_cast<Integer*>(_Singleton::GetSslMap()->GetValue(*pSslTemp));
2978         if (pVal == null)
2979         {
2980                 SysLog(NID_NET_SOCK, "Failed to get the SSL Object.");
2981                 pthread_mutex_unlock(&__mapMutex);
2982                 goto CATCH;
2983         }
2984
2985         sslIndex = pVal->ToInt();
2986         SysLog(NID_NET_SOCK, "Application index(%d).", sslIndex);
2987
2988         pthread_mutex_unlock(&__mapMutex);
2989
2990         delete pSslTemp;
2991
2992         pSecureSocketImpl = static_cast <_SecureSocketImpl*>(SSL_get_ex_data((SSL*) pSsl, sslIndex));
2993         if (pSecureSocketImpl == null)
2994         {
2995                 SysLog(NID_NET_SOCK, "Failed to get the _SecureSocketImpl object.");
2996                 goto CATCH;
2997         }
2998
2999         depth = X509_STORE_CTX_get_error_depth(pX509Ctx);
3000         if (depth > pSecureSocketImpl->__sslDepth)
3001         {
3002                 sslError = X509_V_ERR_CERT_CHAIN_TOO_LONG;
3003                 X509_STORE_CTX_set_error(pX509Ctx, sslError);
3004                 goto CATCH;
3005         }
3006
3007         sslError = X509_STORE_CTX_get_error(pX509Ctx);
3008         if (sslError == X509_V_OK)
3009         {
3010                 SysLog(NID_NET_SOCK, "Verification of client certificate is success.");
3011         }
3012         else
3013         {
3014                 SysLog(NID_NET_SOCK, "Failed to the client certificate validation(%d).", sslError);
3015                 goto CATCH;
3016         }
3017
3018         return 1;
3019
3020 CATCH:
3021         return 0;
3022 }
3023
3024 int
3025 _SecureSocketImpl::OnClientCertCallback(SSL* pSsl, X509** ppX509, EVP_PKEY** ppKey)
3026 {
3027         SysLog(NID_NET_SOCK, "### OnClientCertCallback ###");
3028
3029         _SecureSocketImpl* pSecureSocketImpl = null;
3030
3031         int sslIndex = 0;
3032         Integer* pSslTemp = null;
3033         Integer* pVal = null;
3034
3035         pSslTemp = new (std::nothrow) Integer((int)pSsl);
3036
3037         pthread_mutex_lock(&__mapMutex);
3038
3039         pVal = static_cast<Integer*>(_Singleton::GetSslMap()->GetValue(*pSslTemp));
3040         if (pVal == null)
3041         {
3042                 SysLog(NID_NET_SOCK, "Failed to get the SSL Object.");
3043                 pthread_mutex_unlock(&__mapMutex);
3044                 goto CATCH;
3045         }
3046
3047         sslIndex = pVal->ToInt();
3048         SysLog(NID_NET_SOCK, "Application index(%d).", sslIndex);
3049
3050         pthread_mutex_unlock(&__mapMutex);
3051
3052         delete pSslTemp;
3053
3054         pSecureSocketImpl = static_cast <_SecureSocketImpl*>(SSL_get_ex_data((SSL*) pSsl, sslIndex));
3055         if (pSecureSocketImpl == null)
3056         {
3057                 SysLog(NID_NET_SOCK, "Failed to get the _SecureSocketImpl object.");
3058                 goto CATCH;
3059         }
3060
3061         pSecureSocketImpl->__isClientNoCert = true;
3062
3063 CATCH:
3064         return 0;
3065 }
3066
3067 RSA*
3068 _SecureSocketImpl::OnTmpRsaCallback(SSL* pSsl, int isexport, int keylength)
3069 {
3070         SysLog(NID_NET_SOCK, "### OnTmpRsaCallback ###");
3071
3072         RSA* pRsa = null;
3073
3074         switch (keylength)
3075         {
3076         case _RSA_512_KEY:
3077                 pRsa = RSA_generate_key(512, RSA_F4, null, null);
3078                 break;
3079         case _RSA_1024_KEY:
3080                 pRsa = RSA_generate_key(1024, RSA_F4, null, null);
3081                 break;
3082         default:
3083                 break;
3084         }
3085
3086         return pRsa;
3087 }
3088
3089 result
3090 _SecureSocketImpl::SslConnect(int& sslError)
3091 {
3092         result r = E_SUCCESS;
3093
3094         // char* pErrReason = null;
3095         unsigned long errCode = 0;
3096
3097         // Perform the SSL Handshake
3098         sslError = SSL_connect(__pSsl);
3099
3100         if (sslError < 1)
3101         {
3102                 sslError = SSL_get_error(__pSsl, sslError);
3103
3104                 // sslv3 alert handshake failure
3105                 // pErrReason = (char*) ERR_reason_error_string(ERR_get_error());
3106
3107                 errCode = ERR_GET_REASON(ERR_get_error());
3108
3109                 switch (sslError)
3110                 {
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)))
3115                         {
3116                                 __isConnectFailed = true;
3117                                 r = E_SYSTEM;
3118                         }
3119                         break;
3120
3121                 case SSL_ERROR_SYSCALL: // I/O Error Occurred.
3122                         SysLog(NID_NET_SOCK, "SslConnect - SSL_ERROR_SYSCALL");
3123                         __isConnectFailed = true;
3124                         r = E_SYSTEM;
3125                         break;
3126
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;
3130                         r = E_SYSTEM;
3131                         break;
3132
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");
3137                         r = E_WOULD_BLOCK;
3138                         break;
3139
3140                 default:
3141                         SysLog(NID_NET_SOCK, "SslConnect - default");
3142                         __isConnectFailed = true;
3143                         r = E_SYSTEM;
3144                         break;
3145                 }
3146
3147                 if (r != E_WOULD_BLOCK)
3148                 {
3149                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to perform the handshake.", GetErrorMessage(r));
3150                 }
3151
3152                 goto CATCH;
3153         }
3154         else
3155         {
3156                 SysLog(NID_NET_SOCK, "SslConnect - SSL_connect is success.");
3157
3158                 if (__isAsync == true)
3159                 {
3160                         __isSslConnected = true;
3161                 }
3162         }
3163
3164         return r;
3165
3166 CATCH:
3167         if (__isAsync == true)
3168         {
3169                 __isSslConnected = false;
3170         }
3171         return r;
3172 }
3173
3174 result
3175 _SecureSocketImpl::SslAccept(SSL* pSsl, int& sslError)
3176 {
3177         result r = E_SUCCESS;
3178
3179         //char* pErrReason = null;
3180         unsigned long errCode = 0;
3181
3182         sslError = SSL_accept(pSsl);
3183
3184         if (sslError < 1)
3185         {
3186                 sslError = SSL_get_error(pSsl, sslError);
3187
3188                 //sslv3 alert handshake failure
3189                 //pErrReason = (char*) ERR_reason_error_string(ERR_get_error());
3190
3191                 errCode = ERR_GET_REASON(ERR_get_error());
3192
3193                 switch (sslError)
3194                 {
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)))
3200                         {
3201                                 __isAcceptFailed = true;
3202                                 r = E_SYSTEM;
3203                         }
3204                         break;
3205
3206                 case SSL_ERROR_SYSCALL:     // I/O Error Occurred.
3207                         SysLog(NID_NET_SOCK, "SslAccept - SSL_ERROR_SYSCALL");
3208                         __isAcceptFailed = true;
3209                         r = E_SYSTEM;
3210                         break;
3211
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;
3215                         r = E_SYSTEM;
3216                         break;
3217
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");
3221                         r = E_WOULD_BLOCK;
3222                         break;
3223
3224                 default:
3225                         SysLog(NID_NET_SOCK, "SslAccept - default");
3226                         __isAcceptFailed = true;
3227                         r = E_SYSTEM;
3228                         break;
3229
3230                 }
3231
3232                 if (r != E_WOULD_BLOCK)
3233                 {
3234                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to perform the handshake.", GetErrorMessage(r));
3235                 }
3236
3237                 goto CATCH;
3238         }
3239         else
3240         {
3241                 SysLog(NID_NET_SOCK, "SslAccept - SSL_accept is success.");
3242
3243                 if (__isAsync == true)
3244                 {
3245                         __isSslAccepted = true;
3246                 }
3247         }
3248
3249         return r;
3250
3251 CATCH:
3252         if (__isAsync == true)
3253         {
3254                 __isSslAccepted = false;
3255         }
3256         return r;
3257 }
3258
3259 result
3260 _SecureSocketImpl::ConvertSslError(int sslError)
3261 {
3262         result r = E_SUCCESS;
3263
3264         SysLog(NID_NET_SOCK, "SSL error code (%d).", sslError);
3265
3266         switch (sslError)
3267         {
3268         case SSL_R_READ_TIMEOUT_EXPIRED:
3269                 r = E_TIMEOUT;
3270                 break;
3271         case SSL_R_BAD_RESPONSE_ARGUMENT:
3272                 r = E_INVALID_ARG;
3273                 break;
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;
3282                 break;
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;
3290                 break;
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;
3296                 break;
3297         case SSL_R_NO_SHARED_CIPHER: // Host(server) has no certificate in server side. Certificates are not loaded to ssl.
3298                 r = E_SYSTEM;
3299                 break;
3300         case SSL_R_CERTIFICATE_VERIFY_FAILED: // Failed to the verification of server certificate in client side.
3301                 r = E_CERTIFICATE_VERIFICATION_FAILED;
3302                 break;
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;
3311                 break;
3312         case SSL_R_BAD_DECOMPRESSION:
3313         case SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE:
3314                 r = E_INVALID_DATA;
3315                 break;
3316         case SSL_R_SSLV3_ALERT_BAD_RECORD_MAC:
3317                 r = E_INVALID_STATE;
3318                 break;
3319         case SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
3320                 r = E_SYSTEM;
3321                 break;
3322         case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
3323                 r = E_INVALID_KEY;
3324                 break;
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;
3358                 break;
3359         case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
3360         case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
3361                 r = E_NO_CERTIFICATE;
3362                 break;
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;
3368                 break;
3369         case SSL_R_WRONG_VERSION_NUMBER:
3370         case SSL_R_WRONG_SSL_VERSION:
3371                 r = E_UNSUPPORTED_VERSION;
3372                 break;
3373         default:
3374                 break;
3375
3376         }
3377
3378         return r;
3379 }
3380
3381 _GlibSecureSocketInfo::_GlibSecureSocketInfo(void)
3382         : __pSocketChannel(null)
3383         , __pSocketSource(null)
3384         , __socketFd(INVALID_HANDLE)
3385         , __pUserData(null)
3386 {
3387 }
3388
3389 _GlibSecureSocketInfo::~_GlibSecureSocketInfo(void)
3390 {
3391         if (__pSocketSource != null)
3392         {
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;
3398         }
3399
3400         if (__pSocketChannel != null)
3401         {
3402                 g_io_channel_unref(__pSocketChannel);
3403                 __pSocketChannel = null;
3404         }
3405
3406         if (__pUserData)
3407         {
3408                 delete __pUserData;
3409                 __pUserData = null;
3410         }
3411 }
3412
3413 result
3414 _GlibSecureSocketInfo::SetSocketEvent(_SecureSocketImpl* pSecureSocketImpl, HSocket socketFd)
3415 {
3416         result r = E_SUCCESS;
3417
3418         GIOCondition condition = (GIOCondition)0;
3419
3420         if (__pSocketChannel == null)
3421         {
3422                 __pUserData = new (std::nothrow) _SecureUserData;
3423                 SysTryReturnResult(NID_NET_SOCK, __pUserData, E_OUT_OF_MEMORY, "Memory allocation failed.");
3424
3425                 __pSocketChannel = g_io_channel_unix_new(socketFd);
3426                 SysLog(NID_NET_SOCK, "Created the SocketChannel. [Fd : %d]", socketFd);
3427         }
3428
3429         // Set masking of wanted socket Event
3430         if (pSecureSocketImpl->__isWriteFired == false)
3431         {
3432                 condition = static_cast <GIOCondition>(G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3433         }
3434         else
3435         {
3436                 condition = static_cast <GIOCondition>(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3437         }
3438
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
3445
3446         if (__pSocketSource != null)
3447         {
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.");
3454         }
3455
3456         __pSocketSource = g_io_create_watch(__pSocketChannel, condition);
3457
3458         __pUserData->pSecureSocketImpl = (_SecureSocketImpl*) pSecureSocketImpl;
3459         __pUserData->pGSource = (GSource*) __pSocketSource;
3460
3461         g_source_set_callback(__pSocketSource, (GSourceFunc) _SecureSocketImpl::OnGioEventCallback, __pUserData, null);
3462         g_source_attach(__pSocketSource, pSecureSocketImpl->__pGMainContext);
3463
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);
3466
3467         return r;
3468 }
3469
3470 } } } // Tizen::Net::Sockets