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