merge with master
[framework/osp/net.git] / src / sockets / FNetSock_SocketImpl.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_SocketImpl.cpp
20  * @brief               This is the implementation for the _SocketImpl class.
21  */
22
23 #include <unique_ptr.h>
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <sys/ioctl.h>
27 #include <fcntl.h>
28 #include <netdb.h>
29 #include <arpa/inet.h>
30 #include <unistd.h>
31 #include <netinet/in.h>
32 #include <netinet/tcp.h>
33 #include <sys/select.h>
34 #include <sys/time.h>
35 #include <errno.h>
36 #include <poll.h>
37 #include <FNetNetTypes.h>
38 #include <FNetSockSocket.h>
39 #include <FNetNetEndPoint.h>
40 #include <FNetIpAddress.h>
41 #include <FNetIp4Address.h>
42 #include <FNetNetConnection.h>
43 #include <FNetNetConnectionManager.h>
44 #include <FBaseSysLog.h>
45 #include "FBase_StringConverter.h"
46 #include "FBaseRt_EventDispatcher.h"
47 #include "FApp_AppInfo.h"
48 #include "FNet_NetEndPointImpl.h"
49 #include "FNet_Ip4AddressImpl.h"
50 #include "FNet_NetConnectionManagerImpl.h"
51 #include "FNet_ManagedNetConnectionImpl.h"
52 #include "FNet_NetConnectionInfoImpl.h"
53 #include "FNet_NetConnectionImpl.h"
54 #include "FNetSock_SocketInternalHelp.h"
55 #include "FNetSock_SocketEventArg.h"
56 #include "FNetSock_SocketInternalHelp.h"
57 #include "FNetSock_LingerOptionImpl.h"
58 #include "FNetSock_IpMulticastRequestOptionImpl.h"
59 #include "FNetSock_SocketManagedNetConnectionEventListenerImpl.h"
60 #include "FNetSock_SocketCustomNetConnectionEventListenerImpl.h"
61 #include "FNetSock_SocketImpl.h"
62
63 using namespace std;
64 using namespace Tizen::Base;
65 using namespace Tizen::Base::Runtime;
66 using namespace Tizen::Base::Collection;
67 using namespace Tizen::Base::Utility;
68 using namespace Tizen::Net;
69 using namespace Tizen::App;
70
71 namespace Tizen { namespace Net { namespace Sockets
72 {
73
74 static const long _THREAD_SLEEP_TIMER = 2000; // 2000 milliseconds = 2 seconds (sleep time)
75 static const long _MAX_COUNT_THREAD_SLEEP_TIMER = 15; // 2000 * 15 = 30000 milliseconds = 30 seconds (max sleep time)
76
77 _SocketImpl::_SocketImpl(Socket* pSocket)
78         : __socketFd(INVALID_HANDLE)
79         , __isConstructed(false)
80         , __isClosed(false)
81         , __isLoopback(false)
82         , __isUdp(false)
83         , __isAsync(false)
84         , __isNonblock(false)
85         , __isServer(false)
86         , __isAcceptFired(false)
87         , __isReadFired(false)
88         , __isErrorReadFired(false)
89         , __isConnectFired(false)
90         , __isWriteFired(false)
91         , __isCloseFired(false)
92         , __socketEventType(NET_SOCKET_EVENT_NONE)
93         , __isTimeout(false)
94         , __protocolFamily(NET_SOCKET_AF_NONE)
95         , __socketType(NET_SOCKET_TYPE_NONE)
96         , __protocol(NET_SOCKET_PROTOCOL_NONE)
97         , __pNetConnectionManager(null)
98         , __pManagedNetConnection(null)
99         , __pManagedNetConnectionEventListener(null)
100         , __pCustomNetConnection(null)
101         , __pCustomNetConnectionEventListener(null)
102         , __pSocket(pSocket)
103         , __pSocketEvent(null)
104         , __pLocal(null)
105         , __pPeer(null)
106         , __pLingerOption(null)
107         , __pMulticastOption(null)
108         , __pGMainContext(null)
109         , __pGlibSocketInfo(null)
110 {
111 }
112
113 _SocketImpl::~_SocketImpl(void)
114 {
115         Dispose();
116
117         delete __pGlibSocketInfo;
118         __pGlibSocketInfo = null;
119
120         __pGMainContext = null;
121
122         delete __pMulticastOption;
123         __pMulticastOption = null;
124
125         delete __pLingerOption;
126         __pLingerOption = null;
127
128         delete __pPeer;
129         __pPeer = null;
130
131         delete __pLocal;
132         __pLocal = null;
133
134         __socketEventListenerList.RemoveAll();
135
136         delete __pSocketEvent;
137         __pSocketEvent = null;
138
139         delete __pCustomNetConnection;
140         __pCustomNetConnection = null;
141
142         delete __pCustomNetConnectionEventListener;
143         __pCustomNetConnectionEventListener = null;
144
145         delete __pManagedNetConnection;
146         __pManagedNetConnection = null;
147
148         delete __pManagedNetConnectionEventListener;
149         __pManagedNetConnectionEventListener = null;
150
151         delete __pNetConnectionManager;
152         __pNetConnectionManager = null;
153
154         __protocol = NET_SOCKET_PROTOCOL_NONE;
155         __socketType = NET_SOCKET_TYPE_NONE;
156         __protocolFamily = NET_SOCKET_AF_NONE;
157         __socketEventType = NET_SOCKET_EVENT_NONE;
158         __isTimeout = false;
159         __isCloseFired = false;
160         __isWriteFired = false;
161         __isConnectFired = false;
162         __isErrorReadFired = false;
163         __isReadFired = false;
164         __isAcceptFired = false;
165         __isServer = false;
166         __isNonblock = false;
167         __isAsync = false;
168         __isUdp = false;
169         __isLoopback = false;
170         __isClosed = false;
171         __isConstructed = false;
172         __socketFd = INVALID_HANDLE;
173 }
174
175 result
176 _SocketImpl::Construct(const NetConnection& netConnection, NetSocketAddressFamily addressFamily, NetSocketType socketType,
177         NetSocketProtocol protocol)
178 {
179         SysTryReturnResult(NID_NET_SOCK, addressFamily == NET_SOCKET_AF_IPV4, E_UNSUPPORTED_FAMILY, "The AddressFamily is unsupported.");
180         SysTryReturnResult(NID_NET_SOCK, socketType == NET_SOCKET_TYPE_STREAM || socketType == NET_SOCKET_TYPE_DATAGRAM,
181                 E_UNSUPPORTED_TYPE, "The SocketType is unsupported.");
182         SysTryReturnResult(NID_NET_SOCK, protocol == NET_SOCKET_PROTOCOL_TCP || protocol == NET_SOCKET_PROTOCOL_UDP ||
183                 protocol ==     NET_SOCKET_PROTOCOL_SSL, E_UNSUPPORTED_PROTOCOL, "The Protocol is unsupported.");
184
185         SysLog(NID_NET_SOCK, "Socket uses CustomNetConnection.");
186
187         // Add netConection null check validation
188         NetConnection* pNetConnection = const_cast <NetConnection*>(&netConnection);
189         SysTryReturnResult(NID_NET_SOCK, pNetConnection != null, E_INVALID_ARG, "NetConnection is invalid.");
190
191         result r = E_SUCCESS;
192         int af = 0;
193         int type = 0;
194         int sockFd = INVALID_HANDLE;
195         int err = 0;
196
197         _NetConnectionImpl* pCustomNCImpl = null;
198         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
199
200         String deviceName;
201         char* pDeviceName = null;
202         const NetConnectionInfo* pNetConnectionInfo = null;
203         const _NetConnectionInfoImpl* pNCInfoImpl = null;
204
205         unique_ptr<_SocketEvent> pSocketEvent;
206         unique_ptr<_SocketCustomNetConnectionEventListener> pCustomNetConnectionEventListener;
207         unique_ptr<NetConnection> pCustomNetConnection;
208
209         // Set proper inparam
210         if (addressFamily == NET_SOCKET_AF_IPV4)
211         {
212                 af = AF_INET;
213                 __protocolFamily = addressFamily;
214         }
215
216         if ((socketType == NET_SOCKET_TYPE_STREAM && protocol != NET_SOCKET_PROTOCOL_TCP) ||
217                 (socketType == NET_SOCKET_TYPE_DATAGRAM && protocol != NET_SOCKET_PROTOCOL_UDP))
218         {
219                 r = E_INVALID_ARG;
220                 SysLogException(NID_NET_SOCK, r, "[%s] Type mismatch between SocketType [%d] and protocol [%d].", GetErrorMessage(r), socketType, protocol);
221                 return r;
222         }
223         else if (socketType == NET_SOCKET_TYPE_STREAM)
224         {
225                 type = SOCK_STREAM;
226                 __socketType = socketType;
227                 __protocol = NET_SOCKET_PROTOCOL_TCP;
228         }
229         else if (socketType == NET_SOCKET_TYPE_DATAGRAM)
230         {
231                 type = SOCK_DGRAM;
232                 __socketType = socketType;
233                 __protocol = NET_SOCKET_PROTOCOL_UDP;
234                 __isUdp = true;
235         }
236
237         // Custom Network Check
238         connState = pNetConnection->GetConnectionState();
239
240         if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
241         {
242                 SysLog(NID_NET_SOCK, "Custom Network is available.");
243         }
244         else
245         {
246                 r = E_INVALID_CONNECTION;
247                 SysLogException(NID_NET_SOCK, r, "[%s] Custom Network is not available.", GetErrorMessage(r));
248                 return r;
249         }
250
251         __socketFd = socket(af, type, 0);
252
253         if (__socketFd < 0)
254         {
255                 r = ConvertErrorToResult(errno);
256                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to construct the socket.", GetErrorMessage(r));
257                 goto CATCH;
258         }
259
260         if (fcntl(__socketFd, F_SETFL, O_NONBLOCK) < 0)
261         {
262                 __isNonblock = false;
263                 r = E_SYSTEM;
264                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to construct(fcntl) the socket.", GetErrorMessage(r));
265                 goto CATCH;
266         }
267         else
268         {
269                 __isNonblock = true;
270
271                 __socketEventListenerList.Construct();
272
273                 pSocketEvent.reset(new (std::nothrow) _SocketEvent());
274                 SysTryCatch(NID_NET_SOCK, pSocketEvent != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
275
276                 r = pSocketEvent->Construct(this);
277                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[%s] Failed to construct the SocketEvent.", GetErrorMessage(r));
278         }
279
280         // Set the device name (setsockopt)
281         pNetConnectionInfo = pNetConnection->GetNetConnectionInfo();
282         SysTryCatch(NID_NET_SOCK, pNetConnectionInfo != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get the ConnectionInfo Object.");
283
284         pNCInfoImpl = _NetConnectionInfoImpl::GetInstance(*pNetConnectionInfo);
285         SysTryCatch(NID_NET_SOCK, pNCInfoImpl != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get the ConnectionInfoImpl Object.");
286
287         deviceName = pNCInfoImpl->GetDeviceName();
288
289         if (deviceName.IsEmpty())
290         {
291                 SysLog(NID_NET_SOCK, "Device Name is empty string. - Emulator Case");
292         }
293         else
294         {
295                 SysLog(NID_NET_SOCK, "Device Name is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
296
297                 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
298                 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
299
300                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
301                 delete[] pDeviceName;
302                 if (err < 0)
303                 {
304                         r = ConvertErrorToResult(errno);
305                         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_CONNECTION, E_INVALID_CONNECTION,
306                                 "[E_INVALID_CONNECTION] Failed to bind(setsockopt) Device Name.");
307                 }
308         }
309
310         // Copy New CustomNetConnection
311         pCustomNCImpl = _NetConnectionImpl::GetInstance(*pNetConnection);
312
313         pCustomNetConnection.reset(pCustomNCImpl->CopyInstanceN());
314         SysTryCatch(NID_NET_SOCK, pCustomNetConnection != null, r = E_INVALID_CONNECTION, E_INVALID_CONNECTION,
315                 "[E_INVALID_CONNECTION] CustomNetConnection is null. Failed to copy the InstanceN.");
316
317         // New CustomNetConnectionEventListener
318         pCustomNetConnectionEventListener.reset(new (std::nothrow) _SocketCustomNetConnectionEventListener());
319         SysTryCatch(NID_NET_SOCK, pCustomNetConnectionEventListener != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
320                 "[E_OUT_OF_MEMORY] Memory allocation failed.");
321
322         // AddNetConnectionListener
323         r = pCustomNetConnection->AddNetConnectionListener(*pCustomNetConnectionEventListener);
324         r = TransExceptionsExclusive(r, E_INVALID_CONNECTION, E_OUT_OF_MEMORY);
325         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Failed to add the NetConnectionListener.", GetErrorMessage(r));
326
327         // Set the __socketFd
328         pCustomNetConnectionEventListener->SetConstructParams(pSocketEvent.get(), __socketFd, this);
329
330         __pCustomNetConnection = pCustomNetConnection.release();
331         __pCustomNetConnectionEventListener = pCustomNetConnectionEventListener.release();
332         __pSocketEvent = pSocketEvent.release();
333
334         __isConstructed = true;
335
336         SysLog(NID_NET_SOCK, "Socket is constructed by non-blocking mode.(Default) [Fd : %d]", __socketFd);
337
338         return r;
339
340 CATCH:
341         if (__socketFd > INVALID_HANDLE)
342         {
343                 sockFd = __socketFd;
344                 close(__socketFd);
345                 SysLog(NID_NET_SOCK, "### SocketFd is closed. [Fd : %d]", sockFd);
346         }
347         return r;
348 }
349
350 result
351 _SocketImpl::Construct(NetSocketAddressFamily addressFamily, NetSocketType socketType, NetSocketProtocol protocol)
352 {
353         SysTryReturnResult(NID_NET_SOCK, addressFamily == NET_SOCKET_AF_IPV4, E_UNSUPPORTED_FAMILY,     "The AddressFamily is unsupported.");
354         SysTryReturnResult(NID_NET_SOCK, socketType == NET_SOCKET_TYPE_STREAM || socketType == NET_SOCKET_TYPE_DATAGRAM,
355                                 E_UNSUPPORTED_TYPE, "The SocketType is unsupported.");
356         SysTryReturnResult(NID_NET_SOCK, protocol == NET_SOCKET_PROTOCOL_TCP || protocol == NET_SOCKET_PROTOCOL_UDP || protocol ==
357                                 NET_SOCKET_PROTOCOL_SSL, E_UNSUPPORTED_PROTOCOL, "The Protocol is unsupported.");
358
359         SysLog(NID_NET_SOCK, "Socket uses DefaultNetConnection.");
360
361         result r = E_SUCCESS;
362         int af = 0;
363         int type = 0;
364         int sockFd = INVALID_HANDLE;
365
366         _ManagedNetConnectionImpl* pManagedNCImpl = null;
367
368         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
369         _SocketMethodFlag flag = FLAG_NONE;
370
371         unique_ptr<_SocketEvent> pSocketEvent;
372         unique_ptr<_SocketManagedNetConnectionEventListener> pManagedNetConnectionEventListener;
373         unique_ptr<ManagedNetConnection> pManagedNetConnection;
374         unique_ptr<NetConnectionManager> pNetConnectionManager;
375
376         // Set proper inparam
377         if (addressFamily == NET_SOCKET_AF_IPV4)
378         {
379                 af = AF_INET;
380                 __protocolFamily = addressFamily;
381         }
382
383         if ((socketType == NET_SOCKET_TYPE_STREAM && protocol != NET_SOCKET_PROTOCOL_TCP) ||
384                 (socketType == NET_SOCKET_TYPE_DATAGRAM && protocol != NET_SOCKET_PROTOCOL_UDP))
385         {
386                 r = E_INVALID_ARG;
387                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid SocketType - Mismatch.");
388                 return r;
389         }
390         else if (socketType == NET_SOCKET_TYPE_STREAM)
391         {
392                 type = SOCK_STREAM;
393                 __socketType = socketType;
394                 __protocol = NET_SOCKET_PROTOCOL_TCP;
395         }
396         else if (socketType == NET_SOCKET_TYPE_DATAGRAM)
397         {
398                 type = SOCK_DGRAM;
399                 __socketType = socketType;
400                 __protocol = NET_SOCKET_PROTOCOL_UDP;
401                 __isUdp = true;
402         }
403
404         __socketFd = socket(af, type, 0);
405
406         if (__socketFd < 0)
407         {
408                 r = ConvertErrorToResult(errno);
409                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to construct the socket.", GetErrorMessage(r));
410                 goto CATCH;
411         }
412
413         if (fcntl(__socketFd, F_SETFL, O_NONBLOCK) < 0)
414         {
415                 __isNonblock = false;
416                 r = E_SYSTEM;
417                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to construct(fcntl) the socket.");
418                 goto CATCH;
419         }
420         else
421         {
422                 __isNonblock = true;
423
424                 __socketEventListenerList.Construct();
425
426                 // New SocketEvent
427                 pSocketEvent.reset(new (std::nothrow) _SocketEvent());
428                 SysTryCatch(NID_NET_SOCK, pSocketEvent != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
429
430                 r = pSocketEvent->Construct(this);
431                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[%s] Failed to construct the Socket Event.", GetErrorMessage(r));
432         }
433
434         if (_NetConnectionManagerImpl::IsDefaultMode() != true)
435         {
436                 SysLog(NID_NET_SOCK, "Socket uses ManagedNetConnection.");
437
438                 pNetConnectionManager.reset(new (std::nothrow) NetConnectionManager());
439                 SysTryCatch(NID_NET_SOCK, pNetConnectionManager != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
440
441                 r = pNetConnectionManager->Construct();
442                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_CONNECTION, r, "[%s] Failed to construct the ManagedNetConnection.", GetErrorMessage(r));
443
444                 pManagedNetConnection.reset(pNetConnectionManager->GetManagedNetConnectionN());
445                 SysTryCatch(NID_NET_SOCK, pManagedNetConnection != null, r = E_INVALID_CONNECTION, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] ManagedNetConnection is null. Failed to the GetManagedNetConnectionN.");
446
447                 pManagedNCImpl = _ManagedNetConnectionImpl::GetInstance(*pManagedNetConnection);
448
449                 // New ManagedNetConnectionEventListener
450                 pManagedNetConnectionEventListener.reset(new (std::nothrow) _SocketManagedNetConnectionEventListener());
451                 SysTryCatch(NID_NET_SOCK, pManagedNetConnectionEventListener != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
452
453                 // SetManagedNetConnectionEventListener
454                 r = pManagedNetConnection->SetManagedNetConnectionEventListener(pManagedNetConnectionEventListener.get());
455                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_CONNECTION, r, "[%s] Failed to the SetManagedNetConnectionEventListener.", GetErrorMessage(r));
456
457                 // Set the __socketFd
458                 flag = FLAG_CONSTRUCT;
459                 pManagedNetConnectionEventListener->SetConstructParams(pSocketEvent.get(), __socketFd, flag, this);
460
461                 // Start ManagedNetConnectionImpl
462                 r = pManagedNCImpl->Start();
463                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_CONNECTION, r, "[%s] Failed to start the ManagedNetConnection.", GetErrorMessage(r));
464
465                 connState = pManagedNCImpl->GetConnectionState();
466                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
467                 {
468                         pManagedNetConnectionEventListener->__isStarted = true;
469                 }
470         }
471
472         __pNetConnectionManager = pNetConnectionManager.release();
473         __pManagedNetConnection = pManagedNetConnection.release();
474         __pManagedNetConnectionEventListener = pManagedNetConnectionEventListener.release();
475         __pSocketEvent = pSocketEvent.release();
476
477         __isConstructed = true;
478
479         SysLog(NID_NET_SOCK, "Socket is constructed by Non-blocking mode.(Default) [Fd : %d]", __socketFd);
480
481         return r;
482
483 CATCH:
484         if (__socketFd > INVALID_HANDLE)
485         {
486                 sockFd = __socketFd;
487                 close(__socketFd);
488                 SysLog(NID_NET_SOCK, "### SocketFd is closed. [Fd : %d]", sockFd);
489         }
490         return r;
491 }
492
493 result
494 _SocketImpl::Close(void)
495 {
496         SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
497
498         result r = E_SUCCESS;
499
500         int sockFd = __socketFd;
501         IEnumeratorT<ISocketEventListener*>* pEnum = null;
502         ISocketEventListener* pSocketEventListener = null;
503
504         pEnum = __socketEventListenerList.GetEnumeratorN();
505
506         if (pEnum != null)
507         {
508                 while (pEnum->MoveNext() == E_SUCCESS)
509                 {
510                         r = pEnum->GetCurrent(pSocketEventListener);
511
512                         if (pSocketEventListener != null)
513                         {
514                                 r = __pSocketEvent->RemoveListener(*pSocketEventListener);
515                                 r = __socketEventListenerList.Remove(const_cast<ISocketEventListener*>(pSocketEventListener));
516                         }
517                 }
518                 delete pEnum;
519         }
520
521         if (__pGlibSocketInfo != null)
522         {
523                 delete __pGlibSocketInfo;
524                 __pGlibSocketInfo = null;
525         }
526
527         if (__socketFd > INVALID_HANDLE)
528         {
529                 if (close(__socketFd) < 0)
530                 {
531                         r = ConvertErrorToResult(errno);
532                         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to close the socket.");
533                 }
534
535                 SysLog(NID_NET_SOCK, "Socket is closed. [Fd : %d]", sockFd);
536         }
537
538         __socketFd = INVALID_HANDLE;
539         __isClosed = true;
540
541         return r;
542 }
543
544 result
545 _SocketImpl::Bind(const NetEndPoint& localEP)
546 {
547         SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
548
549         result r = E_SUCCESS;
550
551         NetAddressFamily af;
552         unsigned long ipAddr = 0;
553         unsigned short port = 0;
554
555         Ip4Address* pIp4Addr = null;
556         const _NetEndPointImpl* pLocalEPImpl = null;
557         struct sockaddr_in localAddr;
558
559         pLocalEPImpl = _NetEndPointImpl::GetInstance(localEP);
560
561         af = pLocalEPImpl->GetNetAddressFamily();
562         SysTryReturnResult(NID_NET_SOCK, af == NET_AF_IPV4, E_INVALID_ARG, "Address family is invalid.");
563
564         pIp4Addr = static_cast <Ip4Address*>(pLocalEPImpl->GetAddress());
565         r = pIp4Addr->GetAddress(ipAddr);
566         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, E_INVALID_ARG, "Address is invalid.");
567
568         port = pLocalEPImpl->GetPort();
569
570         memset(&localAddr, 0, sizeof(localAddr));
571         localAddr.sin_family = AF_INET;
572         localAddr.sin_addr.s_addr = htonl(ipAddr);
573         localAddr.sin_port = htons(port);
574
575         if (bind(__socketFd, (struct sockaddr*) &localAddr, sizeof(localAddr)) < 0)
576         {
577                 r = ConvertErrorToResult(errno);
578                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to bind the socket.");
579         }
580
581         SysLog(NID_NET_SOCK, "Socket is binded. [Fd : %d]", __socketFd);
582
583         if (__isAsync == true && __isUdp == true)
584         {
585                 __isConnectFired = true;
586                 __isWriteFired = true;
587                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
588                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
589                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the SocketEvent to attach all condition except G_IO_OUT.", __socketFd);
590         }
591
592         return r;
593 }
594
595 result
596 _SocketImpl::Connect(const NetEndPoint& remoteEP)
597 {
598         SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
599
600         result r = E_SUCCESS;
601         int err = 0;
602
603         NetAddressFamily af;
604         unsigned long ipAddr = 0;
605         unsigned short port = 0;
606
607         Ip4Address* pIp4Addr = null;
608         const _NetEndPointImpl* pRemoteEPImpl = null;
609         struct sockaddr_in remoteAddr;
610         String remoteAddrString;
611
612         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
613         _SocketMethodFlag flag = FLAG_NONE;
614
615         String deviceName;
616         char* pDeviceName = null;
617         const _ManagedNetConnectionImpl* pMNCConnImpl = null;
618         long milliseconds = _THREAD_SLEEP_TIMER;  // 2000 milliseconds (sleep time)
619 //      long timeout = OSP_DEFAULT_TIMEOUT; // 30 seconds (blocking time)
620 //      guint timerId = -1;
621         int tryCount = 0;
622
623         pRemoteEPImpl = _NetEndPointImpl::GetInstance(remoteEP);
624
625         if (pRemoteEPImpl->IsValid() == true)
626         {
627                 pIp4Addr = static_cast <Ip4Address*>(pRemoteEPImpl->GetAddress());
628                 remoteAddrString = pIp4Addr->ToString();
629         }
630         else
631         {
632                 r = E_INVALID_ARG;
633                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] NetEndPoint is invalid.");
634                 return r;
635         }
636
637         _ApiVersion apiVersion = _AppInfo::GetApiVersion();
638
639         if (apiVersion == _API_VERSION_2_0 && _AppInfo::IsOspCompat())
640         {
641                 if (__isLoopback == false)
642                 {
643                         if (remoteAddrString == LOOPBACK_ADDRESS)
644                         {
645                                 r = E_SYSTEM;
646                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
647                                 return r;
648                         }
649                 }
650                 else
651                 {
652                         if (remoteAddrString != LOOPBACK_ADDRESS)
653                         {
654                                 r = E_SYSTEM;
655                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
656                                 return r;
657                         }
658                 }
659         }
660
661         af = pRemoteEPImpl->GetNetAddressFamily();
662         SysTryReturnResult(NID_NET_SOCK, af == NET_AF_IPV4, E_INVALID_ARG, "Address family is invalid.");
663
664         r = pIp4Addr->GetAddress(ipAddr);
665     SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, E_INVALID_ARG, "Address is invalid.");
666
667         port = pRemoteEPImpl->GetPort();
668
669         memset(&remoteAddr, 0, sizeof(remoteAddr));
670         remoteAddr.sin_family = AF_INET;
671         remoteAddr.sin_addr.s_addr = htonl(ipAddr);
672         remoteAddr.sin_port = htons(port);
673
674         if (__pManagedNetConnection != null)
675         {
676                 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
677
678                 if (__isNonblock == false)
679                 {
680                         SysLog(NID_NET_SOCK, "This socket is blocking mode.");
681
682                         pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
683
684 //          timerId = g_timeout_add_seconds(timeout, (GSourceFunc)_SocketImpl::OnTimerCallback, this);
685
686                         // Blocking mode
687                         while (1)
688                         {
689                                 connState = pMNCConnImpl->QueryConnectionState(deviceName);
690
691                                 switch (connState)
692                                 {
693                                 case NET_CONNECTION_STATE_STARTED:
694
695                                 case NET_CONNECTION_STATE_RESUMED:
696
697                                 case NET_CONNECTION_STATE_SUSPENDED:
698                                         SysLog(NID_NET_SOCK, "Network is available.");
699
700                                         if (deviceName.IsEmpty())
701                                         {
702                                                 SysLog(NID_NET_SOCK, "Device Name is empty string. - Emulator Case");
703                                         }
704                                         else
705                                         {
706                                                 SysLog(NID_NET_SOCK, "Device Name is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
707
708                                                 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
709                                                 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
710
711                                                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
712                                                 delete[] pDeviceName;
713                                                 if (err < 0)
714                                                 {
715                                                         ConvertErrorToResult(errno);
716
717                                                         SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Failed to bind the device name.");
718                                                 }
719                                         }
720
721                                         err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
722                                         break;
723
724                                 case NET_CONNECTION_STATE_STARTING:
725
726                                 case NET_CONNECTION_STATE_NONE:
727
728                                 case NET_CONNECTION_STATE_STOPPING:
729
730                                 case NET_CONNECTION_STATE_STOPPED:
731                                         SysLog(NID_NET_SOCK, "Network is not available.");
732                                         break;
733
734                                 default:
735                                         SysLog(NID_NET_SOCK, "Should not come here.");
736                                         break;
737                                 }
738
739                                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
740                                 {
741 //                  g_source_remove(timerId);
742                                         break;
743                                 }
744
745                                 if (connState == NET_CONNECTION_STATE_STOPPED)
746                                 {
747                                         r = E_INVALID_CONNECTION;
748                                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
749 //                  g_source_remove(timerId);
750                                         break;
751                                 }
752
753 //              if (__isTimeout)
754 //              {
755 //                  r = E_TIMEOUT;
756 //                  SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network timeout happened. Try Again");
757 //                  g_source_remove(timerId);
758 //                  __isTimeout = false;
759 //                  break;
760 //              }
761
762                                 tryCount++;
763
764                                 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
765                                 {
766                                         r = E_TIMEOUT;
767                                         SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network is timeout.");
768                                         tryCount = 0;
769                                         break;
770                                 }
771
772                                 Thread::Sleep(milliseconds);
773                         }
774                 }
775                 else
776                 {
777                         SysLog(NID_NET_SOCK, "This socket is non-blocking mode.");
778
779                         if (__pManagedNetConnectionEventListener->__isStarted)
780                         {
781                                 err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
782                         }
783                         else
784                         {
785                                 r = E_WOULD_BLOCK;
786                                 flag = FLAG_CONNECT;
787                                 __pManagedNetConnectionEventListener->SetConnectParams(__socketFd, remoteAddr, flag);
788                         }
789                 }
790         }
791         else
792         {
793                 err = connect(__socketFd, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
794         }
795
796         if (err < 0)
797         {
798                 r = ConvertErrorToResult(errno);
799
800                 if (r != E_WOULD_BLOCK)
801                 {
802                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to connect the socket.", GetErrorMessage(r));
803                         if (__isAsync == true)
804                         {
805                                 __isConnectFired = true;
806                         }
807                         goto CATCH;
808                 }
809                 else
810                 {
811                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to connect the socket.", GetErrorMessage(r));
812                         if (__isAsync == true)
813                         {
814                                 __isConnectFired = false;
815                                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
816                                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
817                                 SysTryReturnResult(NID_NET_SOCK, r != E_SUCCESS, E_WOULD_BLOCK, "SocketFd : [%d], Set the socketEvent to attach all condition.", __socketFd);
818                         }
819                         goto CATCH;
820                 }
821         }
822
823         SysLog(NID_NET_SOCK, "Connect the socket. [Fd : %d]", __socketFd);
824
825         return r;
826
827 CATCH:
828         return r;
829 }
830
831 result
832 _SocketImpl::Send(ByteBuffer& buffer)
833 {
834     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
835
836         result r = E_SUCCESS;
837     result res = E_SUCCESS;
838
839         int sentLength = 0;
840         unsigned int offset = buffer.GetPosition();
841         unsigned int length = buffer.GetRemaining();
842
843         SysTryReturnResult(NID_NET_SOCK, length > 0, E_INVALID_ARG, "Address is invalid.");
844
845         sentLength = send(__socketFd, (char*) (buffer.GetPointer() + offset), length, 0);
846
847         if (sentLength < 0)
848         {
849                 r = ConvertErrorToResult(errno);
850
851                 if (r != E_WOULD_BLOCK)
852                 {
853                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to send the socket.", GetErrorMessage(r));
854                         if (__isAsync == true)
855                         {
856                                 __isWriteFired = true;
857                         }
858                         goto CATCH;
859                 }
860                 else
861                 {
862                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to send the socket.", GetErrorMessage(r));
863                         if (__isAsync == true)
864                         {
865                                 __isWriteFired = false;
866                                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
867                                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
868                                 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);
869                         }
870                         goto CATCH;
871                 }
872         }
873
874         SysLog(NID_NET_SOCK, "Actually send byte : %d byte.", sentLength);
875
876         if (__isAsync == true)
877         {
878                 __isWriteFired = false;
879                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
880                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
881                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
882         }
883
884         r = buffer.SetPosition(offset + sentLength);
885         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM , E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
886
887         return r;
888
889 CATCH:
890         res = buffer.SetPosition(offset);
891         SysTryReturnResult(NID_NET_SOCK, res == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
892
893         return r;
894 }
895
896 result
897 _SocketImpl::Send(void* pBuffer, int length, int& sentLength)
898 {
899     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
900
901         result r = E_SUCCESS;
902
903         if (!pBuffer || length <= 0)
904         {
905                 r = E_INVALID_ARG;
906                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] The buffer is null or the length is invalid.");
907                 return r;
908         }
909
910         sentLength = send(__socketFd, static_cast <char*>(pBuffer), length, 0);
911
912         if (sentLength < 0)
913         {
914                 r = ConvertErrorToResult(errno);
915
916                 if (r != E_WOULD_BLOCK)
917                 {
918                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to send the socket.", GetErrorMessage(r));
919                         if (__isAsync == true)
920                         {
921                                 __isWriteFired = true;
922                         }
923                         goto CATCH;
924                 }
925                 else
926                 {
927                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to send the socket.", GetErrorMessage(r));
928                         if (__isAsync == true)
929                         {
930                                 __isWriteFired = false;
931                                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
932                                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
933                                 SysTryReturnResult(NID_NET_SOCK, r != E_SUCCESS, E_WOULD_BLOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
934                         }
935                         goto CATCH;
936                 }
937         }
938
939         SysLog(NID_NET_SOCK, "Actually send byte : %d byte.", sentLength);
940
941         if (__isAsync == true)
942         {
943                 __isWriteFired = false;
944                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
945                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
946                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
947         }
948
949         return r;
950
951 CATCH:
952         return r;
953 }
954
955 result
956 _SocketImpl::SendTo(ByteBuffer& buffer, const NetEndPoint& remoteEP)
957 {
958     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
959
960         result r = E_SUCCESS;
961     result res = E_SUCCESS;
962
963         int sentLength = 0;
964
965         NetAddressFamily af;
966         unsigned long ipAddr = 0;
967         unsigned short port = 0;
968
969         Ip4Address* pIp4Addr = null;
970         const _NetEndPointImpl* pRemoteEPImpl = null;
971         struct sockaddr_in remoteAddr;
972         String remoteAddrString;
973
974         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
975         _SocketMethodFlag flag = FLAG_NONE;
976
977         int err = 0;
978         String deviceName;
979         char* pDeviceName = null;
980         const _ManagedNetConnectionImpl* pMNCConnImpl = null;
981         long milliseconds = _THREAD_SLEEP_TIMER;  // 2000 milliseconds (sleep time)
982         int tryCount = 0;
983
984         pRemoteEPImpl = _NetEndPointImpl::GetInstance(remoteEP);
985
986         if (pRemoteEPImpl->IsValid() == true)
987         {
988                 pIp4Addr = static_cast <Ip4Address*>(pRemoteEPImpl->GetAddress());
989                 remoteAddrString = pIp4Addr->ToString();
990         }
991         else
992         {
993                 r = E_INVALID_ARG;
994                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] NetEndPoint is invalid.");
995                 return r;
996         }
997
998         _ApiVersion apiVersion = _AppInfo::GetApiVersion();
999
1000         if (apiVersion == _API_VERSION_2_0 && _AppInfo::IsOspCompat())
1001         {
1002                 if (__isLoopback == false)
1003                 {
1004                         if (remoteAddrString == LOOPBACK_ADDRESS)
1005                         {
1006                                 r = E_SYSTEM;
1007                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
1008                                 return r;
1009                         }
1010                 }
1011                 else
1012                 {
1013                         if (remoteAddrString != LOOPBACK_ADDRESS)
1014                         {
1015                                 r = E_SYSTEM;
1016                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
1017                                 return r;
1018                         }
1019                 }
1020         }
1021
1022         af = pRemoteEPImpl->GetNetAddressFamily();
1023         SysTryReturnResult(NID_NET_SOCK, af == NET_AF_IPV4, E_INVALID_ARG, "Address family is invalid.");
1024
1025         r = pIp4Addr->GetAddress(ipAddr);
1026         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, E_INVALID_ARG, "[E_INVALID_ARG] Address is invalid.");
1027
1028         port = pRemoteEPImpl->GetPort();
1029
1030         memset(&remoteAddr, 0, sizeof(remoteAddr));
1031         remoteAddr.sin_family = AF_INET;
1032         remoteAddr.sin_addr.s_addr = htonl(ipAddr);
1033         remoteAddr.sin_port = htons(port);
1034
1035         unsigned int offset = buffer.GetPosition();
1036         unsigned int length = buffer.GetRemaining();
1037
1038         if (length <= 0)
1039         {
1040                 r = E_INVALID_ARG;
1041                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Address is invalid.");
1042                 return r;
1043         }
1044
1045         if (__pManagedNetConnection != null)
1046         {
1047                 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
1048
1049                 if (__isNonblock == false)
1050                 {
1051                         SysLog(NID_NET_SOCK, "This socket is blocking mode.");
1052
1053                         pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
1054
1055                         // Blocking mode
1056                         while (1)
1057                         {
1058                                 connState = pMNCConnImpl->QueryConnectionState(deviceName);
1059
1060                                 switch (connState)
1061                                 {
1062                                 case NET_CONNECTION_STATE_STARTED:
1063
1064                                 case NET_CONNECTION_STATE_RESUMED:
1065
1066                                 case NET_CONNECTION_STATE_SUSPENDED:
1067                                         SysLog(NID_NET_SOCK, "Network is available.");
1068
1069                                         if (deviceName.IsEmpty())
1070                                         {
1071                                                 SysLog(NID_NET_SOCK, "Device Name is empty string. - Emulator Case");
1072                                         }
1073                                         else
1074                                         {
1075                                                 SysLog(NID_NET_SOCK, "Device Name is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
1076
1077                                                 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
1078                                                 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1079
1080                                                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
1081                                                 delete[] pDeviceName;
1082
1083                                                 if (err < 0)
1084                                                 {
1085                                                         ConvertErrorToResult(errno);
1086                                                         SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Failed to bind the device name.");
1087                                                 }
1088                                         }
1089
1090                                         sentLength = sendto(__socketFd, (char*) (buffer.GetPointer() + offset), length, 0, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
1091                                         break;
1092
1093                                 case NET_CONNECTION_STATE_STARTING:
1094
1095                                 case NET_CONNECTION_STATE_NONE:
1096
1097                                 case NET_CONNECTION_STATE_STOPPING:
1098
1099                                 case NET_CONNECTION_STATE_STOPPED:
1100                                         SysLog(NID_NET_SOCK, "Network is not available.");
1101                                         break;
1102
1103                                 default:
1104                                         SysLog(NID_NET_SOCK, "Should not come here.");
1105                                         break;
1106                                 }
1107
1108                                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
1109                                 {
1110                                         break;
1111                                 }
1112
1113                                 if (connState == NET_CONNECTION_STATE_STOPPED)
1114                                 {
1115                                         r = E_INVALID_CONNECTION;
1116                                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
1117                                         break;
1118                                 }
1119
1120                                 tryCount++;
1121
1122                                 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
1123                                 {
1124                                         r = E_TIMEOUT;
1125                                         SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network is timeout.");
1126                                         tryCount = 0;
1127                                         break;
1128                                 }
1129
1130                                 Thread::Sleep(milliseconds);
1131                         }
1132                 }
1133                 else
1134                 {
1135                         SysLog(NID_NET_SOCK, "This socket is non-blocking mode.");
1136
1137                         if (__pManagedNetConnectionEventListener->__isStarted)
1138                         {
1139                                 sentLength = sendto(__socketFd, (char*) (buffer.GetPointer() + offset), length, 0, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
1140                         }
1141                         else
1142                         {
1143                                 r = E_WOULD_BLOCK;
1144                                 flag = FLAG_SENDTO;
1145                                 __pManagedNetConnectionEventListener->SetSendToParams(__socketFd, flag);
1146                         }
1147                 }
1148         }
1149         else
1150         {
1151                 sentLength = sendto(__socketFd, (char*) (buffer.GetPointer() + offset), length, 0, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
1152         }
1153
1154         if (sentLength < 0)
1155         {
1156                 r = ConvertErrorToResult(errno);
1157
1158                 if (r != E_WOULD_BLOCK)
1159                 {
1160                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to sendto() the socket.", GetErrorMessage(r));
1161                         if (__isAsync == true)
1162                         {
1163                                 __isConnectFired = false;
1164                                 __isWriteFired = true;
1165                         }
1166                         goto CATCH;
1167                 }
1168                 else
1169                 {
1170                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to sendto() the socket.", GetErrorMessage(r));
1171                         if (__isAsync == true)
1172                         {
1173                                 __isConnectFired = true;
1174                                 __isWriteFired = false;
1175                                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1176                                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
1177                                 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);
1178                         }
1179                         goto CATCH;
1180                 }
1181         }
1182
1183         SysLog(NID_NET_SOCK, "Actually send byte : %d byte.", sentLength);
1184
1185         if (__isAsync == true)
1186         {
1187                 __isConnectFired = true;
1188                 __isWriteFired = false;
1189                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1190                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
1191                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
1192         }
1193
1194         r = buffer.SetPosition(offset + sentLength);
1195         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
1196
1197         return r;
1198
1199 CATCH:
1200         res = buffer.SetPosition(offset);
1201         SysTryReturnResult(NID_NET_SOCK, res == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
1202
1203         return r;
1204 }
1205
1206 result
1207 _SocketImpl::SendTo(void* pBuffer, int length, const NetEndPoint& remoteEP, int& sentLength)
1208 {
1209     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1210
1211         result r = E_SUCCESS;
1212
1213         NetAddressFamily af;
1214         unsigned long ipAddr = 0;
1215         unsigned short port = 0;
1216         Ip4Address* pIp4Addr = null;
1217         const _NetEndPointImpl* pRemoteEPImpl = null;
1218         struct sockaddr_in remoteAddr;
1219         String remoteAddrString;
1220
1221         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
1222         _SocketMethodFlag flag = FLAG_NONE;
1223
1224         int err = 0;
1225         String deviceName;
1226         char* pDeviceName = null;
1227         const _ManagedNetConnectionImpl* pMNCConnImpl = null;
1228         long milliseconds = _THREAD_SLEEP_TIMER; // 2000 milliseconds (sleep time)
1229         int tryCount = 0;
1230
1231         pRemoteEPImpl = _NetEndPointImpl::GetInstance(remoteEP);
1232
1233         if (!pBuffer || length <= 0)
1234         {
1235                 r = E_INVALID_ARG;
1236                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] The buffer is null or the length is invalid.");
1237                 return r;
1238         }
1239
1240         if (pRemoteEPImpl->IsValid() == true)
1241         {
1242                 pIp4Addr = static_cast <Ip4Address*>(pRemoteEPImpl->GetAddress());
1243                 remoteAddrString = pIp4Addr->ToString();
1244         }
1245         else
1246         {
1247                 r = E_INVALID_ARG;
1248                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] NetEndPoint is invalid.");
1249                 return r;
1250         }
1251
1252         _ApiVersion apiVersion = _AppInfo::GetApiVersion();
1253
1254         if (apiVersion == _API_VERSION_2_0 && _AppInfo::IsOspCompat())
1255         {
1256                 if (__isLoopback == false)
1257                 {
1258                         if (remoteAddrString == LOOPBACK_ADDRESS)
1259                         {
1260                                 r = E_SYSTEM;
1261                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
1262                                 return r;
1263                         }
1264                 }
1265                 else
1266                 {
1267                         if (remoteAddrString != LOOPBACK_ADDRESS)
1268                         {
1269                                 r = E_SYSTEM;
1270                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
1271                                 return r;
1272                         }
1273                 }
1274         }
1275
1276         af = pRemoteEPImpl->GetNetAddressFamily();
1277         SysTryReturnResult(NID_NET_SOCK, af == NET_AF_IPV4, E_INVALID_ARG, "Address family is invalid.");
1278
1279         r = pIp4Addr->GetAddress(ipAddr);
1280         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, E_INVALID_ARG, "[E_INVALID_ARG] Address is invalid.");
1281
1282         port = pRemoteEPImpl->GetPort();
1283
1284         memset(&remoteAddr, 0, sizeof(remoteAddr));
1285         remoteAddr.sin_family = AF_INET;
1286         remoteAddr.sin_addr.s_addr = htonl(ipAddr);
1287         remoteAddr.sin_port = htons(port);
1288
1289         if (__pManagedNetConnection != null)
1290         {
1291                 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
1292
1293                 if (__isNonblock == false)
1294                 {
1295                         SysLog(NID_NET_SOCK, "This socket is blocking mode.");
1296
1297                         pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
1298
1299                         // Blocking mode
1300                         while (1)
1301                         {
1302                                 connState = pMNCConnImpl->QueryConnectionState(deviceName);
1303
1304                                 switch (connState)
1305                                 {
1306                                 case NET_CONNECTION_STATE_STARTED:
1307
1308                                 case NET_CONNECTION_STATE_RESUMED:
1309
1310                                 case NET_CONNECTION_STATE_SUSPENDED:
1311                                         SysLog(NID_NET_SOCK, "Network is available.");
1312
1313                                         if (deviceName.IsEmpty())
1314                                         {
1315                                                 SysLog(NID_NET_SOCK, "Device Name is empty string. - Emulator Case");
1316                                         }
1317                                         else
1318                                         {
1319                                                 SysLog(NID_NET_SOCK, "Device Name is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
1320
1321                                                 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
1322                                                 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1323
1324                                                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
1325                                                 delete[] pDeviceName;
1326
1327                                                 if (err < 0)
1328                                                 {
1329                                                         ConvertErrorToResult(errno);
1330                                                         SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Failed to bind the device name.");
1331                                                 }
1332                                         }
1333
1334                                         sentLength = sendto(__socketFd, static_cast <char*>(pBuffer), length, 0, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
1335                                         break;
1336
1337                                 case NET_CONNECTION_STATE_STARTING:
1338
1339                                 case NET_CONNECTION_STATE_NONE:
1340
1341                                 case NET_CONNECTION_STATE_STOPPING:
1342
1343                                 case NET_CONNECTION_STATE_STOPPED:
1344                                         SysLog(NID_NET_SOCK, "Network is not available.");
1345                                         break;
1346
1347                                 default:
1348                                         SysLog(NID_NET_SOCK, "Should not come here.");
1349                                         break;
1350                                 }
1351
1352                                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
1353                                 {
1354                                         break;
1355                                 }
1356
1357                                 if (connState == NET_CONNECTION_STATE_STOPPED)
1358                                 {
1359                                         r = E_INVALID_CONNECTION;
1360                                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
1361                                         break;
1362                                 }
1363
1364                                 tryCount++;
1365
1366                                 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
1367                                 {
1368                                         r = E_TIMEOUT;
1369                                         SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network is timeout.");
1370                                         tryCount = 0;
1371                                         break;
1372                                 }
1373
1374                                 Thread::Sleep(milliseconds);
1375                         }
1376                 }
1377                 else
1378                 {
1379                         SysLog(NID_NET_SOCK, "This socket is non-blocking mode.");
1380
1381                         if (__pManagedNetConnectionEventListener->__isStarted)
1382                         {
1383                                 sentLength = sendto(__socketFd, static_cast <char*>(pBuffer), length, 0, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
1384                         }
1385                         else
1386                         {
1387                                 r = E_WOULD_BLOCK;
1388                                 flag = FLAG_SENDTO;
1389                                 __pManagedNetConnectionEventListener->SetSendToParams(__socketFd, flag);
1390                         }
1391                 }
1392         }
1393         else
1394         {
1395                 sentLength = sendto(__socketFd, static_cast <char*>(pBuffer), length, 0, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
1396         }
1397
1398         if (sentLength < 0)
1399         {
1400                 r = ConvertErrorToResult(errno);
1401
1402                 if (r != E_WOULD_BLOCK)
1403                 {
1404                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to sendto() the socket.", GetErrorMessage(r));
1405                         if (__isAsync == true)
1406                         {
1407                                 __isConnectFired = false;
1408                                 __isWriteFired = true;
1409                         }
1410                         goto CATCH;
1411                 }
1412                 else
1413                 {
1414                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to sendto() the socket.", GetErrorMessage(r));
1415                         if (__isAsync == true)
1416                         {
1417                                 __isConnectFired = true;
1418                                 __isWriteFired = false;
1419                                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1420                                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
1421                                 SysTryReturnResult(NID_NET_SOCK, r != E_SUCCESS, E_WOULD_BLOCK, "SocketFd : [%d], Set the socketEvent to attach all condition.", __socketFd);
1422                         }
1423                         goto CATCH;
1424                 }
1425         }
1426
1427         SysLog(NID_NET_SOCK, "Actually sendto() byte : %d byte.", sentLength);
1428
1429         if (__isAsync == true)
1430         {
1431                 __isConnectFired = true;
1432                 __isWriteFired = false;
1433                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1434                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
1435                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
1436         }
1437
1438         return r;
1439
1440 CATCH:
1441         return r;
1442 }
1443
1444 result
1445 _SocketImpl::Receive(ByteBuffer& buffer)
1446 {
1447     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1448
1449         result r = E_SUCCESS;
1450         result res = E_SUCCESS;
1451
1452         int rcvdLength = 0;
1453         unsigned int offset = buffer.GetPosition();
1454         unsigned int length = buffer.GetRemaining();
1455
1456         SysTryReturnResult(NID_NET_SOCK, length > 0, E_INVALID_ARG, "Address is invalid.");
1457
1458         rcvdLength = recv(__socketFd, (char*) (buffer.GetPointer() + offset), length, 0);
1459
1460         if (rcvdLength < 0)
1461         {
1462                 r = ConvertErrorToResult(errno);
1463
1464                 if (r != E_WOULD_BLOCK)
1465                 {
1466                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to receive the socket.", GetErrorMessage(r));
1467                         if (__isAsync == true)
1468                         {
1469                                 __isReadFired = true;
1470                         }
1471                         goto CATCH;
1472                 }
1473                 else
1474                 {
1475                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to receive the socket.", GetErrorMessage(r));
1476                         if (__isAsync == true)
1477                         {
1478                                 __isReadFired = false;
1479                         }
1480                         goto CATCH;
1481                 }
1482         }
1483
1484         SysLog(NID_NET_SOCK, "Actually receive byte : %d byte", rcvdLength);
1485
1486         if (__isAsync == true)
1487         {
1488                 __isReadFired = false;
1489         }
1490
1491         r = buffer.SetPosition(offset + rcvdLength);
1492         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
1493
1494         return r;
1495
1496 CATCH:
1497     res = buffer.SetPosition(offset);
1498     SysTryReturnResult(NID_NET_SOCK, res == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
1499
1500     return r;
1501 }
1502
1503 result
1504 _SocketImpl::Receive(void* pBuffer, int length, int& rcvdLength)
1505 {
1506     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1507
1508         result r = E_SUCCESS;
1509
1510         if (!pBuffer || length <= 0)
1511         {
1512                 r = E_INVALID_ARG;
1513                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] The buffer is null or the length is invalid.");
1514                 return r;
1515         }
1516
1517         rcvdLength = recv(__socketFd, static_cast <char*>(pBuffer), length, 0);
1518
1519         if (rcvdLength < 0)
1520         {
1521                 r = ConvertErrorToResult(errno);
1522
1523                 if (r != E_WOULD_BLOCK)
1524                 {
1525                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to receive the socket.", GetErrorMessage(r));
1526                         if (__isAsync == true)
1527                         {
1528                                 __isReadFired = true;
1529                         }
1530                         goto CATCH;
1531                 }
1532                 else
1533                 {
1534                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to receive the socket.", GetErrorMessage(r));
1535                         if (__isAsync == true)
1536                         {
1537                                 __isReadFired = false;
1538                         }
1539                         goto CATCH;
1540                 }
1541         }
1542
1543         SysLog(NID_NET_SOCK, "Actually receive byte : %d byte.", rcvdLength);
1544
1545         if (__isAsync == true)
1546         {
1547                 __isReadFired = false;
1548         }
1549
1550         return r;
1551
1552 CATCH:
1553         return r;
1554 }
1555
1556 result
1557 _SocketImpl::ReceiveFrom(ByteBuffer& buffer, NetEndPoint& remoteEP)
1558 {
1559     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1560
1561         result r = E_SUCCESS;
1562         result res = E_SUCCESS;
1563
1564         int rcvdLength = 0;
1565         unsigned int fromSize = 0;
1566         unsigned long ipAddr = 0;
1567         unsigned short port = 0;
1568         Ip4Address* pIp4Addr = null;
1569         _NetEndPointImpl* pRemoteEPImpl = null;
1570         struct sockaddr_in remoteAddr;
1571         String remoteAddrString;
1572
1573         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
1574         _SocketMethodFlag flag = FLAG_NONE;
1575
1576         int err = 0;
1577         String deviceName;
1578         char* pDeviceName = null;
1579         const _ManagedNetConnectionImpl* pMNCConnImpl = null;
1580         long milliseconds = _THREAD_SLEEP_TIMER; // 2000 milliseconds (sleep time)
1581         int tryCount = 0;
1582
1583         pRemoteEPImpl = _NetEndPointImpl::GetInstance(remoteEP);
1584
1585         memset(&remoteAddr, 0, sizeof(remoteAddr));
1586         remoteAddr.sin_family = AF_INET;
1587         remoteAddr.sin_addr.s_addr = htonl(ipAddr);
1588         remoteAddr.sin_port = htons(port);
1589
1590         if (pRemoteEPImpl->IsValid() == true)
1591         {
1592                 pIp4Addr = static_cast <Ip4Address*>(pRemoteEPImpl->GetAddress());
1593                 remoteAddrString = pIp4Addr->ToString();
1594         }
1595         else
1596         {
1597                 r = E_INVALID_ARG;
1598                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] NetEndPoint is invalid.");
1599                 return r;
1600         }
1601
1602         _ApiVersion apiVersion = _AppInfo::GetApiVersion();
1603
1604         if (apiVersion == _API_VERSION_2_0 && _AppInfo::IsOspCompat())
1605         {
1606                 if (__isLoopback == false)
1607                 {
1608                         if (remoteAddrString == LOOPBACK_ADDRESS)
1609                         {
1610                                 r = E_SYSTEM;
1611                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
1612                                 return r;
1613                         }
1614                 }
1615                 else
1616                 {
1617                         if (remoteAddrString != LOOPBACK_ADDRESS)
1618                         {
1619                                 r = E_SYSTEM;
1620                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
1621                                 return r;
1622                         }
1623                 }
1624         }
1625
1626         fromSize = sizeof(remoteAddr);
1627
1628         unsigned int offset = buffer.GetPosition();
1629         unsigned int length = buffer.GetRemaining();
1630
1631         if (length <= 0)
1632         {
1633                 r = E_INVALID_ARG;
1634                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Address is invalid.");
1635                 return r;
1636         }
1637
1638         if (__pManagedNetConnection != null)
1639         {
1640                 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
1641
1642                 if (__isNonblock == false)
1643                 {
1644                         SysLog(NID_NET_SOCK, "This socket is blocking mode.");
1645
1646                         pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
1647
1648                         // Blocking mode
1649                         while (1)
1650                         {
1651                                 connState = pMNCConnImpl->QueryConnectionState(deviceName);
1652
1653                                 switch (connState)
1654                                 {
1655                                 case NET_CONNECTION_STATE_STARTED:
1656
1657                                 case NET_CONNECTION_STATE_RESUMED:
1658
1659                                 case NET_CONNECTION_STATE_SUSPENDED:
1660                                         SysLog(NID_NET_SOCK, "Network is available.");
1661
1662                                         if (deviceName.IsEmpty())
1663                                         {
1664                                                 SysLog(NID_NET_SOCK, "Device Name is empty string. - Emulator Case");
1665                                         }
1666                                         else
1667                                         {
1668                                                 SysLog(NID_NET_SOCK, "Device Name is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
1669
1670                                                 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
1671                                                 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY));
1672
1673                                                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
1674                                                 delete[] pDeviceName;
1675
1676                                                 if (err < 0)
1677                                                 {
1678                                                         ConvertErrorToResult(errno);
1679                                                         SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[%s] Failed to bind the device name.", GetErrorMessage(E_INVALID_CONNECTION));
1680                                                 }
1681                                         }
1682
1683                                         rcvdLength = recvfrom(__socketFd, (char*) (buffer.GetPointer() + offset), length, 0, (struct sockaddr*) &remoteAddr, &fromSize);
1684                                         break;
1685
1686                                 case NET_CONNECTION_STATE_STARTING:
1687
1688                                 case NET_CONNECTION_STATE_NONE:
1689
1690                                 case NET_CONNECTION_STATE_STOPPING:
1691
1692                                 case NET_CONNECTION_STATE_STOPPED:
1693                                         SysLog(NID_NET_SOCK, "Network is not available.");
1694                                         break;
1695
1696                                 default:
1697                                         SysLog(NID_NET_SOCK, "Should not come here.");
1698                                         break;
1699                                 }
1700
1701                                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
1702                                 {
1703                                         break;
1704                                 }
1705
1706                                 if (connState == NET_CONNECTION_STATE_STOPPED)
1707                                 {
1708                                         r = E_INVALID_CONNECTION;
1709                                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
1710                                         break;
1711                                 }
1712
1713                                 tryCount++;
1714
1715                                 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
1716                                 {
1717                                         r = E_TIMEOUT;
1718                                         SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network is timeout.");
1719                                         tryCount = 0;
1720                                         break;
1721                                 }
1722
1723                                 Thread::Sleep(milliseconds);
1724                         }
1725                 }
1726                 else
1727                 {
1728                         SysLog(NID_NET_SOCK, "This socket is non-blocking mode.");
1729
1730                         if (__pManagedNetConnectionEventListener->__isStarted)
1731                         {
1732                                 rcvdLength = recvfrom(__socketFd, (char*) (buffer.GetPointer() + offset), length, 0, (struct sockaddr*) &remoteAddr, &fromSize);
1733                         }
1734                         else
1735                         {
1736                                 r = E_WOULD_BLOCK;
1737                                 flag = FLAG_RECEIVEFROM;
1738                                 __pManagedNetConnectionEventListener->SetReceiveFromParams(__socketFd, flag);
1739                         }
1740                 }
1741         }
1742         else
1743         {
1744                 rcvdLength = recvfrom(__socketFd, (char*) (buffer.GetPointer() + offset), length, 0, (struct sockaddr*) &remoteAddr, &fromSize);
1745         }
1746
1747         if (rcvdLength < 0)
1748         {
1749                 r = ConvertErrorToResult(errno);
1750
1751                 if (r != E_WOULD_BLOCK)
1752                 {
1753                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to recvfrom() the socket.", GetErrorMessage(r));
1754                         if (__isAsync == true)
1755                         {
1756                                 __isConnectFired = false;
1757                                 __isReadFired = true;
1758                         }
1759                         goto CATCH;
1760                 }
1761                 else
1762                 {
1763                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to recvfrom() the socket.", GetErrorMessage(r));
1764
1765                         if (__isAsync == true)
1766                         {
1767                                 __isConnectFired = true;
1768                                 __isReadFired = false;
1769                                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1770                                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
1771                                 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);
1772                         }
1773                         goto CATCH;
1774                 }
1775         }
1776
1777         SysLog(NID_NET_SOCK, "Actually recvfrom() byte : %d byte", rcvdLength);
1778
1779         if (__isAsync == true)
1780         {
1781                 __isConnectFired = true;
1782                 __isReadFired = false;
1783                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
1784                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
1785                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
1786         }
1787
1788         r = buffer.SetPosition(offset + rcvdLength);
1789         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
1790
1791         // Implementation : change from remoteAddr to NetEndPoint
1792         ipAddr = ntohl(remoteAddr.sin_addr.s_addr);
1793         port = ntohs(remoteAddr.sin_port);
1794
1795         pIp4Addr = new (std::nothrow) Ip4Address(ipAddr);
1796         SysTryReturnResult(NID_NET_SOCK, pIp4Addr, E_OUT_OF_MEMORY, "Memory allocation failed.");
1797         r = pRemoteEPImpl->Update(*pIp4Addr, port);
1798         delete pIp4Addr;
1799
1800     r = TransExceptionsExclusive(r, E_SYSTEM, E_OUT_OF_MEMORY);
1801         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS || r == E_SYSTEM, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1802         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to Set the NetEndPoint.");
1803
1804         return r;
1805
1806 CATCH:
1807         res = buffer.SetPosition(offset);
1808         SysTryReturnResult(NID_NET_SOCK, res == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] Failed to Set the position.");
1809
1810         return r;
1811 }
1812
1813 result
1814 _SocketImpl::ReceiveFrom(void* pBuffer, int length, NetEndPoint& remoteEP, int& rcvdLength)
1815 {
1816     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
1817
1818         result r = E_SUCCESS;
1819         unsigned int fromSize = 0;
1820         unsigned long ipAddr = 0;
1821         unsigned short port = 0;
1822         Ip4Address* pIp4Addr = null;
1823         _NetEndPointImpl* pRemoteEPImpl = null;
1824         struct sockaddr_in remoteAddr;
1825         String remoteAddrString;
1826
1827         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
1828         _SocketMethodFlag flag = FLAG_NONE;
1829
1830         int err = 0;
1831         String deviceName;
1832         char* pDeviceName = null;
1833         const _ManagedNetConnectionImpl* pMNCConnImpl = null;
1834         long milliseconds = _THREAD_SLEEP_TIMER; // 2000 milliseconds (sleep time)
1835         int tryCount = 0;
1836
1837         pRemoteEPImpl = _NetEndPointImpl::GetInstance(remoteEP);
1838
1839         memset(&remoteAddr, 0, sizeof(remoteAddr));
1840         remoteAddr.sin_family = AF_INET;
1841         remoteAddr.sin_addr.s_addr = htonl(ipAddr);
1842         remoteAddr.sin_port = htons(port);
1843
1844         if (!pBuffer || length <= 0)
1845         {
1846                 r = E_INVALID_ARG;
1847                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] The buffer is null or the length is invalid.");
1848                 return r;
1849         }
1850
1851         if (pRemoteEPImpl->IsValid() == true)
1852         {
1853                 pIp4Addr = static_cast <Ip4Address*>(pRemoteEPImpl->GetAddress());
1854                 remoteAddrString = pIp4Addr->ToString();
1855         }
1856         else
1857         {
1858                 r = E_INVALID_ARG;
1859                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] NetEndPoint is invalid.");
1860                 return r;
1861         }
1862
1863         _ApiVersion apiVersion = _AppInfo::GetApiVersion();
1864
1865         if (apiVersion == _API_VERSION_2_0 && _AppInfo::IsOspCompat())
1866         {
1867                 if (__isLoopback == false)
1868                 {
1869                         if (remoteAddrString == LOOPBACK_ADDRESS)
1870                         {
1871                                 r = E_SYSTEM;
1872                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
1873                                 return r;
1874                         }
1875                 }
1876                 else
1877                 {
1878                         if (remoteAddrString != LOOPBACK_ADDRESS)
1879                         {
1880                                 r = E_SYSTEM;
1881                                 SysLogException(NID_NET_SOCK, r, "[E_SYSTEM] Failed to assign the requested address.");
1882                                 return r;
1883                         }
1884                 }
1885         }
1886
1887         fromSize = sizeof(remoteAddr);
1888
1889         if (__pManagedNetConnection != null)
1890         {
1891                 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
1892
1893                 if (__isNonblock == false)
1894                 {
1895                         SysLog(NID_NET_SOCK, "This socket is blocking mode.");
1896
1897                         pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
1898
1899                         // Blocking mode
1900                         while (1)
1901                         {
1902                                 connState = pMNCConnImpl->QueryConnectionState(deviceName);
1903
1904                                 switch (connState)
1905                                 {
1906                                 case NET_CONNECTION_STATE_STARTED:
1907
1908                                 case NET_CONNECTION_STATE_RESUMED:
1909
1910                                 case NET_CONNECTION_STATE_SUSPENDED:
1911                                         SysLog(NID_NET_SOCK, "Network is available.");
1912
1913                                         if (deviceName.IsEmpty())
1914                                         {
1915                                                 SysLog(NID_NET_SOCK, "Device Name is empty string. - Emulator Case");
1916                                         }
1917                                         else
1918                                         {
1919                                                 SysLog(NID_NET_SOCK, "Device Name is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
1920
1921                                                 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
1922                                                 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
1923
1924                                                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
1925                                                 delete[] pDeviceName;
1926
1927                                                 if (err < 0)
1928                                                 {
1929                                                         ConvertErrorToResult(errno);
1930                                                         SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Failed to bind the device name.");
1931                                                 }
1932                                         }
1933
1934                                         rcvdLength = recvfrom(__socketFd, static_cast <char*>(pBuffer), length, 0, (struct sockaddr*) &remoteAddr, &fromSize);
1935                                         break;
1936
1937                                 case NET_CONNECTION_STATE_STARTING:
1938
1939                                 case NET_CONNECTION_STATE_NONE:
1940
1941                                 case NET_CONNECTION_STATE_STOPPING:
1942
1943                                 case NET_CONNECTION_STATE_STOPPED:
1944                                         SysLog(NID_NET_SOCK, "Network is not available.");
1945                                         break;
1946
1947                                 default:
1948                                         SysLog(NID_NET_SOCK, "Should not come here.");
1949                                         break;
1950                                 }
1951
1952                                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
1953                                 {
1954                                         break;
1955                                 }
1956
1957                                 if (connState == NET_CONNECTION_STATE_STOPPED)
1958                                 {
1959                                         r = E_INVALID_CONNECTION;
1960                                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
1961                                         break;
1962                                 }
1963
1964                                 tryCount++;
1965
1966                                 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
1967                                 {
1968                                         r = E_TIMEOUT;
1969                                         SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network is timeout.");
1970                                         tryCount = 0;
1971                                         break;
1972                                 }
1973
1974                                 Thread::Sleep(milliseconds);
1975                         }
1976                 }
1977                 else
1978                 {
1979                         SysLog(NID_NET_SOCK, "This socket is non-blocking mode.");
1980
1981                         if (__pManagedNetConnectionEventListener->__isStarted)
1982                         {
1983                                 rcvdLength = recvfrom(__socketFd, static_cast <char*>(pBuffer), length, 0, (struct sockaddr*) &remoteAddr, &fromSize);
1984                         }
1985                         else
1986                         {
1987                                 r = E_WOULD_BLOCK;
1988                                 flag = FLAG_RECEIVEFROM;
1989                                 __pManagedNetConnectionEventListener->SetReceiveFromParams(__socketFd, flag);
1990                         }
1991                 }
1992         }
1993         else
1994         {
1995                 rcvdLength = recvfrom(__socketFd, static_cast <char*>(pBuffer), length, 0, (struct sockaddr*) &remoteAddr, &fromSize);
1996         }
1997
1998         if (rcvdLength < 0)
1999         {
2000                 r = ConvertErrorToResult(errno);
2001
2002                 if (r != E_WOULD_BLOCK)
2003                 {
2004                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to recvfrom() the socket.", GetErrorMessage(r));
2005                         if (__isAsync == true)
2006                         {
2007                                 __isConnectFired = false;
2008                                 __isReadFired = true;
2009                         }
2010                         goto CATCH;
2011                 }
2012                 else
2013                 {
2014                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to recvfrom() the socket.", GetErrorMessage(r));
2015
2016                         if (__isAsync == true)
2017                         {
2018                                 __isConnectFired = true;
2019                                 __isReadFired = false;
2020                                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
2021                                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
2022                                 SysTryReturnResult(NID_NET_SOCK, r != E_SUCCESS, E_WOULD_BLOCK, "SocketFd : [%d], Set the socketEvent to attach all condition.", __socketFd);
2023                         }
2024                         goto CATCH;
2025                 }
2026         }
2027
2028         SysLog(NID_NET_SOCK, "Actually recvfrom() byte : %d byte", rcvdLength);
2029
2030         if (__isAsync == true)
2031         {
2032                 __isConnectFired = true;
2033                 __isReadFired = false;
2034                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
2035                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
2036                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
2037         }
2038
2039         // Implementation : change from remoteAddr to NetEndPoint.
2040         ipAddr = ntohl(remoteAddr.sin_addr.s_addr);
2041         port = ntohs(remoteAddr.sin_port);
2042
2043         pIp4Addr = new (std::nothrow) Ip4Address(ipAddr);
2044         SysTryReturnResult(NID_NET_SOCK, pIp4Addr, E_OUT_OF_MEMORY, "Memory allocation failed.");
2045         r = pRemoteEPImpl->Update(*pIp4Addr, port);
2046         delete pIp4Addr;
2047
2048     r = TransExceptionsExclusive(r, E_SYSTEM, E_OUT_OF_MEMORY);
2049         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS || r == E_SYSTEM, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2050     SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] Failed to Set the NetEndPoint.");
2051
2052         return r;
2053
2054 CATCH:
2055         return r;
2056 }
2057
2058 result
2059 _SocketImpl::Listen(int backLog)
2060 {
2061     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2062
2063         result r = E_SUCCESS;
2064         int err = 0;
2065
2066         _SocketMethodFlag flag = FLAG_NONE;
2067         NetConnectionState connState = NET_CONNECTION_STATE_NONE;
2068
2069         String deviceName;
2070         char* pDeviceName = null;
2071         const _ManagedNetConnectionImpl* pMNCConnImpl = null;
2072         long milliseconds = _THREAD_SLEEP_TIMER; // 2000 milliseconds (sleep time)
2073         int tryCount = 0;
2074
2075         if (__pManagedNetConnection != null)
2076         {
2077                 SysLog(NID_NET_SOCK, "This socket uses ManagedNetConnection internally. [Fd : %d]", __socketFd);
2078
2079                 if (__isNonblock == false)
2080                 {
2081                         SysLog(NID_NET_SOCK, "This socket is blocking mode.");
2082
2083                         pMNCConnImpl = _ManagedNetConnectionImpl::GetInstance(*__pManagedNetConnection);
2084
2085                         // Blocking mode
2086                         while (1)
2087                         {
2088                                 connState = pMNCConnImpl->QueryConnectionState(deviceName);
2089
2090                                 switch (connState)
2091                                 {
2092                                 case NET_CONNECTION_STATE_STARTED:
2093
2094                                 case NET_CONNECTION_STATE_RESUMED:
2095
2096                                 case NET_CONNECTION_STATE_SUSPENDED:
2097                                         SysLog(NID_NET_SOCK, "Network is available.");
2098
2099                                         if (deviceName.IsEmpty())
2100                                         {
2101                                                 SysLog(NID_NET_SOCK, "Device Name is empty string. - Emulator Case");
2102                                         }
2103                                         else
2104                                         {
2105                                                 SysLog(NID_NET_SOCK, "Device Name is not empty string. [Device Name : %ls] - Target Case", deviceName.GetPointer());
2106
2107                                                 pDeviceName = _StringConverter::CopyToCharArrayN(deviceName);
2108                                                 SysTryCatch(NID_NET_SOCK, pDeviceName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2109
2110                                                 err = setsockopt(__socketFd, SOL_SOCKET, SO_BINDTODEVICE, pDeviceName, strlen(pDeviceName) + 1);
2111                                                 delete[] pDeviceName;
2112                                                 if (err < 0)
2113                                                 {
2114                                                         ConvertErrorToResult(errno);
2115                                                         SysLogException(NID_NET_SOCK, E_INVALID_CONNECTION, "[E_INVALID_CONNECTION] Failed to bind the device name.");
2116                                                 }
2117                                         }
2118
2119                                         err = listen(__socketFd, backLog);
2120                                         break;
2121
2122                                 case NET_CONNECTION_STATE_STARTING:
2123
2124                                 case NET_CONNECTION_STATE_NONE:
2125
2126                                 case NET_CONNECTION_STATE_STOPPING:
2127
2128                                 case NET_CONNECTION_STATE_STOPPED:
2129                                         SysLog(NID_NET_SOCK, "Network is not available.");
2130                                         break;
2131
2132                                 default:
2133                                         SysLog(NID_NET_SOCK, "Should not come here.");
2134                                         break;
2135                                 }
2136
2137                                 if (connState == NET_CONNECTION_STATE_STARTED || connState == NET_CONNECTION_STATE_RESUMED || connState == NET_CONNECTION_STATE_SUSPENDED)
2138                                 {
2139                                         break;
2140                                 }
2141
2142                                 if (connState == NET_CONNECTION_STATE_STOPPED)
2143                                 {
2144                                         r = E_INVALID_CONNECTION;
2145                                         SysLogException(NID_NET_SOCK, r, "[E_INVALID_CONNECTION] Network is stopped.");
2146                                         break;
2147                                 }
2148
2149                                 tryCount++;
2150
2151                                 if (tryCount > _MAX_COUNT_THREAD_SLEEP_TIMER) // 2000 milliseconds * 15 count = 30 seconds timeout
2152                                 {
2153                                         r = E_TIMEOUT;
2154                                         SysLogException(NID_NET_SOCK, r, "[E_TIMEOUT] Network is timeout. Try Again.");
2155                                         tryCount = 0;
2156                                         break;
2157                                 }
2158
2159                                 Thread::Sleep(milliseconds);
2160                         }
2161                 }
2162                 else
2163                 {
2164                         SysLog(NID_NET_SOCK, "This socket is non-blocking mode.");
2165
2166                         if (__pManagedNetConnectionEventListener->__isStarted)
2167                         {
2168                                 err = listen(__socketFd, backLog);
2169                         }
2170                         else
2171                         {
2172                                 r = E_WOULD_BLOCK;
2173                                 flag = FLAG_LISTEN;
2174                                 __pManagedNetConnectionEventListener->SetListenParams(__socketFd, backLog, flag);
2175                         }
2176                 }
2177         }
2178         else
2179         {
2180                 err = listen(__socketFd, backLog);
2181         }
2182
2183         if (err < 0)
2184         {
2185                 r = ConvertErrorToResult(errno);
2186
2187                 if (r != E_WOULD_BLOCK)
2188                 {
2189                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to listen the socket.", GetErrorMessage(r));
2190                         if (__isAsync == true)
2191                         {
2192                                 __isAcceptFired = true;
2193                         }
2194                         goto CATCH;
2195                 }
2196                 else
2197                 {
2198                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to listen the socket.", GetErrorMessage(r));
2199                         __isServer = true;
2200                         if (__isAsync == true)
2201                         {
2202                                 __isAcceptFired = false;
2203                                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
2204                                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
2205                                 SysTryReturnResult(NID_NET_SOCK, r != E_SUCCESS, E_WOULD_BLOCK, "SocketFd : [%d], Set the socketEvent to attach all condition.", __socketFd);
2206                         }
2207                         goto CATCH;
2208                 }
2209         }
2210
2211         SysLog(NID_NET_SOCK, "Socket is listening. [Fd : %d, backLog : %d]", __socketFd, backLog);
2212
2213         __isServer = true;
2214
2215         if (__isAsync == true)
2216         {
2217                 __isAcceptFired = false;
2218                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
2219                 SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Memory allocation failed.");
2220                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach G_IO_OUT condition.", __socketFd);
2221         }
2222
2223         return r;
2224
2225 CATCH:
2226         return r;
2227 }
2228
2229 Socket*
2230 _SocketImpl::AcceptN(void)
2231 {
2232     ClearLastResult();
2233
2234         result r = E_SUCCESS;
2235         Socket* pClientSocket = null;
2236         _SocketImpl* pClientSocketImpl = null;
2237         int clientFd = INVALID_HANDLE;
2238         unsigned int clientSize = 0;
2239         struct sockaddr_in clientAddr;
2240
2241         SysTryCatch(NID_NET_SOCK, __isClosed == false, r = E_INVALID_STATE, E_INVALID_STATE, "[E_INVALID_STATE] Socket is already closed.");
2242
2243         clientSize = sizeof(clientAddr);
2244
2245         clientFd = accept(__socketFd, (struct sockaddr*) &clientAddr, &clientSize);
2246
2247         if (clientFd < 0)
2248         {
2249                 r = ConvertErrorToResult(errno);
2250
2251                 if (r != E_WOULD_BLOCK)
2252                 {
2253                         SysLogException(NID_NET_SOCK, r, "[%s] Failed to accept the socket.", GetErrorMessage(r));
2254                         goto CATCH;
2255                 }
2256                 else
2257                 {
2258                         SysLogException(NID_NET_SOCK, r, "[%s] Returned EWOULDBLOCK to accept the socket.", GetErrorMessage(r));
2259                         goto CATCH;
2260                 }
2261         }
2262
2263         if (__isAsync == true)
2264         {
2265                 __isAcceptFired = false;
2266                 r = __pGlibSocketInfo->SetSocketEvent(this, __socketFd);
2267                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
2268                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach All condition.", __socketFd);
2269         }
2270
2271         // Implementation - new Socket
2272         pClientSocket = new (std::nothrow) Socket();
2273         SysTryCatch(NID_NET_SOCK, pClientSocket != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2274
2275         pClientSocketImpl = new (std::nothrow) _SocketImpl(pClientSocket);
2276         SysTryCatch(NID_NET_SOCK, pClientSocketImpl, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2277
2278         // Set new SocketEvent
2279         pClientSocketImpl->__pSocketEvent = new (std::nothrow) _SocketEvent();
2280         SysTryCatch(NID_NET_SOCK, pClientSocketImpl->__pSocketEvent, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2281
2282         r = pClientSocketImpl->__pSocketEvent->Construct(pClientSocketImpl);
2283         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to construct the socket event.");
2284
2285         // New socket creation complete.
2286         pClientSocketImpl->__socketFd = clientFd;
2287         pClientSocketImpl->__isClosed = false;
2288         pClientSocketImpl->__isLoopback = this->__isLoopback;
2289         pClientSocketImpl->__isNonblock = this->__isNonblock;
2290         pClientSocketImpl->__socketEventType = this->__socketEventType;
2291         pClientSocketImpl->__isServer = false;
2292         pClientSocketImpl->__isConnectFired = true;
2293         pClientSocketImpl->__protocolFamily = this->__protocolFamily;
2294         pClientSocketImpl->__socketType = this->__socketType;
2295         pClientSocketImpl->__protocol = this->__protocol;
2296         pClientSocketImpl->__pLocal = this->__pLocal;
2297         pClientSocketImpl->__pPeer = this->__pPeer;
2298         pClientSocketImpl->__pLingerOption = this->__pLingerOption;
2299         pClientSocketImpl->__pMulticastOption = this->__pMulticastOption;
2300         pClientSocketImpl->__pGMainContext = this->__pGMainContext;
2301         pClientSocketImpl->__isConstructed = true;
2302
2303         pClientSocket->__pSocketImpl = pClientSocketImpl;
2304
2305         SysLog(NID_NET_SOCK, "New Socket(Child Socket) is created by Server Socket. [ServerFd : %d] [ChildFd : %d]", pClientSocket->__pSocketImpl->__socketFd, __socketFd);
2306
2307         if (__isAsync == true)
2308         {
2309                 pClientSocketImpl->__pGlibSocketInfo = new (std::nothrow) _GlibSocketInfo();
2310                 SysTryCatch(NID_NET_SOCK, __pGlibSocketInfo, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2311
2312                 r = pClientSocketImpl->__pGlibSocketInfo->SetSocketEvent(pClientSocketImpl, clientFd);
2313                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, , r, "[%s] Memory allocation failed.", GetErrorMessage(r));
2314                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to attach All condition to ClientFd.", clientFd);
2315         }
2316
2317         return pClientSocket;
2318
2319 CATCH:
2320         SetLastResult(r);
2321         return null;
2322 }
2323
2324 result
2325 _SocketImpl::Ioctl(NetSocketIoctlCmd cmd, unsigned long& pArg)
2326 {
2327     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2328     SysTryReturnResult(NID_NET_SOCK, (cmd == NET_SOCKET_FIONBIO || cmd == NET_SOCKET_FIONREAD || cmd == NET_SOCKET_SIOCATMARK),
2329                                 E_INVALID_ARG, "IoctlCmd is invalid.");
2330
2331         result r = E_SUCCESS;
2332         int err = 0;
2333         int flag = 0;
2334
2335         if (cmd == NET_SOCKET_FIONBIO && pArg != 0)
2336         {
2337                 // command = FIONBIO;
2338                 flag = fcntl(__socketFd, F_GETFL);
2339                 err = fcntl(__socketFd, F_SETFL, flag | O_NONBLOCK);
2340                 SysLog(NID_NET_SOCK, "Changed the Socket by Non-blocking mode. [Fd : %d]", __socketFd);
2341                 __isNonblock = true;
2342         }
2343         else if (cmd == NET_SOCKET_FIONBIO && pArg == 0)
2344         {
2345                 // command = FIONBIO;
2346                 flag = fcntl(__socketFd, F_GETFL);
2347                 err = fcntl(__socketFd, F_SETFL, flag & ~O_NONBLOCK);
2348                 SysLog(NID_NET_SOCK, "Changed the Socket by blocking mode. [Fd : %d]", __socketFd);
2349                 __isNonblock = false;
2350         }
2351         else if (cmd == NET_SOCKET_FIONREAD)
2352         {
2353                 // command = FIONREAD;
2354                 err = ioctl(__socketFd, FIONREAD, (unsigned long*) &pArg);
2355                 SysLog(NID_NET_SOCK, "Amount of data that can be read : %d bytes. [Fd : %d]", pArg, __socketFd);
2356         }
2357         else if (cmd == NET_SOCKET_SIOCATMARK)
2358         {
2359                 // command = SIOCATMARK;
2360                 err = ioctl(__socketFd, SIOCATMARK, (unsigned long*) &pArg);
2361                 SysLog(NID_NET_SOCK, "All out of band(OOB) data has been read. [Fd : %d]", __socketFd);
2362         }
2363
2364         if (err < 0)
2365         {
2366                 r = ConvertErrorToResult(errno);
2367                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to Ioctl the socket.", GetErrorMessage(r));
2368         }
2369
2370         return r;
2371 }
2372
2373 result
2374 _SocketImpl::AsyncSelectByListener(unsigned long socketEventType)
2375 {
2376     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2377
2378         result r = E_SUCCESS;
2379
2380         // New _GlibSocketInfo
2381         if (__pGlibSocketInfo == null)
2382         {
2383                 __pGlibSocketInfo = new (std::nothrow) _GlibSocketInfo();
2384                 SysTryReturnResult(NID_NET_SOCK, __pGlibSocketInfo, E_OUT_OF_MEMORY, "Memory allocation failed.");
2385         }
2386
2387         SysLog(NID_NET_SOCK, "Socket set the socketEvent by AsyncSelectByListener. [Fd : %d]", __socketFd);
2388
2389         __socketEventType = socketEventType;
2390         __isNonblock = true;
2391         __isAsync = true;
2392
2393         return r;
2394 }
2395
2396 result
2397 _SocketImpl::AddSocketListener(ISocketEventListener& listener)
2398 {
2399     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2400
2401         result r = E_SUCCESS;
2402
2403         // Get the current GMainContext
2404         _EventDispatcher* pEventDispatcher = _EventDispatcher::GetCurrentEventDispatcher();
2405         SysTryReturnResult(NID_NET_SOCK, pEventDispatcher, E_SYSTEM, "GetCurrentEventDispatcher is null.");
2406
2407         __pGMainContext = pEventDispatcher->GetGMainContext();
2408         SysTryReturnResult(NID_NET_SOCK, __pGMainContext, E_SYSTEM, "GetGMainContext is null.");
2409
2410         r = __pSocketEvent->AddListener(listener, true);
2411         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to add the listener.");
2412
2413         r = __socketEventListenerList.Add(const_cast<ISocketEventListener*>(&listener));
2414         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to add the listener to the list.");
2415
2416         return r;
2417 }
2418
2419 result
2420 _SocketImpl::RemoveSocketListener(ISocketEventListener& listener)
2421 {
2422     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2423
2424         result r = E_SUCCESS;
2425
2426         r = __pSocketEvent->RemoveListener(listener);
2427         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to remove the listener.");
2428
2429         r = __socketEventListenerList.Remove(const_cast<ISocketEventListener*>(&listener));
2430         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to remove the listener to the list.");
2431
2432         return r;
2433 }
2434
2435 const NetEndPoint*
2436 _SocketImpl::GetPeerEndPoint(void)
2437 {
2438     ClearLastResult();
2439
2440         result r = E_SUCCESS;
2441         Ip4Address* pIp4Addr = null;
2442         _NetEndPointImpl* pNetEndPointImpl = null;
2443         unsigned int addrSize = 0;
2444         struct sockaddr_in remoteAddr;
2445
2446         SysTryCatch(NID_NET_SOCK, __isClosed == false, r = E_INVALID_STATE, E_INVALID_STATE, "[E_INVALID_STATE] Socket is already closed.");
2447
2448         addrSize = sizeof(remoteAddr);
2449
2450         if ((getpeername(__socketFd, (struct sockaddr*) &remoteAddr, &addrSize)) < 0)
2451         {
2452                 r = ConvertErrorToResult(errno);
2453                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the PeerEndPoint.", GetErrorMessage(r));
2454                 goto CATCH;
2455         }
2456
2457         SysLog(NID_NET_SOCK, "Peer Address, Port : [%s], [%d]", inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port));
2458
2459         // New and set Ip4Address
2460         pIp4Addr = new (std::nothrow) Ip4Address(ntohl(remoteAddr.sin_addr.s_addr));
2461         SysTryReturn(NID_NET_SOCK, pIp4Addr, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2462
2463         if (__pPeer == null)
2464         {
2465                 __pPeer = new (std::nothrow) NetEndPoint(*pIp4Addr, ntohs(remoteAddr.sin_port));
2466                 SysTryReturn(NID_NET_SOCK, __pPeer, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2467         }
2468         else
2469         {
2470                 pNetEndPointImpl = _NetEndPointImpl::GetInstance(*__pPeer);
2471
2472                 r = pNetEndPointImpl->Update(*pIp4Addr, ntohs(remoteAddr.sin_port));
2473                 //r = TransExceptionsExclusive(r, E_SYSTEM, E_OUT_OF_MEMORY);
2474                 //SysTryCatch(NID_NET_SOCK, r == E_SUCCESS || r == E_SYSTEM, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2475                 //SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to Set the NetEndPoint.");
2476                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS || r == E_INVALID_ARG, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2477                 SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to Set the NetEndPoint.");
2478
2479         }
2480         delete pIp4Addr;
2481         return (NetEndPoint*) __pPeer;
2482
2483 CATCH:
2484     delete pIp4Addr;
2485         return null;
2486 }
2487
2488 const NetEndPoint*
2489 _SocketImpl::GetLocalEndPoint(void)
2490 {
2491         ClearLastResult();
2492
2493         result r = E_SUCCESS;
2494         Ip4Address* pIp4Addr = null;
2495         _NetEndPointImpl* pNetEndPointImpl = null;
2496         unsigned int addrSize = 0;
2497         struct sockaddr_in localAddr;
2498
2499         SysTryCatch(NID_NET_SOCK, __isClosed == false, r = E_INVALID_STATE, E_INVALID_STATE, "[%s] Socket is already closed.", GetErrorMessage(E_INVALID_STATE));
2500
2501         addrSize = sizeof(localAddr);
2502
2503         if ((getsockname(__socketFd, (struct sockaddr*) &localAddr, &addrSize)) < 0)
2504         {
2505                 r = ConvertErrorToResult(errno);
2506                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the LocalEndPoint.", GetErrorMessage(r));
2507                 goto CATCH;
2508         }
2509
2510         SysLog(NID_NET_SOCK, "Local Address, Port : [%s], [%d]", inet_ntoa(localAddr.sin_addr), ntohs(localAddr.sin_port));
2511
2512         // New and set Ip4Address
2513         pIp4Addr = new (std::nothrow) Ip4Address(ntohl(localAddr.sin_addr.s_addr));
2514         SysTryReturn(NID_NET_SOCK, pIp4Addr, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2515
2516         if (__pLocal == null)
2517         {
2518                 __pLocal = new (std::nothrow) NetEndPoint(*pIp4Addr, ntohs(localAddr.sin_port));
2519                 SysTryReturn(NID_NET_SOCK, __pLocal, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2520         }
2521         else
2522         {
2523                 pNetEndPointImpl = _NetEndPointImpl::GetInstance(*__pLocal);
2524
2525                 r = pNetEndPointImpl->Update(*pIp4Addr, ntohs(localAddr.sin_port));
2526         //r = TransExceptionsExclusive(r, E_SYSTEM, E_OUT_OF_MEMORY);
2527         //SysTryCatch(NID_NET_SOCK, r == E_SUCCESS || r == E_SYSTEM, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2528         //SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to Set the NetEndPoint.");
2529         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS || r == E_INVALID_ARG, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
2530         SysTryCatch(NID_NET_SOCK, r == E_SUCCESS, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to Set the NetEndPoint.");
2531         }
2532         delete pIp4Addr;
2533         return (NetEndPoint*) __pLocal;
2534
2535 CATCH:
2536     delete pIp4Addr;
2537         return null;
2538 }
2539
2540 result
2541 _SocketImpl::GetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, int& pOptVal) const
2542 {
2543     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2544
2545         result r = E_SUCCESS;
2546         int err = 0;
2547         int optLevel = 0;
2548         int optName = 0;
2549         unsigned int optLen = 0;
2550
2551         struct timeval timeout;
2552
2553         switch (optionLevel)
2554         {
2555         case NET_SOCKET_IPPROTO_TCP:
2556                 optLevel = IPPROTO_TCP;
2557                 break;
2558
2559         case NET_SOCKET_IPPROTO_IP:
2560                 optLevel = IPPROTO_IP;
2561                 break;
2562
2563         case NET_SOCKET_SOL_SOCKET:
2564                 optLevel = SOL_SOCKET;
2565                 break;
2566
2567         default:
2568                 r = E_INVALID_ARG;
2569                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used. Option level = %d", optionLevel);
2570                 return r;
2571         }
2572
2573         switch (optionName)
2574         {
2575         case NET_SOCKET_TCP_NODELAY:
2576                 optName = TCP_NODELAY;
2577                 break;
2578
2579         case NET_SOCKET_TCP_MAXSEG:
2580                 optName = TCP_MAXSEG;
2581                 break;
2582
2583         case NET_SOCKET_IP_TTL:
2584                 optName = IP_TTL;
2585                 break;
2586
2587         case NET_SOCKET_IP_TOS:
2588                 optName = IP_TOS;
2589                 break;
2590
2591         case NET_SOCKET_SO_ACCEPTCONN:
2592                 optName = SO_ACCEPTCONN;
2593                 break;
2594
2595         case NET_SOCKET_SO_BROADCAST:
2596                 optName = SO_BROADCAST;
2597                 break;
2598
2599 //      case NET_SOCKET_SO_DEBUG:
2600 //              optName = SO_DEBUG;
2601 //              break;
2602
2603         case NET_SOCKET_SO_DONTROUTE:
2604                 optName = SO_DONTROUTE;
2605                 break;
2606
2607         case NET_SOCKET_SO_ERROR:
2608                 optName = SO_ERROR;
2609                 break;
2610
2611         case NET_SOCKET_SO_KEEPALIVE:
2612                 optName = SO_KEEPALIVE;
2613                 break;
2614
2615         case NET_SOCKET_SO_OOBINLINE:
2616                 optName = SO_OOBINLINE;
2617                 break;
2618
2619         case NET_SOCKET_SO_RCVBUF:
2620                 optName = SO_RCVBUF;
2621                 break;
2622
2623         case NET_SOCKET_SO_RCVTIMEO:
2624                 optName = SO_RCVTIMEO;
2625                 break;
2626
2627         case NET_SOCKET_SO_REUSEADDR:
2628                 optName = SO_REUSEADDR;
2629                 break;
2630
2631         case NET_SOCKET_SO_SNDBUF:
2632                 optName = SO_SNDBUF;
2633                 break;
2634
2635         case NET_SOCKET_SO_SNDTIMEO:
2636                 optName = SO_SNDTIMEO;
2637                 break;
2638
2639         case NET_SOCKET_SO_TYPE:
2640                 optName = SO_TYPE;
2641                 break;
2642
2643         default:
2644                 r = E_UNSUPPORTED_OPTION;
2645                 SysLogException(NID_NET_SOCK, r, "[E_UNSUPPORTED_OPTION] %d is unsupported", optionName);
2646                 return r;
2647         }
2648
2649         if (optName == SO_RCVTIMEO || optName == SO_SNDTIMEO)
2650         {
2651                 optLen = sizeof(timeout);
2652                 err = getsockopt(__socketFd, optLevel, optName, &timeout, &optLen);
2653                 pOptVal = (timeout.tv_sec * 1000) + (timeout.tv_usec / 1000);
2654         }
2655         else
2656         {
2657                 optLen = sizeof(pOptVal);
2658                 err = getsockopt(__socketFd, optLevel, optName, (int*) &pOptVal, &optLen);
2659         }
2660
2661         if (err < 0)
2662         {
2663                 r = ConvertErrorToResult(errno);
2664                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the option value.", GetErrorMessage(r));
2665         }
2666
2667         return r;
2668 }
2669
2670 result
2671 _SocketImpl::GetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, LingerOption& optionValue) const
2672 {
2673     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2674     SysTryReturnResult(NID_NET_SOCK, optionLevel == NET_SOCKET_SOL_SOCKET, E_INVALID_ARG, "This is only for LingerOption.");
2675     SysTryReturnResult(NID_NET_SOCK, optionName == NET_SOCKET_SO_LINGER, E_INVALID_ARG, "This is only for LingerOption.");
2676
2677         result r = E_SUCCESS;
2678
2679         int optLevel = SOL_SOCKET;
2680         int optName = SO_LINGER;
2681         struct linger lingerOption;
2682         unsigned int optLen = sizeof(lingerOption);
2683
2684         _LingerOptionImpl* pLingerOptionImpl = null;
2685         pLingerOptionImpl = _LingerOptionImpl::GetInstance(optionValue);
2686
2687         if (getsockopt(__socketFd, optLevel, optName, (char*) &lingerOption, &optLen) < 0)
2688         {
2689                 r = ConvertErrorToResult(errno);
2690                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the linger option value.", GetErrorMessage(r));
2691         }
2692
2693         // Implementation
2694         if (lingerOption.l_onoff == 0)
2695         {
2696                 pLingerOptionImpl->__enabled = false;
2697         }
2698         else
2699         {
2700                 pLingerOptionImpl->__enabled = true;
2701         }
2702
2703         if (lingerOption.l_linger >= 0)
2704         {
2705                 pLingerOptionImpl->__lingerTime = lingerOption.l_linger;
2706         }
2707         else
2708         {
2709                 pLingerOptionImpl->__lingerTime = 0;
2710         }
2711
2712         return r;
2713 }
2714
2715 result
2716 _SocketImpl::SetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, int optionValue)
2717 {
2718     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2719
2720         result r = E_SUCCESS;
2721         int err = 0;
2722         int optLevel = NET_SOCKET_OPTLEVEL_NONE;
2723         int optName = NET_SOCKET_OPTNAME_NONE;
2724         unsigned int optLen = 0;
2725         struct timeval timeout;
2726
2727         switch (optionLevel)
2728         {
2729         case NET_SOCKET_IPPROTO_TCP:
2730                 optLevel = IPPROTO_TCP;
2731                 break;
2732
2733         case NET_SOCKET_IPPROTO_IP:
2734                 optLevel = IPPROTO_IP;
2735                 break;
2736
2737         case NET_SOCKET_SOL_SOCKET:
2738                 optLevel = SOL_SOCKET;
2739                 break;
2740
2741         default:
2742                 r = E_INVALID_ARG;
2743                 SysLogException(NID_NET_SOCK, r, "[E_INVALID_ARG] Invalid argument is used. Option level = %d", optionLevel);
2744                 return r;
2745         }
2746
2747         switch (optionName)
2748         {
2749         case NET_SOCKET_TCP_NODELAY:
2750                 optName = TCP_NODELAY;
2751                 break;
2752
2753         case NET_SOCKET_TCP_MAXSEG:
2754                 optName = TCP_MAXSEG;
2755                 break;
2756
2757         case NET_SOCKET_IP_TTL:
2758                 optName = IP_TTL;
2759                 break;
2760
2761         case NET_SOCKET_IP_TOS:
2762                 optName = IP_TOS;
2763                 break;
2764
2765         case NET_SOCKET_SO_BROADCAST:
2766                 optName = SO_BROADCAST;
2767                 break;
2768
2769 //      case NET_SOCKET_SO_DEBUG:
2770 //              optName = SO_DEBUG;
2771 //              break;
2772
2773         case NET_SOCKET_SO_DONTROUTE:
2774                 optName = SO_DONTROUTE;
2775                 break;
2776
2777         case NET_SOCKET_SO_KEEPALIVE:
2778                 optName = SO_KEEPALIVE;
2779                 break;
2780
2781         case NET_SOCKET_SO_OOBINLINE:
2782                 optName = SO_OOBINLINE;
2783                 break;
2784
2785         case NET_SOCKET_SO_RCVBUF:
2786                 optName = SO_RCVBUF;
2787                 break;
2788
2789         case NET_SOCKET_SO_RCVTIMEO:
2790                 optName = SO_RCVTIMEO;
2791                 // milliseconds
2792                 timeout.tv_sec = optionValue / 1000;
2793                 timeout.tv_usec = (optionValue % 1000) * 1000;
2794                 break;
2795
2796         case NET_SOCKET_SO_REUSEADDR:
2797                 optName = SO_REUSEADDR;
2798                 break;
2799
2800         case NET_SOCKET_SO_SNDBUF:
2801                 optName = SO_SNDBUF;
2802                 break;
2803
2804         case NET_SOCKET_SO_SNDTIMEO:
2805                 optName = SO_SNDTIMEO;
2806                 // milliseconds
2807                 timeout.tv_sec = optionValue / 1000;
2808                 timeout.tv_usec = (optionValue % 1000) * 1000;
2809                 break;
2810
2811         default:
2812                 r = E_UNSUPPORTED_OPTION;
2813                 SysLogException(NID_NET_SOCK, r, "[E_UNSUPPORTED_OPTION] %d is unsupported", optionName);
2814                 return r;
2815         }
2816
2817         if (optName == SO_RCVTIMEO || optName == SO_SNDTIMEO)
2818         {
2819                 optLen = sizeof(timeout);
2820                 err = setsockopt(__socketFd, optLevel, optName, (struct timeval*) &timeout, optLen);
2821         }
2822         else
2823         {
2824                 optLen = sizeof(optionValue);
2825                 err = setsockopt(__socketFd, optLevel, optName, (int*) &optionValue, optLen);
2826         }
2827
2828         if (err < 0)
2829         {
2830                 r = ConvertErrorToResult(errno);
2831                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to get the option value.", GetErrorMessage(r));
2832         }
2833
2834         return r;
2835 }
2836
2837 result
2838 _SocketImpl::SetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, const LingerOption& optionValue)
2839 {
2840     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2841     SysTryReturnResult(NID_NET_SOCK, optionLevel == NET_SOCKET_SOL_SOCKET, E_INVALID_ARG, "This is only for LingerOption.");
2842     SysTryReturnResult(NID_NET_SOCK, optionName == NET_SOCKET_SO_LINGER, E_INVALID_ARG, "This is only for LingerOption.");
2843
2844         result r = E_SUCCESS;
2845
2846         int optLevel = SOL_SOCKET;
2847         int optName = SO_LINGER;
2848         struct linger lingerOption;
2849         unsigned int optLen = sizeof(lingerOption);
2850
2851         const _LingerOptionImpl* pLingerOptionImpl = null;
2852         pLingerOptionImpl = _LingerOptionImpl::GetInstance(optionValue);
2853
2854         if (pLingerOptionImpl->__enabled == false)
2855         {
2856                 lingerOption.l_onoff = 0;
2857         }
2858         else
2859         {
2860                 lingerOption.l_onoff = 1;
2861         }
2862
2863         lingerOption.l_linger = pLingerOptionImpl->__lingerTime;
2864
2865         if (setsockopt(__socketFd, optLevel, optName, (char*) &lingerOption, optLen) < 0)
2866         {
2867                 r = ConvertErrorToResult(errno);
2868                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to set the LingerOption value.", GetErrorMessage(r));
2869         }
2870
2871         return r;
2872 }
2873
2874 result
2875 _SocketImpl::SetSockOpt(NetSocketOptLevel optionLevel, NetSocketOptName optionName, const IpMulticastRequestOption& optionValue)
2876 {
2877     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2878     SysTryReturnResult(NID_NET_SOCK, optionLevel == NET_SOCKET_IPPROTO_IP, E_INVALID_ARG, "This is only for MulticastOption.");
2879     SysTryReturnResult(NID_NET_SOCK, (optionName == NET_SOCKET_IP_ADD_MEMBERSHIP) || (optionName == NET_SOCKET_IP_DROP_MEMBERSHIP),
2880                                 E_INVALID_ARG, "This is only for MulticastOption.");
2881
2882         result r = E_SUCCESS;
2883         int optLevel = SOL_SOCKET;
2884         int optName = SO_LINGER;
2885         struct ip_mreq multicastOption;
2886         unsigned int optLen = sizeof(multicastOption);
2887
2888         const _IpMulticastRequestOptionImpl* pMulticastOptionImpl = null;
2889         Ip4Address* pIp4AddrMulti = null;
2890         Ip4Address* pIp4AddrInter = null;
2891         IpAddress* pIpAddrMulti = null;
2892         IpAddress* pIpAddrInter = null;
2893         _Ip4AddressImpl* pIp4AddrImplMulti = null;
2894         _Ip4AddressImpl* pIp4AddrImplInter = null;
2895
2896         unsigned long ipAddrMulti = 0;
2897         unsigned long ipAddrInter = 0;
2898
2899         pMulticastOptionImpl = _IpMulticastRequestOptionImpl::GetInstance(optionValue);
2900
2901         pIpAddrMulti = pMulticastOptionImpl->__pMulticastAddr->GetAddress();
2902         SysTryReturnResult(NID_NET_SOCK, pIpAddrMulti, E_SYSTEM,"Multicast address is null.");
2903
2904         pIp4AddrMulti = dynamic_cast <Ip4Address*>(pIpAddrMulti);
2905         SysTryReturnResult(NID_NET_SOCK, pIp4AddrMulti, E_SYSTEM, "Multicast IpAddress is null.");
2906
2907         pIp4AddrImplMulti = _Ip4AddressImpl::GetInstance(*pIp4AddrMulti);
2908         pIp4AddrImplMulti->GetAddress(ipAddrMulti);
2909
2910         pIpAddrInter = pMulticastOptionImpl->__pInterfaceAddr->GetAddress();
2911         SysTryReturnResult(NID_NET_SOCK, pIpAddrInter, E_SYSTEM, "Interface address is null.");
2912
2913         pIp4AddrInter = dynamic_cast <Ip4Address*>(pIpAddrInter);
2914         SysTryReturnResult(NID_NET_SOCK, pIp4AddrInter, E_SYSTEM, "Interface IpAddress is null.");
2915
2916         pIp4AddrImplInter = _Ip4AddressImpl::GetInstance(*pIp4AddrInter);
2917         pIp4AddrImplInter->GetAddress(ipAddrInter);
2918
2919         multicastOption.imr_multiaddr.s_addr = ipAddrMulti;
2920         multicastOption.imr_interface.s_addr = ipAddrInter;
2921
2922         if (setsockopt(__socketFd, optLevel, optName, (char*) &multicastOption, optLen) < 0)
2923         {
2924                 r = ConvertErrorToResult(errno);
2925                 SysLogException(NID_NET_SOCK, r, "[%s] Failed to set the MulticastOption value.", GetErrorMessage(r));
2926         }
2927
2928         return r;
2929 }
2930
2931 int
2932 _SocketImpl::GetSocketFd(void)
2933 {
2934     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2935
2936         return __socketFd;
2937 }
2938
2939 Socket*
2940 _SocketImpl::GetSocket(void) const
2941 {
2942         return __pSocket;
2943 }
2944
2945 _SocketImpl*
2946 _SocketImpl::GetInstance(Socket& socket)
2947 {
2948         return socket.__pSocketImpl;
2949 }
2950
2951 const _SocketImpl*
2952 _SocketImpl::GetInstance(const Socket& socket)
2953 {
2954         return socket.__pSocketImpl;
2955 }
2956
2957 result
2958 _SocketImpl::Dispose(void)
2959 {
2960     SysTryReturnResult(NID_NET_SOCK, __isClosed == false, E_INVALID_STATE, "Socket is already closed.");
2961
2962         result r = E_SUCCESS;
2963
2964         r = Close();
2965         SysTryReturnResult(NID_NET_SOCK, r == E_SUCCESS, r, "Failed to close the socket.");
2966
2967         __isClosed = true;
2968
2969         return r;
2970 }
2971
2972 // glib Event
2973 gboolean
2974 _SocketImpl::OnGioEventCallback(GIOChannel* pSource, GIOCondition condition, gpointer pUserData)
2975 {
2976         SysLog(NID_NET_SOCK, "### OnGioEventCallback ###");
2977
2978         result errorCode = E_SUCCESS;
2979         GIOStatus status = G_IO_STATUS_NORMAL;
2980         gchar buffer[1024];
2981         gsize bytes_read = 0;
2982         int readSize = 0;
2983         int error = 0;
2984
2985         _UserData* pRecvUserData = (_UserData*) pUserData;
2986
2987         _SocketImpl* pSocketImpl = static_cast <_SocketImpl*>(pRecvUserData->pSocketImpl);
2988         GSource* pGSource = static_cast <GSource*>(pRecvUserData->pGSource);
2989
2990         _SocketEventArg* pEventArg = null;
2991
2992         SysLog(NID_NET_SOCK, "====> [Event] OnGioEventCallback : All GIO event is received.(%d).", condition);
2993
2994         if (condition & G_IO_ERR)
2995         {
2996                 SysLog(NID_NET_SOCK, "====> [Event] Socket event is received.(G_IO_ERR)");
2997
2998                 if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSocketImpl->__isCloseFired == false))
2999                 {
3000                         // Fire the event(NET_SOCKET_EVENT_CLOSE)
3001                         pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
3002                         SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3003                         // G_IO_ERROR Converting
3004                         status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
3005                         errorCode = ConvertGioStatus(status);
3006                         pEventArg->SetError(E_SUCCESS);
3007                         pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3008
3009                         g_source_set_callback(pGSource, null, null, null);
3010                         SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
3011
3012                         goto CATCH;
3013                 }
3014         }
3015
3016         if (pSocketImpl->__isServer)    // For Server
3017         {
3018                 SysLog(NID_NET_SOCK, "====> [Event] This is server");
3019
3020                 if (condition & (G_IO_IN))
3021                 {
3022                         SysLog(NID_NET_SOCK, "====> [Event] Socket event is received.(G_IO_IN)");
3023
3024                         struct pollfd fds[1];
3025                         fds[0].fd = pSocketImpl->__socketFd;
3026                         fds[0].events = POLLRDHUP;
3027
3028
3029                         error = poll(fds, 1, 0);
3030             SysTryCatch(NID_NET_SOCK, error != -1, , null, "Failed to the poll");
3031
3032
3033                         if (fds[0].revents & POLLRDHUP)
3034                         {
3035                                 SysLog(NID_NET_SOCK, "====> Socket is not available.(POLLRDHUP)");
3036
3037                                 if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSocketImpl->__isCloseFired == false))
3038                                 {
3039                                         // Fire the event(NET_SOCKET_EVENT_CLOSE)
3040                                         pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
3041                                         SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3042                                         // G_IO_ERROR Converting
3043                                         status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
3044                                         errorCode = ConvertGioStatus(status);
3045                                         pEventArg->SetError(errorCode);
3046                                         pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3047
3048                                         g_source_set_callback(pGSource, null, null, null);
3049                                         SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null.(%d)", g_source_get_id(pGSource));
3050
3051                                         goto CATCH;
3052                                 }
3053                         }
3054                         else
3055                         {
3056                                 SysLog(NID_NET_SOCK, "====> Socket is available.(Not POLLRDHUP)");
3057
3058                                 if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_ACCEPT) && (pSocketImpl->__isAcceptFired == false) &&
3059                                         (pSocketImpl->__isCloseFired == false) && (pSocketImpl->__socketType == NET_SOCKET_TYPE_STREAM))
3060                                 {
3061                                         // Fire the event(NET_SOCKET_EVENT_ACCEPT)
3062                                         pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_ACCEPT);
3063                                         SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3064                                         pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3065
3066                                         goto CATCH;
3067                                 }
3068                         }
3069                 }
3070
3071                 if (condition & (G_IO_OUT))
3072                 {
3073                         SysLog(NID_NET_SOCK, "====> [Event] Socket event is received.(G_IO_OUT).");
3074                 }
3075
3076         }
3077         else // For Client
3078         {
3079                 SysLog(NID_NET_SOCK, "====> [Event] This is Client");
3080
3081                 if (condition & (G_IO_IN))
3082                 {
3083                     SysLog(NID_NET_SOCK, "====> [Event] Socket event is Received.(G_IO_IN).");
3084
3085                         struct pollfd fds[1];
3086                         fds[0].fd = pSocketImpl->__socketFd;
3087                         fds[0].events = POLLRDHUP;
3088
3089                         error = poll(fds, 1, 0);
3090             SysTryCatch(NID_NET_SOCK, error != -1, , null, "Failed to the poll");
3091
3092                         if (fds[0].revents & POLLRDHUP)
3093                         {
3094                                 SysLog(NID_NET_SOCK, "====> Socket is not available.(POLLRDHUP)");
3095
3096                                 ioctl(pSocketImpl->__socketFd, FIONREAD, &readSize);
3097                                 SysLog(NID_NET_SOCK, "Amount of data that can be read : %d bytes. [Fd : %d byte]", readSize, pSocketImpl->__socketFd);
3098
3099                                 if (readSize <= 0)
3100                                 {
3101                                         if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSocketImpl->__isCloseFired == false))
3102                                         {
3103                                                 // Fire the event(NET_SOCKET_EVENT_CLOSE)
3104                                                 pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
3105                                                 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3106                                                 // G_IO_ERROR Converting
3107                                                 status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
3108                                                 errorCode = ConvertGioStatus(status);
3109                                                 pEventArg->SetError(errorCode);
3110                                                 pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3111
3112                                                 g_source_set_callback(pGSource, null, null, null);
3113                                                 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
3114
3115                                                 goto CATCH;
3116                                         }
3117                                 }
3118                                 else
3119                                 {
3120                                         if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_READ) && (pSocketImpl->__isReadFired == false) &&
3121                                                 (pSocketImpl->__isErrorReadFired == false) && (pSocketImpl->__isCloseFired == false))
3122                                         {
3123                                                 // Fire the event(NET_SOCKET_EVENT_READ)
3124                                                 pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_READ);
3125                                                 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3126                                                 pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3127
3128                                                 pSocketImpl->__isErrorReadFired = true;
3129
3130                                                 goto CATCH;
3131                                         }
3132
3133                                         if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_CLOSE) && (pSocketImpl->__isCloseFired == false))
3134                                         {
3135                                                 // Fire the event(NET_SOCKET_EVENT_CLOSE)
3136                                                 pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_CLOSE);
3137                                                 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3138                                                 // G_IO_ERROR Converting
3139                                                 // status = g_io_channel_read_chars(pSource, buffer, sizeof(buffer), &bytes_read, null);
3140                                                 // errorCode = ConvertGioStatus(status);
3141                                                 pEventArg->SetError(E_SUCCESS);
3142                                                 pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3143
3144                                                 g_source_set_callback(pGSource, null, null, null);
3145                                                 SysLog(NID_NET_SOCK, "### Set giocondition for GSource to null (%d)", g_source_get_id(pGSource));
3146
3147                                                 goto CATCH;
3148                                         }
3149                                 }
3150                         }
3151                         else
3152                         {
3153                                 SysLog(NID_NET_SOCK, "====> Socket is available.(Not POLLRDHUP)");
3154
3155                                 if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_READ) && (pSocketImpl->__isReadFired == false) &&
3156                                         (pSocketImpl->__isCloseFired == false))
3157                                 {
3158                                         // Fire the event(NET_SOCKET_EVENT_READ)
3159                                         pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_READ);
3160                                         SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3161                                         pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3162
3163                                         goto CATCH;
3164                                 }
3165                         }
3166                 }
3167
3168                 if (condition & (G_IO_OUT))
3169                 {
3170                         SysLog(NID_NET_SOCK, "====> [Event] Socket event is Received.(G_IO_OUT).");
3171
3172                         if (pSocketImpl->__isWriteFired == true)
3173                         {
3174                             errorCode = pSocketImpl->__pGlibSocketInfo->SetSocketEvent(pSocketImpl, pSocketImpl->__socketFd);
3175                                 SysTryReturn(NID_NET_SOCK, errorCode == E_SUCCESS, true, errorCode, "[%s] Memory allocation failed.", GetErrorMessage(errorCode));
3176                                 SysLog(NID_NET_SOCK, "SocketFd : [%d], Set the socketEvent to release G_IO_OUT condition in OnGioEventCallback.", pSocketImpl->__socketFd);
3177
3178                                 goto CATCH;
3179                         }
3180
3181                         if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_CONNECT) && (pSocketImpl->__isConnectFired == false) &&
3182                                 (pSocketImpl->__isCloseFired == false) && (pSocketImpl->__socketType == NET_SOCKET_TYPE_STREAM))
3183                         {
3184                                 // Fire the event(NET_SOCKET_EVENT_CONNECT)
3185                                 pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_CONNECT);
3186                                 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3187                                 pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3188
3189                                 goto CATCH;
3190                         }
3191
3192                         if ((pSocketImpl->__socketEventType & NET_SOCKET_EVENT_WRITE) && (pSocketImpl->__isConnectFired == true) &&
3193                                 (pSocketImpl->__isWriteFired == false) && (pSocketImpl->__isCloseFired == false))
3194                         {
3195                                 // Fire the event(NET_SOCKET_EVENT_WRITE)
3196                                 pEventArg = new (std::nothrow) _SocketEventArg(pSocketImpl->__socketFd, NET_SOCKET_EVENT_WRITE);
3197                                 SysTryCatch(NID_NET_SOCK, pEventArg, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed.");
3198                                 pSocketImpl->__pSocketEvent->Fire(*pEventArg);
3199
3200                                 goto CATCH;
3201                         }
3202                 }
3203         }
3204
3205         if (condition & G_IO_PRI)
3206         {
3207                 SysLog(NID_NET_SOCK, "====> [Event] Socket event is Received.(G_IO_PRI).");
3208         }
3209
3210         if (condition & G_IO_HUP)
3211         {
3212                 SysLog(NID_NET_SOCK, "====> [Event] Socket event is Received.(G_IO_HUP).");
3213         }
3214
3215         if (condition & G_IO_NVAL)
3216         {
3217                 SysLog(NID_NET_SOCK, "====> [Event] Socket event is Received.(G_IO_NVAL).");
3218         }
3219
3220         return true;
3221
3222 CATCH:
3223         return true;
3224 }
3225
3226 gboolean
3227 _SocketImpl::OnTimerCallback(gpointer pUserData)
3228 {
3229         SysLog(NID_NET_SOCK, "### OnTimercallback ###");
3230
3231         _SocketImpl* pSocketImpl = static_cast <_SocketImpl*>(pUserData);
3232
3233         pSocketImpl->__isTimeout = true;
3234
3235         return true;
3236 }
3237
3238 _GlibSocketInfo::_GlibSocketInfo(void)
3239         : __pSocketChannel(null)
3240         , __pSocketSource(null)
3241         , __socketFd(INVALID_HANDLE)
3242         , __pUserData(null)
3243 {
3244 }
3245
3246 _GlibSocketInfo::~_GlibSocketInfo(void)
3247 {
3248     delete __pUserData;
3249     __pUserData = null;
3250
3251         if (__pSocketSource != null)
3252         {
3253                 g_source_set_callback(__pSocketSource, null, null, null);
3254                 SysLog(NID_NET_SOCK, "### Deleted g_source_destroy(%d)", g_source_get_id(__pSocketSource));
3255                 g_source_destroy(__pSocketSource);
3256                 g_source_unref(__pSocketSource);
3257                 __pSocketSource = null;
3258         }
3259
3260         if (__pSocketChannel != null)
3261         {
3262                 g_io_channel_unref(__pSocketChannel);
3263                 __pSocketChannel = null;
3264         }
3265 }
3266
3267 result
3268 _GlibSocketInfo::SetSocketEvent(_SocketImpl* pSocketImpl, HSocket socketFd)
3269 {
3270         result r = E_SUCCESS;
3271
3272         GIOCondition condition = (GIOCondition)0;
3273
3274         if (__pSocketChannel == null)
3275         {
3276                 __pUserData = new (std::nothrow) _UserData;
3277                 SysTryReturnResult(NID_NET_SOCK, __pUserData, E_OUT_OF_MEMORY, "Memory allocation failed.");
3278
3279                 __pSocketChannel = g_io_channel_unix_new(socketFd);
3280                 SysLog(NID_NET_SOCK, "Created the SocketChannel. [Fd : %d]", socketFd);
3281         }
3282
3283         // Set masking of wanted socket Event
3284         if (pSocketImpl->__isWriteFired == false)
3285     {
3286         condition = static_cast <GIOCondition>(G_IO_IN | G_IO_OUT | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3287     }
3288         else
3289         {
3290                 condition = static_cast <GIOCondition>(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL);
3291         }
3292
3293         // G_IO_IN : There is data to read. 1
3294         // G_IO_OUT : Data can be written (without blocking). 4
3295         // G_IO_PRI : There is urgent data to read. 2
3296         // G_IO_ERR : Error condition. 8
3297         // G_IO_HUP : Hung up (the connection has been broken, usually for pipes and sockets). 16
3298         // G_IO_NVAL : Invalid request. The file descriptor is not open. 32
3299
3300         if (__pSocketSource != null)
3301         {
3302                 g_source_set_callback(__pSocketSource, null, null, null);
3303                 SysLog(NID_NET_SOCK, "### Deleted g_source_destroy(%d)", g_source_get_id(__pSocketSource));
3304                 g_source_destroy(__pSocketSource);
3305                 g_source_unref(__pSocketSource);
3306                 __pSocketSource = null;
3307                 SysLog(NID_NET_SOCK, "Unref the SocketSource.");
3308         }
3309
3310         __pSocketSource = g_io_create_watch(__pSocketChannel, condition);
3311
3312         __pUserData->pSocketImpl = (_SocketImpl*) pSocketImpl;
3313         __pUserData->pGSource = (GSource*) __pSocketSource;
3314
3315         g_source_set_callback(__pSocketSource, (GSourceFunc) _SocketImpl::OnGioEventCallback, __pUserData, null);
3316         g_source_attach(__pSocketSource, pSocketImpl->__pGMainContext);
3317
3318         SysLog(NID_NET_SOCK, "Created the GSource Id : [%d]", g_source_get_id(__pSocketSource));
3319         SysLog(NID_NET_SOCK, "Created the SocketSource for receiving the event. [%d]", condition);
3320
3321         return r;
3322 }
3323
3324 } } } // Tizen::Net::Sockets