3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author João Luis M. Assirati
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
16 #include "support/unicode.h"
17 #include "support/lstrings.h"
19 #include <boost/filesystem/operations.hpp>
20 #include <boost/lexical_cast.hpp>
21 #include <boost/scoped_ptr.hpp>
23 // getpid(), getppid()
24 #ifdef HAVE_SYS_TYPES_H
25 # include <sys/types.h>
32 #ifdef HAVE_SYS_TIME_H
33 # include <sys/time.h>
37 #ifdef HAVE_SYS_SELECT_H
38 # include <sys/select.h>
41 // socket(), connect()
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
60 using lyx::support::prefixIs;
62 using boost::scoped_ptr;
63 namespace fs = boost::filesystem;
75 string itoa(unsigned int i)
77 return boost::lexical_cast<string>(i);
81 /// Returns the absolute pathnames of all lyx local sockets in
82 /// file system encoding.
83 /// Parts stolen from lyx::support::DirList().
84 vector<fs::path> lyxSockets(string const & dir, string const & pid)
86 vector<fs::path> dirlist;
88 fs::path dirpath(dir);
90 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
91 lyxerr << dir << " does not exist or is not a directory."
96 fs::directory_iterator beg((fs::path(dir)));
97 fs::directory_iterator end;
99 for (; beg != end; ++beg) {
100 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
101 fs::path lyxsocket = beg->path() / "lyxsocket";
102 if (fs::exists(lyxsocket)) {
103 dirlist.push_back(lyxsocket);
112 namespace socktools {
115 /// Connect to the socket \p name.
116 /// Caution: \p name is in filesystem encoding
117 int connect(string const & name)
119 int fd; // File descriptor for the socket
120 sockaddr_un addr; // Structure that hold the socket address
122 // char sun_path[108]
123 string::size_type len = name.size();
125 cerr << "lyxclient: Socket address '" << name
126 << "' too long." << endl;
129 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
130 addr.sun_family = AF_UNIX;
131 name.copy(addr.sun_path, 107);
132 addr.sun_path[len] = '\0';
134 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
135 cerr << "lyxclient: Could not create socket descriptor: "
136 << strerror(errno) << endl;
140 reinterpret_cast<struct sockaddr *>(&addr),
141 sizeof(addr)) == -1) {
142 cerr << "lyxclient: Could not connect to socket " << name
143 << ": " << strerror(errno) << endl;
147 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
148 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
149 << strerror(errno) << endl;
157 } // namespace socktools
158 } // namespace support
162 // Class IOWatch ------------------------------------------------------------
183 void IOWatch::clear()
189 void IOWatch::addfd(int fd)
195 bool IOWatch::wait(double timeout)
198 to.tv_sec = static_cast<long int>(timeout);
199 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
201 return select(FD_SETSIZE, &act,
202 (fd_set *)0, (fd_set *)0, &to);
209 return select(FD_SETSIZE, &act,
210 (fd_set *)0, (fd_set *)0, (timeval *)0);
214 bool IOWatch::isset(int fd) {
215 return FD_ISSET(fd, &act);
217 // ~Class IOWatch ------------------------------------------------------------
220 // Class LyXDataSocket -------------------------------------------------------
221 // Modified LyXDataSocket class for use with the client
222 class LyXDataSocket {
224 LyXDataSocket(string const &);
226 // File descriptor of the connection
229 bool connected() const;
230 // Line buffered input from the socket
231 bool readln(string &);
232 // Write the string + '\n' to the socket
233 void writeln(string const &);
235 // File descriptor for the data socket
237 // True if the connection is up
239 // buffer for input data
244 LyXDataSocket::LyXDataSocket(string const & address)
246 if ((fd_ = support::socktools::connect(address)) == -1) {
254 LyXDataSocket::~LyXDataSocket()
260 int LyXDataSocket::fd() const
266 bool LyXDataSocket::connected() const
272 // Returns true if there was a complete line to input
273 // A line is of the form <key>:<value>
274 // A line not of this form will not be passed
275 // The line read is splitted and stored in 'key' and 'value'
276 bool LyXDataSocket::readln(string & line)
278 int const charbuf_size = 100;
279 char charbuf[charbuf_size]; // buffer for the ::read() system call
281 string::size_type pos;
283 // read and store characters in buffer
284 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
285 charbuf[count] = '\0'; // turn it into a c string
289 // Error conditions. The buffer must still be
290 // processed for lines read
291 if (count == 0) { // EOF -- connection closed
293 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
294 cerr << "lyxclient: IO error." << endl;
298 // Cut a line from buffer
299 if ((pos = buffer.find('\n')) == string::npos)
300 return false; // No complete line stored
301 line = buffer.substr(0, pos);
302 buffer = buffer.substr(pos + 1);
307 // Write a line of the form <key>:<value> to the socket
308 void LyXDataSocket::writeln(string const & line)
310 string linen(line + '\n');
311 int size = linen.size();
312 int written = ::write(fd_, linen.c_str(), size);
313 if (written < size) { // Allways mean end of connection.
314 if ((written == -1) && (errno == EPIPE)) {
315 // The program will also receive a SIGPIPE
316 // that must be catched
317 cerr << "lyxclient: connection closed while writing."
320 // Anything else, including errno == EAGAIN, must be
321 // considered IO error. EAGAIN should never happen
322 // when line is small
323 cerr << "lyxclient: IO error: " << strerror(errno);
328 // ~Class LyXDataSocket -------------------------------------------------------
331 // Class CmdLineParser -------------------------------------------------------
332 class CmdLineParser {
334 typedef int (*optfunc)(vector<docstring> const & args);
335 std::map<string, optfunc> helper;
336 std::map<string, bool> isset;
337 bool parse(int, char * []);
338 vector<char *> nonopt;
342 bool CmdLineParser::parse(int argc, char * argv[])
346 vector<docstring> args;
347 if (helper[argv[opt]]) {
348 isset[argv[opt]] = true;
350 while ((arg < argc) && (!helper[argv[arg]])) {
351 args.push_back(from_local8bit(argv[arg]));
354 int taken = helper[argv[opt]](args);
359 if (argv[opt][0] == '-') {
360 if ((argv[opt][1] == '-')
361 && (argv[opt][2]== '\0')) {
364 nonopt.push_back(argv[opt]);
369 cerr << "lyxclient: unknown option "
370 << argv[opt] << endl;
374 nonopt.push_back(argv[opt]);
380 // ~Class CmdLineParser -------------------------------------------------------
388 cerr << "Usage: lyxclient [options]" << endl
389 << "Options are:" << endl
390 << " -a address set address of the lyx socket" << endl
391 << " -t directory set system temporary directory" << endl
392 << " -p pid select a running lyx by pid" << endl
393 << " -c command send a single command and quit" << endl
394 << " -g file row send a command to go to file and row" << endl
395 << " -n name set client name" << endl
396 << " -h name display this help end exit" << endl
397 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
398 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
399 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
400 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
401 << "will read commands from standard input and disconnect when command read is BYE:"
406 int h(vector<docstring> const &)
413 docstring clientName(from_ascii(support::itoa(::getppid()) + ">" + support::itoa(::getpid())));
415 int n(vector<docstring> const & arg)
417 if (arg.size() < 1) {
418 cerr << "lyxclient: The option -n requires 1 argument."
427 docstring singleCommand;
430 int c(vector<docstring> const & arg)
432 if (arg.size() < 1) {
433 cerr << "lyxclient: The option -c requires 1 argument."
437 singleCommand = arg[0];
442 int g(vector<docstring> const & arg)
444 if (arg.size() < 2) {
445 cerr << "lyxclient: The option -g requires 2 arguments."
449 singleCommand = "LYXCMD:server-goto-file-row "
456 // empty if LYXSOCKET is not set in the environment
457 docstring serverAddress;
460 int a(vector<docstring> const & arg)
462 if (arg.size() < 1) {
463 cerr << "lyxclient: The option -a requires 1 argument."
467 // -a supercedes LYXSOCKET environment variable
468 serverAddress = arg[0];
473 docstring mainTmp(from_ascii("/tmp"));
476 int t(vector<docstring> const & arg)
478 if (arg.size() < 1) {
479 cerr << "lyxclient: The option -t requires 1 argument."
488 string serverPid; // Init to empty string
491 int p(vector<docstring> const & arg)
493 if (arg.size() < 1) {
494 cerr << "lyxclient: The option -p requires 1 argument."
498 serverPid = to_ascii(arg[0]);
503 } // namespace cmdline
508 int main(int argc, char * argv[])
511 lyxerr.rdbuf(cerr.rdbuf());
513 char const * const lyxsocket = getenv("LYXSOCKET");
515 cmdline::serverAddress = from_local8bit(lyxsocket);
518 args.helper["-h"] = cmdline::h;
519 args.helper["-c"] = cmdline::c;
520 args.helper["-g"] = cmdline::g;
521 args.helper["-n"] = cmdline::n;
522 args.helper["-a"] = cmdline::a;
523 args.helper["-t"] = cmdline::t;
524 args.helper["-p"] = cmdline::p;
526 // Command line failure conditions:
527 if ((!args.parse(argc, argv))
528 || (args.isset["-c"] && args.isset["-g"])
529 || (args.isset["-a"] && args.isset["-p"])) {
534 scoped_ptr<LyXDataSocket> server;
536 if (!cmdline::serverAddress.empty()) {
537 server.reset(new LyXDataSocket(to_utf8(cmdline::serverAddress)));
538 if (!server->connected()) {
539 cerr << "lyxclient: " << "Could not connect to "
540 << to_utf8(cmdline::serverAddress) << endl;
544 // We have to look for an address.
545 // serverPid can be empty.
546 vector<fs::path> addrs = support::lyxSockets(to_utf8(cmdline::mainTmp), cmdline::serverPid);
547 vector<fs::path>::const_iterator addr = addrs.begin();
548 vector<fs::path>::const_iterator end = addrs.end();
549 for (; addr != end; ++addr) {
550 // Caution: addr->string() is in filesystem encoding
551 server.reset(new LyXDataSocket(addr->string()));
552 if (server->connected())
554 lyxerr << "lyxclient: " << "Could not connect to "
555 << addr->string() << endl;
558 lyxerr << "lyxclient: No suitable server found."
562 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
565 int const serverfd = server->fd();
568 iowatch.addfd(serverfd);
570 // Used to read from server
574 server->writeln("HELLO:" + to_utf8(cmdline::clientName));
575 // wait at most 2 seconds until server responds
577 if (iowatch.isset(serverfd) && server->readln(answer)) {
578 if (prefixIs(answer, "BYE:")) {
579 cerr << "lyxclient: Server disconnected." << endl;
580 cout << answer << endl;
584 cerr << "lyxclient: No answer from server." << endl;
588 if (args.isset["-g"] || args.isset["-c"]) {
589 server->writeln(to_utf8(cmdline::singleCommand));
591 if (iowatch.isset(serverfd) && server->readln(answer)) {
593 if (prefixIs(answer, "ERROR:"))
597 cerr << "lyxclient: No answer from server." << endl;
602 // Take commands from stdin
603 iowatch.addfd(0); // stdin
604 bool saidbye = false;
605 while ((!saidbye) && server->connected()) {
607 if (iowatch.isset(0)) {
610 if (command == "BYE:") {
611 server->writeln("BYE:");
614 server->writeln("LYXCMD:" + command);
617 if (iowatch.isset(serverfd)) {
618 while(server->readln(answer))
619 cout << answer << endl;
629 void assertion_failed(char const* a, char const* b, char const* c, long d)
631 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '