Debian Codegraph @

gobi-api/GobiAPI_2012-07-12-1036/Core/Socket.cpp

raw
1 /*===========================================================================
2 FILE:
3 Socket.cpp
4
5 DESCRIPTION:
6 Implementation of cSocket class
7
8 PUBLIC CLASSES AND METHODS:
9 cSocket
10 This class wraps low level communication to qmuxd
11
12 Copyright (c) 2012, Code Aurora Forum. All rights reserved.
13
14 Redistribution and use in source and binary forms, with or without
15 modification, are permitted provided that the following conditions are met:
16 * Redistributions of source code must retain the above copyright
17 notice, this list of conditions and the following disclaimer.
18 * Redistributions in binary form must reproduce the above copyright
19 notice, this list of conditions and the following disclaimer in the
20 documentation and/or other materials provided with the distribution.
21 * Neither the name of Code Aurora Forum nor
22 the names of its contributors may be used to endorse or promote
23 products derived from this software without specific prior written
24 permission.
25
26
27 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
31 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 POSSIBILITY OF SUCH DAMAGE.
38 ===========================================================================*/
39
40 //---------------------------------------------------------------------------
41 // Include Files
42 //---------------------------------------------------------------------------
43 #include "StdAfx.h"
44 #include "Socket.h"
45 #include "ProtocolServer.h"
46 #include <sys/socket.h>
47 #include <sys/un.h>
48
49 //---------------------------------------------------------------------------
50 // Definitions
51 //---------------------------------------------------------------------------
52 // Thread commands
53 #define START_READ_CMD 0
54 #define STOP_READ_CMD 1
55 #define EXIT_CMD 2
56
57 // Size of the QMUXD command payload
58 // GET_CLIENT_ID and RELEASE_CLIENT_ID must pass in a buffer of this size
59 #define PAYLOAD_SIZE 664
60
61 /*=========================================================================*/
62 // struct sQMUXDHeader
63 /*=========================================================================*/
64 #pragma pack( push, 1 )
65
66 struct sQMUXDHeader
67 {
68 /* Total size of header and following buffer */
69 int mTotalSize;
70
71 /* QMUXD client ID */
72 int mQMUXDClientID;
73
74 /* Message type */
75 eQMUXDMessageTypes mQMUXDMsgID;
76
77 /* Duplicate of mQMUXDClientID */
78 int mQMUXDClientIDDuplicate;
79
80 /* Transaction ID */
81 unsigned long mTxID;
82
83 /* System error code */
84 int mSysErrCode;
85
86 /* QMI error code (duplicate of TLV 0x02) */
87 int mQmiErrCode;
88
89 /* SMD channel. 0 = SMD_DATA_5 */
90 int mQMUXDConectionType;
91
92 /* QMI service ID */
93 int mQMUXServiceID;
94
95 /* QMI client ID */
96 unsigned char mQMUXClientID;
97
98 /* QMI flags */
99 unsigned char mRxFlags;
100
101 /* In QMUXD this struct is not packed, so the compiler appends
102 these two bytes */
103 unsigned short int mMissing2Bytes;
104 };
105
106 #pragma pack( pop )
107
108
109 /*=========================================================================*/
110 // Free Methods
111 /*=========================================================================*/
112
113 /*===========================================================================
114 METHOD:
115 RxSocketThread (Free Method)
116
117 DESCRIPTION:
118 Thread for simulating asynchronous reads to a socket
119
120 PARAMETERS:
121 pData [ I ] cSocket pointer
122
123 RETURN VALUE:
124 void * - thread exit value (always 0)
125 ===========================================================================*/
126 void * RxSocketThread( void * pData )
127 {
128 cSocket * pSocket = (cSocket*)pData;
129 if (pSocket == NULL || pSocket->IsValid() == false)
130 {
131 return 0;
132 }
133
134 fd_set inputSet, outputSet;
135 FD_ZERO( &inputSet );
136 FD_SET( pSocket->mCommandPipe[READING], &inputSet );
137 int largestFD = pSocket->mCommandPipe[READING];
138
139 int status = 0;
140 while (true)
141 {
142 // No FD_COPY() available
143 memcpy( &outputSet, &inputSet, sizeof( fd_set ) );
144
145 // Wait until we recieve a command or data is available
146 status = select( largestFD + 1, &outputSet, NULL, NULL, NULL );
147 if (status <= 0)
148 {
149 TRACE( "error %d in select, errno %d\n", status, errno );
150 break;
151 }
152
153 if (FD_ISSET( pSocket->mCommandPipe[READING], &outputSet ) == true)
154 {
155 // Read command value from the pipe
156 BYTE cmd;
157 status = read( pSocket->mCommandPipe[READING], &cmd, 1 );
158 if (status != 1)
159 {
160 TRACE( "cmd error %d\n", status );
161 break;
162 }
163
164 if (cmd == START_READ_CMD)
165 {
166 FD_SET( pSocket->mSocket, &inputSet );
167 largestFD = std::max( pSocket->mSocket,
168 pSocket->mCommandPipe[READING] );
169 }
170 else if (cmd == STOP_READ_CMD)
171 {
172 FD_CLR( pSocket->mSocket, &inputSet );
173 largestFD = pSocket->mCommandPipe[READING];
174 }
175 else
176 {
177 // EXIT_CMD or anything else
178 pSocket->mpRxCallback = 0;
179 break;
180 }
181 }
182 else if (FD_ISSET( pSocket->mSocket, &outputSet ) == true)
183 {
184 // Stop watching for read data
185 FD_CLR( pSocket->mSocket, &inputSet );
186 largestFD = pSocket->mCommandPipe[READING];
187
188 // Perform a recv for the header
189 sQMUXDHeader recvHdr;
190 status = recv( pSocket->mSocket,
191 &recvHdr,
192 sizeof( recvHdr ),
193 0 );
194 if (status != sizeof( recvHdr ))
195 {
196 TRACE( "recv error, bad size %d\n", status );
197 break;
198 }
199
200 // Calculate and read the remaining data
201 int remainder = recvHdr.mTotalSize - sizeof( recvHdr );
202 if (remainder > pSocket->mBuffSz)
203 {
204 TRACE( "read too large for buffer\n" );
205 break;
206 }
207
208 status = recv( pSocket->mSocket,
209 pSocket->mpBuffer,
210 remainder,
211 0 );
212
213 // Is this one of our IOCTLS or a standard message?
214 if (recvHdr.mQMUXDMsgID == eQMUXD_MSG_WRITE_QMI_SDU)
215 {
216 cIOCallback * pCallback = pSocket->mpRxCallback;
217 pSocket->mpRxCallback = 0;
218
219 if (pCallback == (cIOCallback *)1)
220 {
221 // We wanted to read, but not to be notified
222 }
223 else if (status >= 0)
224 {
225 pCallback->IOComplete( 0, status );
226 }
227 else
228 {
229 pCallback->IOComplete( status, 0 );
230 }
231 }
232 else
233 {
234 pSocket->mpRxCallback = 0;
235 // Notify SendCtl() that control message completed
236
237 if (recvHdr.mQMUXDMsgID == eQMUXD_MSG_ALLOC_QMI_CLIENT_ID)
238 {
239 DWORD clientID;
240 memcpy( &clientID, &pSocket->mpBuffer[0], 4 );
241
242 pSocket->mCtrlMsgComplete.Set( clientID );
243 }
244 else
245 {
246 // Just set the event
247 pSocket->mCtrlMsgComplete.Set( 0 );
248 }
249 }
250 }
251 }
252
253 return 0;
254 };
255
256 /*=========================================================================*/
257 // cSocket Methods
258 /*=========================================================================*/
259
260 /*===========================================================================
261 METHOD:
262 cSocket (Public Method)
263
264 DESCRIPTION:
265 Constructor
266
267 RETURN VALUE:
268 None
269 ===========================================================================*/
270 cSocket::cSocket()
271 : mSocket( INVALID_HANDLE_VALUE ),
272 mbCancelWrite( false ),
273 mpBuffer( 0 ),
274 mBuffSz( 0 ),
275 mRxThreadID( 0 ),
276 mCtrlMsgComplete(),
277 mQMUXDClientID( 0 ),
278 mQMUXClientID( 0 ),
279 mQMUXServiceID( 0 ),
280 mChannelID( -1 ),
281 mQMUXDTxID( 0 )
282 {
283 mCommandPipe[READING] = INVALID_HANDLE_VALUE;
284 mCommandPipe[WRITING] = INVALID_HANDLE_VALUE;
285 }
286
287 /*===========================================================================
288 METHOD:
289 ~cSocket (Public Method)
290
291 DESCRIPTION:
292 Destructor
293
294 RETURN VALUE:
295 None
296 ===========================================================================*/
297 cSocket::~cSocket()
298 {
299 // Disconnect from current port
300 Disconnect();
301
302 mCommandPipe[READING] = INVALID_HANDLE_VALUE;
303 mCommandPipe[WRITING] = INVALID_HANDLE_VALUE;
304 }
305
306 /*===========================================================================
307 METHOD:
308 IsValid (Public Method)
309
310 DESCRIPTION:
311 Is this object valid?
312
313 RETURN VALUE:
314 Bool
315 ===========================================================================*/
316 bool cSocket::IsValid()
317 {
318 // Nothing to do
319 return true;
320 }
321
322 /*===========================================================================
323 METHOD:
324 Connect (Public Method)
325
326 DESCRIPTION:
327 Connect to the specified port
328
329 PARAMETERS:
330 pChannel [ I ] - Channel number (IE: "0" = SMD_DATA_5 )
331
332 RETURN VALUE:
333 bool
334 ===========================================================================*/
335 bool cSocket::Connect( LPCSTR pChannel )
336 {
337 if (IsValid() == false || pChannel == 0 || pChannel[0] == 0)
338 {
339 return false;
340 }
341
342 if (mSocket != INVALID_HANDLE_VALUE)
343 {
344 Disconnect();
345 }
346
347 // Initialize command pipe for read thread
348 int nRet = pipe( mCommandPipe );
349 if (nRet != 0)
350 {
351 TRACE( "cSocket:Connect() pipe creation failed %d\n", nRet );
352 return false;
353 }
354
355 // Start the read thread
356 nRet = pthread_create( &mRxThreadID,
357 0,
358 RxSocketThread,
359 this );
360 if (nRet != 0)
361 {
362 TRACE( "cSocket::Connect() pthread_create = %d\n", nRet );
363
364 Disconnect();
365 return false;
366 }
367
368 // Create a socket
369 mSocket = socket( AF_UNIX, SOCK_STREAM, 0 );
370 if (mSocket == INVALID_HANDLE_VALUE)
371 {
372 TRACE( "unable to create socket %d\n", errno );
373
374 Disconnect();
375 return false;
376 }
377
378 struct sockaddr_un clientSockAddr;
379 memset( &clientSockAddr, 0, sizeof( clientSockAddr ) );
380 clientSockAddr.sun_family = AF_UNIX;
381
382 // Format the client path
383 snprintf( &clientSockAddr.sun_path[0],
384 sizeof( clientSockAddr.sun_path ),
385 "/var/qmux_client_socket%7lu",
386 (unsigned long)getpid() );
387
388 // Delete if it exists already
389 unlink( clientSockAddr.sun_path );
390
391 // Bind to a client address
392 nRet = bind( mSocket,
393 (struct sockaddr *)&clientSockAddr,
394 sizeof( sockaddr_un ) );
395 if (nRet == -1)
396 {
397 TRACE( "bad bind %d\n", errno );
398
399 Disconnect();
400 return false;
401 }
402
403 // Format the connection path
404 struct sockaddr_un connectSockAddr;
405 memset( &connectSockAddr, 0, sizeof( connectSockAddr ) );
406 connectSockAddr.sun_family = AF_UNIX;
407
408 snprintf( &connectSockAddr.sun_path[0],
409 sizeof( connectSockAddr.sun_path ),
410 "/var/qmux_connect_socket" );
411
412 // Connect to server address
413 nRet = connect( mSocket,
414 (struct sockaddr *)&connectSockAddr,
415 sizeof( sockaddr_un ) );
416 if (nRet < 0)
417 {
418 TRACE( "bad connect %d\n", errno );
419
420 Disconnect();
421 return false;
422 }
423
424 int clientID;
425 nRet = recv( mSocket, &clientID, sizeof( clientID ), 0 );
426 if (nRet != sizeof( clientID ))
427 {
428 printf( "bad client ID %d\n", errno );
429
430 Disconnect();
431 return false;
432 }
433
434 // Save QMUXD Client ID
435 mQMUXDClientID = clientID;
436
437 // Save SMD channel
438 mChannelID = strtol( pChannel, 0, 10 );
439 if (mChannelID == -1)
440 {
441 Disconnect();
442 return false;
443 }
444
445 // Success!
446 return true;
447 }
448
449 /*===========================================================================
450 METHOD:
451 SendCtl (Public Method)
452
453 DESCRIPTION:
454 Send a control message to the lower layer
455
456 PARAMETERS:
457 msgType [ I ] - eQMUXDMessageType
458 pData [I/O] - input or output specific to ioctl request value
459
460 RETURN VALUE:
461 int - control message return value (0 for success)
462 ===========================================================================*/
463 int cSocket::SendCtl(
464 UINT msgType,
465 void * pData )
466 {
467 if (mSocket == INVALID_HANDLE_VALUE)
468 {
469 TRACE( "Invalid file handle\n" );
470 return -EBADFD;
471 }
472
473 BYTE msg[sizeof( sQMUXDHeader ) + PAYLOAD_SIZE];
474 memset( &msg[0], 0, sizeof( msg ) );
475
476 // The important QMUXD header values
477 sQMUXDHeader * pHdr = (sQMUXDHeader *)&msg[0];
478 pHdr->mTotalSize = sizeof( msg );
479 pHdr->mQMUXDClientID = mQMUXDClientID;
480 pHdr->mQMUXDMsgID = (eQMUXDMessageTypes)msgType;
481 pHdr->mQMUXDClientIDDuplicate = mQMUXDClientID;
482
483 // mQMUXDTxID could go to INT_MAX, but rather than dealing with possible
484 // overflow in qmuxd or one of the lower layers, we'll stop early
485 mQMUXDTxID++;
486 if (mQMUXDTxID > 100000)
487 {
488 mQMUXDTxID = 1;
489 }
490 pHdr->mTxID = ++mQMUXDTxID;
491
492 // The Payload
493 BYTE * pPayload = &msg[sizeof( sQMUXDHeader )];
494 if (msgType == (int)eQMUXD_MSG_ALLOC_QMI_CLIENT_ID)
495 {
496 memcpy( &mQMUXServiceID, pData, 4 );
497 memcpy( &pPayload[0], &mQMUXServiceID, 4 );
498 }
499 else if (msgType == (int)eQMUXD_MSG_RELEASE_QMI_CLIENT_ID)
500 {
501 memcpy( &pPayload[0], &mQMUXServiceID, 4 );
502 memcpy( &pPayload[4], &mQMUXClientID, 4 );
503 }
504
505 // Send the message
506 int rc = send( mSocket, &msg[0], sizeof( msg ), 0 );
507 if (rc != sizeof( msg ))
508 {
509 TRACE( "bad write %d\n", rc );
510 return rc;
511 }
512
513 if (mpRxCallback == 0)
514 {
515 // No one is currently reading, need to trigger a read
516 // so our data can be recieved
517 RxData( &msg[0], sizeof( msg ), 0 );
518 }
519
520 // Wait for the response (10s timeout)
521 DWORD val;
522 rc = mCtrlMsgComplete.Wait( 10000, val );
523 if (rc != 0)
524 {
525 TRACE( "bad SendCtl() wait %d\n", rc );
526 return rc;
527 }
528
529 if (msgType == (int)eQMUXD_MSG_ALLOC_QMI_CLIENT_ID)
530 {
531 // Grab the client ID
532 mQMUXClientID = val;
533 }
534
535 return 0;
536 }
537
538 /*===========================================================================
539 METHOD:
540 Disconnect (Public Method)
541
542 DESCRIPTION:
543 Disconnect from the current port
544
545 RETURN VALUE:
546 bool
547 ===========================================================================*/
548 bool cSocket::Disconnect()
549 {
550 // Assume success
551 bool bRC = true;
552
553 if (mCommandPipe[WRITING] != INVALID_HANDLE_VALUE)
554 {
555 if (mRxThreadID != 0)
556 {
557 // Notify the thread to exit
558 BYTE byte = EXIT_CMD;
559 write( mCommandPipe[WRITING], &byte, 1 );
560
561 // And wait for it
562 int nRC = pthread_join( mRxThreadID, 0 );
563 if (nRC != 0)
564 {
565 TRACE( "failed to join thread %d\n", nRC );
566 bRC = false;
567 }
568
569 mRxThreadID = 0;
570 }
571
572 close( mCommandPipe[WRITING] );
573 close( mCommandPipe[READING] );
574 mCommandPipe[READING] = INVALID_HANDLE_VALUE;
575 mCommandPipe[WRITING] = INVALID_HANDLE_VALUE;
576 }
577
578 if (mSocket != INVALID_HANDLE_VALUE)
579 {
580 close( mSocket );
581 mSocket = INVALID_HANDLE_VALUE;
582 }
583
584 // Double check
585 mpRxCallback = 0;
586
587 mCtrlMsgComplete.Clear();
588 mQMUXDClientID = 0;
589 mQMUXClientID = 0;
590 mQMUXServiceID = 0;
591 mQMUXDTxID = 0;
592 return bRC;
593 }
594
595 /*===========================================================================
596 METHOD:
597 CancelIO (Public Method)
598
599 DESCRIPTION:
600 Cancel any in-progress I/O
601
602 PARAMETERS:
603
604 RETURN VALUE:
605 bool
606 ===========================================================================*/
607 bool cSocket::CancelIO()
608 {
609 if (mSocket == INVALID_HANDLE_VALUE)
610 {
611 return false;
612 }
613
614 bool bRxCancel = CancelRx();
615 bool bTxCancel = CancelTx();
616
617 return (bRxCancel && bTxCancel);
618 }
619
620 /*===========================================================================
621 METHOD:
622 CancelRx (Public Method)
623
624 DESCRIPTION:
625 Cancel any in-progress receive operation
626
627 RETURN VALUE:
628 bool
629 ===========================================================================*/
630 bool cSocket::CancelRx()
631 {
632 if (mSocket == INVALID_HANDLE_VALUE
633 || mCommandPipe[WRITING] == INVALID_HANDLE_VALUE
634 || mpRxCallback == 0
635 || mRxThreadID == 0)
636 {
637 TRACE( "cannot cancel, thread not active\n" );
638 mpRxCallback = 0;
639 return false;
640 }
641
642 // Notify the thread to stop reading
643 BYTE byte = STOP_READ_CMD;
644 int nRC = write( mCommandPipe[WRITING], &byte, 1 );
645 if (nRC != 1)
646 {
647 TRACE( "error %d canceling read\n", nRC );
648 return false;
649 }
650
651 // Remove the old callback
652 mpRxCallback = 0;
653
654 return true;
655 }
656
657 /*===========================================================================
658 METHOD:
659 CancelTx (Public Method)
660
661 DESCRIPTION:
662 Cancel any in-progress transmit operation
663
664 RETURN VALUE:
665 bool
666 ===========================================================================*/
667 bool cSocket::CancelTx()
668 {
669 if (mSocket == INVALID_HANDLE_VALUE)
670 {
671 return false;
672 }
673
674 mbCancelWrite = true;
675
676 return true;
677 }
678
679 /*===========================================================================
680 METHOD:
681 RxData (Public Method)
682
683 DESCRIPTION:
684 Receive data
685
686 PARAMETERS:
687 pBuf [ I ] - Buffer to contain received data
688 bufSz [ I ] - Amount of data to be received
689 pCallback [ I ] - Callback object to be exercised when the
690 operation completes
691
692 RETURN VALUE:
693 bool
694 ===========================================================================*/
695 bool cSocket::RxData(
696 BYTE * pBuf,
697 ULONG bufSz,
698 cIOCallback * pCallback )
699 {
700 if (IsValid() == false || mpRxCallback != 0)
701 {
702 return false;
703 }
704
705 if (pCallback == 0)
706 {
707 // Not interested in being notified, but we still need a value
708 // for this so that only one outstanding I/O operation is active
709 // at any given point in time
710 mpRxCallback = (cIOCallback * )1;
711 }
712 else
713 {
714 mpRxCallback = pCallback;
715 }
716
717 mpBuffer = pBuf;
718 mBuffSz = bufSz;
719
720 // Notify the thread to start reading
721 BYTE byte = START_READ_CMD;
722 int nRC = write( mCommandPipe[WRITING], &byte, 1 );
723 if (nRC != 1)
724 {
725 TRACE( "error %d starting read\n", nRC );
726 return false;
727 }
728
729 return true;
730 }
731
732 /*===========================================================================
733 METHOD:
734 TxData (Public Method)
735
736 DESCRIPTION:
737 Transmit data
738
739 PARAMETERS:
740 pBuf [ I ] - Data to be transmitted
741 bufSz [ I ] - Amount of data to be transmitted
742
743 RETURN VALUE:
744 bool
745 ===========================================================================*/
746 bool cSocket::TxData(
747 const BYTE * pBuf,
748 ULONG bufSz )
749 {
750 if (IsValid() == false)
751 {
752 return false;
753 }
754
755 #ifdef DEBUG
756 ULONGLONG nStart = GetTickCount();
757 #endif
758
759 // Allow ourselves to be interupted
760 mbCancelWrite = false;
761
762 // Format the header
763 int totalSz = sizeof( sQMUXDHeader ) + bufSz;
764 BYTE * pMsg = new BYTE[totalSz];
765 if (pMsg == 0)
766 {
767 TRACE( "unable to allocate buffer\n" );
768 return false;
769 }
770 memset( pMsg, 0, totalSz );
771
772 // The important QMUXD header values
773 sQMUXDHeader * pHdr = (sQMUXDHeader *)pMsg;
774 pHdr->mTotalSize = totalSz;
775 pHdr->mQMUXDClientID = mQMUXDClientID;
776 pHdr->mQMUXDMsgID = eQMUXD_MSG_WRITE_QMI_SDU;
777 pHdr->mQMUXDClientIDDuplicate = mQMUXDClientID;
778
779 // mQMUXDTxID could go to INT_MAX, but rather than dealing with possible
780 // overflow in qmuxd or one of the lower layers, we'll stop early
781 mQMUXDTxID++;
782 if (mQMUXDTxID > 100000)
783 {
784 mQMUXDTxID = 1;
785 }
786 pHdr->mTxID = ++mQMUXDTxID;
787
788 pHdr->mQMUXServiceID = mQMUXServiceID;
789 pHdr->mQMUXClientID = mQMUXClientID;
790
791 // The data payload
792 memcpy( &pMsg[sizeof( sQMUXDHeader )], pBuf, bufSz );
793
794 // Send the message
795 int nRet = send( mSocket, pMsg, totalSz, 0 );
796 delete [] pMsg;
797 if (nRet != totalSz)
798 {
799 TRACE( "cSocket::TxData() write returned %d instead of %d\n",
800 nRet,
801 totalSz );
802 return false;
803 }
804
805 #ifdef DEBUG
806 TRACE( "Write of %d bytes took %llu miliseconds\n",
807 totalSz,
808 GetTickCount() - nStart );
809 #endif
810
811 return true;
812 }