* [ GAM-6 ] enhace routing algorithm: changed the way the routing algorithm gets...
[profile/ivi/audiomanager.git] / AudioManagerDaemon / src / TelnetServer.cpp
1 /**
2  * Copyright (C) 2011, BMW AG
3  *
4  * GeniviAudioMananger AudioManagerDaemon
5  *
6  * \file TelnetServer.cpp
7  *
8  * \date 20-Oct-2011 3:42:04 PM
9  * \author Christian Mueller (christian.ei.mueller@bmw.de)
10  *
11  * \section License
12  * GNU Lesser General Public License, version 2.1, with special exception (GENIVI clause)
13  * Copyright (C) 2011, BMW AG Christian Mueller  Christian.ei.mueller@bmw.de
14  *
15  * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License, version 2.1, as published by the Free Software Foundation.
16  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License, version 2.1, for more details.
17  * You should have received a copy of the GNU Lesser General Public License, version 2.1, along with this program; if not, see <http://www.gnu.org/licenses/lgpl-2.1.html>.
18  * Note that the copyright holders assume that the GNU Lesser General Public License, version 2.1, may also be applicable to programs even in cases in which the program is not a library in the technical sense.
19  * Linking AudioManager statically or dynamically with other modules is making a combined work based on AudioManager. You may license such other modules under the GNU Lesser General Public License, version 2.1. If you do not want to license your linked modules under the GNU Lesser General Public License, version 2.1, you may use the program under the following exception.
20  * As a special exception, the copyright holders of AudioManager give you permission to combine AudioManager with software programs or libraries that are released under any license unless such a combination is not permitted by the license of such a software program or library. You may copy and distribute such a system following the terms of the GNU Lesser General Public License, version 2.1, including this special exception, for AudioManager and the licenses of the other code concerned.
21  * Note that people who make modified versions of AudioManager are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License, version 2.1, gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception.
22  *
23  */
24
25 #include "TelnetServer.h"
26 #include <cassert>
27 #include <sys/socket.h>
28 #include <arpa/inet.h>
29 #include <sys/ioctl.h>
30 #include <string.h>
31 #include <netdb.h>
32 #include <config.h>
33 #include <errno.h>
34 #include <sstream>
35 #include <istream>
36 #include <iostream>
37 #include <iterator>
38 #include "DatabaseHandler.h"
39 #include "RoutingSender.h"
40 #include "DLTWrapper.h"
41 #include "CAmTelnetMenuHelper.h"
42
43 using namespace am;
44
45 TelnetServer* TelnetServer::instance = NULL;
46
47 #define PRINT_BOOL(var) var ? output+="true\t\t" : output+="false\t\t";
48
49 TelnetServer::TelnetServer(SocketHandler *iSocketHandler, CommandSender *iCommandSender, CommandReceiver *iCommandReceiver, RoutingSender *iRoutingSender, RoutingReceiver *iRoutingReceiver, ControlSender *iControlSender, ControlReceiver *iControlReceiver, DatabaseHandler *iDatabasehandler, Router *iRouter, unsigned int servPort, unsigned int maxConnections)
50    :telnetConnectFiredCB(this,&TelnetServer::connectSocket),
51    telnetReceiveFiredCB(this,&TelnetServer::receiveData),
52    telnetDispatchCB(this,&TelnetServer::dispatchData),
53    telnetCheckCB(this,&TelnetServer::check),
54    mSocketHandler(iSocketHandler),
55    mCommandSender(iCommandSender),
56    mCommandReceiver(iCommandReceiver),
57    mRoutingSender(iRoutingSender),
58    mRoutingReceiver(iRoutingReceiver),
59    mControlSender(iControlSender),
60    mControlReceiver(iControlReceiver),
61    mDatabasehandler(iDatabasehandler),
62    mRouter(iRouter),
63    mConnecthandle(),
64    mMsgList(),
65    mListConnections(),
66    mConnectFD(NULL),
67    mServerPort(servPort),
68    mMaxConnections(maxConnections),
69    mTelnetMenuHelper(iSocketHandler,iCommandSender,iCommandReceiver,iRoutingSender,iRoutingReceiver,iControlSender,iControlReceiver,iDatabasehandler,iRouter,this)
70 {
71         assert(mSocketHandler!=NULL);
72         assert(mCommandReceiver!=NULL);
73         assert(mCommandSender!=NULL);
74         assert(mControlSender!=NULL);
75         assert(mControlReceiver!=NULL);
76         assert(mRoutingSender!=NULL);
77         assert(mRoutingReceiver!=NULL);
78         assert(mDatabasehandler!=NULL);
79         assert(mRouter!=NULL);
80         assert(servPort!=0);
81         assert(mMaxConnections!=0);
82
83         instance = this;
84         //mTelnetMenuHelper.setTelnetServer(this);
85
86         int yes = 1;
87         struct sockaddr_in servAddr;
88
89    //setup the port Listener
90    mConnectFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
91    setsockopt(mConnectFD, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
92    memset(&servAddr, 0, sizeof(servAddr));
93    servAddr.sin_family      = AF_INET;
94    servAddr.sin_addr.s_addr = INADDR_ANY;
95    servAddr.sin_port        = htons(servPort);
96    bind(mConnectFD, (struct sockaddr *) &servAddr, sizeof(servAddr));
97
98    if (listen(mConnectFD,mMaxConnections) < 0)
99    {
100       logError("TelnetServer::TelnetServerk cannot listen ",errno);
101    }
102    else
103       logInfo("TelnetServer::TelnetServer started listening on port", mServerPort);
104
105         int a=1;
106         ioctl (mConnectFD, FIONBIO, (char *) &a); // should we use the posix call fcntl(mConnectFD, F_SETFL, O_NONBLOCK)
107         setsockopt (mConnectFD, SOL_SOCKET, SO_KEEPALIVE, (char *) &a, sizeof (a));
108
109    short events = 0;
110    events |= POLLIN;
111    mSocketHandler->addFDPoll(mConnectFD, events, NULL, &telnetConnectFiredCB, NULL, NULL, NULL, mConnecthandle);
112 }
113
114 TelnetServer::~TelnetServer()
115 {
116    mTelnetMenuHelper.setTelnetServer(NULL);
117 }
118
119 void TelnetServer::connectSocket(const pollfd pfd, const sh_pollHandle_t handle, void *userData)
120 {
121     (void) handle;
122     (void) userData;
123    //first, accept the connection, create a new filedescriptor
124         struct sockaddr answer;
125         socklen_t len=sizeof(answer);
126         connection_s connection;
127         connection.handle = 0;
128         connection.filedescriptor = accept(pfd.fd, (struct sockaddr*)&answer, &len);
129
130         // Notiy menuhelper
131         mTelnetMenuHelper.newSocketConnection(connection.filedescriptor);
132
133         //set the correct event:
134         short event = 0;
135         event |=POLLIN;
136
137         //aded the filedescriptor to the sockethandler and register the callbacks for receiving the data
138         mSocketHandler->addFDPoll(connection.filedescriptor,event,NULL,&telnetReceiveFiredCB,&telnetCheckCB,&telnetDispatchCB,NULL,connection.handle);
139         mListConnections.push_back(connection);
140 }
141
142 void TelnetServer::disconnectClient(int filedescriptor)
143 {
144    std::vector<connection_s>::iterator iter = mListConnections.begin();
145    while(iter != mListConnections.end())
146    {
147       if( filedescriptor == iter->filedescriptor )
148       {
149          if( E_OK == mSocketHandler->removeFDPoll(iter->handle))
150          {
151             mListConnections.erase(iter);
152             close(filedescriptor);
153          }
154          else
155          {
156             // TODO: Handle error
157          }
158
159          break;
160       }
161       iter++;
162    }
163 }
164
165 void TelnetServer::receiveData(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)
166 {
167     (void) handle;
168     (void) userData;
169         //initialize buffer
170         char buffer[100];
171         //read until buffer is full or no more data is there
172         int read=recv(pollfd.fd,buffer,100,NULL);
173         if (read>1)
174         {
175                 //read the message and store it in a queue - its a telnet connection so data will be sent on enter !
176                 std::string msg=std::string(buffer,read);
177                 mMsgList.push(msg);
178         }
179 }
180
181 bool TelnetServer::dispatchData(const sh_pollHandle_t handle, void *userData)
182 {
183     (void) userData;
184         std::vector<connection_s>::iterator iterator=mListConnections.begin();
185         for(;iterator!=mListConnections.end();++iterator)
186         {
187                 if(iterator->handle==handle) break;
188         }
189         //if (iterator==mListConnections.end()) return false;
190
191         std::string command;
192         std::queue<std::string> MsgQueue;
193         if(!mMsgList.empty())
194         {
195            sliceCommand(mMsgList.front(),command,MsgQueue);
196            mMsgList.pop();
197         }
198
199         mTelnetMenuHelper.enterCmdQueue(MsgQueue,iterator->filedescriptor);
200
201         // must return false to stop endless polling
202         return false;
203
204         /*
205         mMsgList.pop();
206         mMapCommand_t::iterator commandIter=mMapCommands.find(command);
207         if (commandIter==mMapCommands.end())
208         {
209                 send(iterator->filedescriptor,"Command not found!\n",20,0);
210         }
211         else
212         {
213            commandIter->second(msg,iterator->filedescriptor);
214                 //(*commandIter).second(msg,iterator->filedescriptor);
215         }
216
217         //remove the message from the queue and return false if there is no more message to read.
218         if (mMsgList.size()!=0) return true;
219         return false;
220         */
221 }
222
223 bool TelnetServer::check(const sh_pollHandle_t handle, void *userData)
224 {
225     (void)handle;
226     (void)userData;
227     if (mMsgList.size() != 0) return true;
228     return false;
229 }
230
231 void am::TelnetServer::sliceCommand(const std::string & string, std::string & command, std::queue<std::string> & MsgQueue)
232 {
233     (void) command;
234     std::stringstream stream(string);
235     std::istream_iterator<std::string> begin(stream);
236     std::istream_iterator<std::string> end;
237     std::string cmd;
238     bool endOfStream = false;
239
240     int c = 0;
241
242     while(!endOfStream)
243     {
244        cmd = *begin;
245        MsgQueue.push(cmd);
246        begin++;
247
248        if(begin == end )
249        {
250           endOfStream = true;
251        }
252        c++;
253     }
254
255
256     /*
257     command = *begin++;
258     msg = std::vector<std::string>(begin, end);
259     */
260 }
261
262