]> git.lyx.org Git - lyx.git/blob - src/ServerSocket.cpp
getting rid of superfluous lyx::support:: statements.
[lyx.git] / src / ServerSocket.cpp
1 /**
2  * \file ServerSocket.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author Angus Leeming
9  * \author John Levon
10  * \author João Luis M. Assirati
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "ServerSocket.h"
18
19 #include "support/debug.h"
20 #include "FuncRequest.h"
21 #include "LyXAction.h"
22 #include "LyXFunc.h"
23
24 #include "frontends/Application.h"
25
26 #include "support/environment.h"
27 #include "support/FileName.h"
28 #include "support/lyxlib.h"
29 #include "support/socktools.h"
30
31 #include <boost/bind.hpp>
32
33 #include <cerrno>
34 #include <ostream>
35
36 #if defined (_WIN32)
37 # include <io.h>
38 #endif
39
40 using namespace std;
41 using namespace lyx::support;
42
43 using boost::shared_ptr;
44
45 namespace lyx {
46
47 // Address is the unix address for the socket.
48 // MAX_CLIENTS is the maximum number of clients
49 // that can connect at the same time.
50 ServerSocket::ServerSocket(LyXFunc * f, FileName const & addr)
51         : func(f),
52           fd_(socktools::listen(addr, 3)),
53           address_(addr)
54 {
55         if (fd_ == -1) {
56                 lyxerr << "lyx: Disabling LyX socket." << endl;
57                 return;
58         }
59
60         // These env vars are used by DVI inverse search
61         // Needed by xdvi
62         setEnv("XEDITOR", "lyxclient -g %f %l");
63         // Needed by lyxclient
64         setEnv("LYXSOCKET", address_.absFilename());
65
66         theApp()->registerSocketCallback(
67                 fd_,
68                 boost::bind(&ServerSocket::serverCallback, this)
69                 );
70
71         LYXERR(Debug::LYXSERVER, "lyx: New server socket "
72                                  << fd_ << ' ' << address_.absFilename());
73 }
74
75
76 // Close the socket and remove the address of the filesystem.
77 ServerSocket::~ServerSocket()
78 {
79         if (fd_ != -1) {
80                 BOOST_ASSERT (theApp());
81                 theApp()->unregisterSocketCallback(fd_);
82                 if (::close(fd_) != 0)
83                         lyxerr << "lyx: Server socket " << fd_
84                                << " IO error on closing: " << strerror(errno);
85         }
86         address_.removeFile();
87         LYXERR(Debug::LYXSERVER, "lyx: Server socket quitting");
88 }
89
90
91 string const ServerSocket::address() const
92 {
93         return address_.absFilename();
94 }
95
96
97 // Creates a new LyXDataSocket and checks to see if the connection
98 // is OK and if the number of clients does not exceed MAX_CLIENTS
99 void ServerSocket::serverCallback()
100 {
101         int const client_fd = socktools::accept(fd_);
102
103         if (fd_ == -1) {
104                 LYXERR(Debug::LYXSERVER, "lyx: Failed to accept new client");
105                 return;
106         }
107
108         if (clients.size() >= MAX_CLIENTS) {
109                 writeln("BYE:Too many clients connected");
110                 return;
111         }
112
113         // Register the new client.
114         clients[client_fd] =
115                 shared_ptr<LyXDataSocket>(new LyXDataSocket(client_fd));
116         theApp()->registerSocketCallback(
117                 client_fd,
118                 boost::bind(&ServerSocket::dataCallback,
119                             this, client_fd)
120                 );
121 }
122
123
124 // Reads and processes input from client and check
125 // if the connection has been closed
126 void ServerSocket::dataCallback(int fd)
127 {
128         shared_ptr<LyXDataSocket> client = clients[fd];
129
130         string line;
131         size_t pos;
132         bool saidbye = false;
133         while (!saidbye && client->readln(line)) {
134                 // The protocol must be programmed here
135                 // Split the key and the data
136                 if ((pos = line.find(':')) == string::npos) {
137                         client->writeln("ERROR:" + line + ":malformed message");
138                         continue;
139                 }
140
141                 string const key = line.substr(0, pos);
142                 if (key == "LYXCMD") {
143                         string const cmd = line.substr(pos + 1);
144                         func->dispatch(lyxaction.lookupFunc(cmd));
145                         string const rval = to_utf8(func->getMessage());
146                         if (func->errorStat()) {
147                                 client->writeln("ERROR:" + cmd + ':' + rval);
148                         } else {
149                                 client->writeln("INFO:" + cmd + ':' + rval);
150                         }
151                 } else if (key == "HELLO") {
152                         // no use for client name!
153                         client->writeln("HELLO:");
154                 } else if (key == "BYE") {
155                         saidbye = true;
156                 } else {
157                         client->writeln("ERROR:unknown key " + key);
158                 }
159         }
160
161         if (saidbye || !client->connected()) {
162                 clients.erase(fd);
163         }
164 }
165
166
167 void ServerSocket::writeln(string const & line)
168 {
169         string const linen = line + '\n';
170         int const size = linen.size();
171         int const written = ::write(fd_, linen.c_str(), size);
172         if (written < size) { // Always mean end of connection.
173                 if (written == -1 && errno == EPIPE) {
174                         // The program will also receive a SIGPIPE
175                         // that must be caught
176                         lyxerr << "lyx: Server socket " << fd_
177                                << " connection closed while writing." << endl;
178                 } else {
179                         // Anything else, including errno == EAGAIN, must be
180                         // considered IO error. EAGAIN should never happen
181                         // when line is small
182                         lyxerr << "lyx: Server socket " << fd_
183                              << " IO error: " << strerror(errno);
184                 }
185         }
186 }
187
188 // Debug
189 // void ServerSocket::dump() const
190 // {
191 //      lyxerr << "ServerSocket debug dump.\n"
192 //           << "fd = " << fd_ << ", address = " << address_.absFilename() << ".\n"
193 //           << "Clients: " << clients.size() << ".\n";
194 //      map<int, shared_ptr<LyXDataSocket> >::const_iterator client = clients.begin();
195 //      map<int, shared_ptr<LyXDataSocket> >::const_iterator end = clients.end();
196 //      for (; client != end; ++client)
197 //              lyxerr << "fd = " << client->first << '\n';
198 // }
199
200
201 LyXDataSocket::LyXDataSocket(int fd)
202         : fd_(fd), connected_(true)
203 {
204         LYXERR(Debug::LYXSERVER, "lyx: New data socket " << fd_);
205 }
206
207
208 LyXDataSocket::~LyXDataSocket()
209 {
210         if (::close(fd_) != 0)
211                 lyxerr << "lyx: Data socket " << fd_
212                        << " IO error on closing: " << strerror(errno);
213
214         theApp()->unregisterSocketCallback(fd_);
215         LYXERR(Debug::LYXSERVER, "lyx: Data socket " << fd_ << " quitting.");
216 }
217
218
219 bool LyXDataSocket::connected() const
220 {
221         return connected_;
222 }
223
224
225 // Returns true if there was a complete line to input
226 bool LyXDataSocket::readln(string & line)
227 {
228         int const charbuf_size = 100;
229         char charbuf[charbuf_size]; // buffer for the ::read() system call
230         int count;
231
232         // read and store characters in buffer
233         while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
234                 buffer_.append(charbuf, charbuf + count);
235         }
236
237         // Error conditions. The buffer must still be
238         // processed for lines read
239         if (count == 0) { // EOF -- connection closed
240                 LYXERR(Debug::LYXSERVER, "lyx: Data socket " << fd_
241                                          << ": connection closed.");
242                 connected_ = false;
243         } else if ((count == -1) && (errno != EAGAIN)) { // IO error
244                 lyxerr << "lyx: Data socket " << fd_
245                        << ": IO error." << endl;
246                 connected_ = false;
247         }
248
249         // Cut a line from buffer
250         size_t pos = buffer_.find('\n');
251         if (pos == string::npos) {
252                 LYXERR(Debug::LYXSERVER, "lyx: Data socket " << fd_
253                                          << ": line not completed.");
254                 return false; // No complete line stored
255         }
256         line = buffer_.substr(0, pos);
257         buffer_.erase(0, pos + 1);
258         return true;
259 }
260
261
262 // Write a line of the form <key>:<value> to the socket
263 void LyXDataSocket::writeln(string const & line)
264 {
265         string const linen = line + '\n';
266         int const size = linen.size();
267         int const written = ::write(fd_, linen.c_str(), size);
268         if (written < size) { // Always mean end of connection.
269                 if (written == -1 && errno == EPIPE) {
270                         // The program will also receive a SIGPIPE
271                         // that must be catched
272                         lyxerr << "lyx: Data socket " << fd_
273                                << " connection closed while writing." << endl;
274                 } else {
275                         // Anything else, including errno == EAGAIN, must be
276                         // considered IO error. EAGAIN should never happen
277                         // when line is small
278                         lyxerr << "lyx: Data socket " << fd_
279                              << " IO error: " << strerror(errno);
280                 }
281                 connected_ = false;
282         }
283 }
284
285
286 } // namespace lyx