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