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.
15 #include "support/debug.h"
16 #include "support/FileName.h"
17 #include "support/unicode.h"
18 #include "support/lstrings.h"
20 #include <boost/filesystem/operations.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 support::FileName;
61 using support::prefixIs;
63 using ::boost::scoped_ptr;
64 namespace fs = ::boost::filesystem;
76 string itoa(unsigned int i)
79 sprintf(buf, "%d", i);
84 /// Returns the absolute pathnames of all lyx local sockets in
85 /// file system encoding.
86 /// Parts stolen from lyx::support::DirList().
87 vector<fs::path> lyxSockets(string const & dir, string const & pid)
89 vector<fs::path> dirlist;
91 fs::path dirpath(dir);
93 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
94 lyxerr << dir << " does not exist or is not a directory."
99 fs::directory_iterator beg((fs::path(dir)));
100 fs::directory_iterator end;
102 for (; beg != end; ++beg) {
103 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
104 fs::path lyxsocket = beg->path() / "lyxsocket";
105 if (fs::exists(lyxsocket)) {
106 dirlist.push_back(lyxsocket);
115 namespace socktools {
118 /// Connect to the socket \p name.
119 int connect(FileName const & name)
121 int fd; // File descriptor for the socket
122 sockaddr_un addr; // Structure that hold the socket address
124 string const encoded = name.toFilesystemEncoding();
125 // char sun_path[108]
126 string::size_type len = encoded.size();
128 cerr << "lyxclient: Socket address '" << name
129 << "' too long." << endl;
132 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
133 addr.sun_family = AF_UNIX;
134 encoded.copy(addr.sun_path, 107);
135 addr.sun_path[len] = '\0';
137 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
138 cerr << "lyxclient: Could not create socket descriptor: "
139 << strerror(errno) << endl;
143 reinterpret_cast<struct sockaddr *>(&addr),
144 sizeof(addr)) == -1) {
145 cerr << "lyxclient: Could not connect to socket " << name.absFilename()
146 << ": " << strerror(errno) << endl;
150 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
151 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
152 << strerror(errno) << endl;
160 } // namespace socktools
161 } // namespace support
165 /////////////////////////////////////////////////////////////////////
169 /////////////////////////////////////////////////////////////////////
191 void IOWatch::clear()
197 void IOWatch::addfd(int fd)
203 bool IOWatch::wait(double timeout)
206 to.tv_sec = static_cast<long int>(timeout);
207 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
209 return select(FD_SETSIZE, &act,
210 (fd_set *)0, (fd_set *)0, &to);
217 return select(FD_SETSIZE, &act,
218 (fd_set *)0, (fd_set *)0, (timeval *)0);
222 bool IOWatch::isset(int fd)
224 return FD_ISSET(fd, &act);
229 /////////////////////////////////////////////////////////////////////
233 /////////////////////////////////////////////////////////////////////
235 // Modified LyXDataSocket class for use with the client
236 class LyXDataSocket {
238 LyXDataSocket(FileName const &);
240 // File descriptor of the connection
243 bool connected() const;
244 // Line buffered input from the socket
245 bool readln(string &);
246 // Write the string + '\n' to the socket
247 void writeln(string const &);
249 // File descriptor for the data socket
251 // True if the connection is up
253 // buffer for input data
258 LyXDataSocket::LyXDataSocket(FileName const & address)
260 if ((fd_ = support::socktools::connect(address)) == -1) {
268 LyXDataSocket::~LyXDataSocket()
274 int LyXDataSocket::fd() const
280 bool LyXDataSocket::connected() const
286 // Returns true if there was a complete line to input
287 // A line is of the form <key>:<value>
288 // A line not of this form will not be passed
289 // The line read is splitted and stored in 'key' and 'value'
290 bool LyXDataSocket::readln(string & line)
292 int const charbuf_size = 100;
293 char charbuf[charbuf_size]; // buffer for the ::read() system call
295 string::size_type pos;
297 // read and store characters in buffer
298 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
299 charbuf[count] = '\0'; // turn it into a c string
303 // Error conditions. The buffer must still be
304 // processed for lines read
305 if (count == 0) { // EOF -- connection closed
307 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
308 cerr << "lyxclient: IO error." << endl;
312 // Cut a line from buffer
313 if ((pos = buffer.find('\n')) == string::npos)
314 return false; // No complete line stored
315 line = buffer.substr(0, pos);
316 buffer = buffer.substr(pos + 1);
321 // Write a line of the form <key>:<value> to the socket
322 void LyXDataSocket::writeln(string const & line)
324 string linen(line + '\n');
325 int size = linen.size();
326 int written = ::write(fd_, linen.c_str(), size);
327 if (written < size) { // Allways mean end of connection.
328 if ((written == -1) && (errno == EPIPE)) {
329 // The program will also receive a SIGPIPE
330 // that must be catched
331 cerr << "lyxclient: connection closed while writing."
334 // Anything else, including errno == EAGAIN, must be
335 // considered IO error. EAGAIN should never happen
336 // when line is small
337 cerr << "lyxclient: IO error: " << strerror(errno);
344 /////////////////////////////////////////////////////////////////////
348 /////////////////////////////////////////////////////////////////////
350 class CmdLineParser {
352 typedef int (*optfunc)(vector<docstring> const & args);
353 std::map<string, optfunc> helper;
354 std::map<string, bool> isset;
355 bool parse(int, char * []);
356 vector<char *> nonopt;
360 bool CmdLineParser::parse(int argc, char * argv[])
364 vector<docstring> args;
365 if (helper[argv[opt]]) {
366 isset[argv[opt]] = true;
368 while ((arg < argc) && (!helper[argv[arg]])) {
369 args.push_back(from_local8bit(argv[arg]));
372 int taken = helper[argv[opt]](args);
377 if (argv[opt][0] == '-') {
378 if ((argv[opt][1] == '-')
379 && (argv[opt][2]== '\0')) {
382 nonopt.push_back(argv[opt]);
387 cerr << "lyxclient: unknown option "
388 << argv[opt] << endl;
392 nonopt.push_back(argv[opt]);
398 // ~Class CmdLineParser -------------------------------------------------------
407 "Usage: lyxclient [options]\n"
409 " -a address set address of the lyx socket\n"
410 " -t directory set system temporary directory\n"
411 " -p pid select a running lyx by pidi\n"
412 " -c command send a single command and quit\n"
413 " -g file row send a command to go to file and row\n"
414 " -n name set client name\n"
415 " -h name display this help end exit\n"
416 "If -a is not used, lyxclient will use the arguments of -t and -p to look for\n"
417 "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set,\n"
418 "lyxclient will connect only to a lyx with the specified pid. Options -c and -g\n"
419 "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient\n"
420 "will read commands from standard input and disconnect when command read is BYE:"
425 int h(vector<docstring> const &)
432 docstring clientName =
433 from_ascii(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
435 int n(vector<docstring> const & arg)
437 if (arg.size() < 1) {
438 cerr << "lyxclient: The option -n requires 1 argument."
447 docstring singleCommand;
450 int c(vector<docstring> const & arg)
452 if (arg.size() < 1) {
453 cerr << "lyxclient: The option -c requires 1 argument."
457 singleCommand = arg[0];
462 int g(vector<docstring> const & arg)
464 if (arg.size() < 2) {
465 cerr << "lyxclient: The option -g requires 2 arguments."
469 singleCommand = "LYXCMD:server-goto-file-row "
476 // empty if LYXSOCKET is not set in the environment
477 docstring serverAddress;
480 int a(vector<docstring> const & arg)
482 if (arg.size() < 1) {
483 cerr << "lyxclient: The option -a requires 1 argument."
487 // -a supercedes LYXSOCKET environment variable
488 serverAddress = arg[0];
493 docstring mainTmp(from_ascii("/tmp"));
496 int t(vector<docstring> const & arg)
498 if (arg.size() < 1) {
499 cerr << "lyxclient: The option -t requires 1 argument."
508 string serverPid; // Init to empty string
511 int p(vector<docstring> const & arg)
513 if (arg.size() < 1) {
514 cerr << "lyxclient: The option -p requires 1 argument."
518 serverPid = to_ascii(arg[0]);
523 } // namespace cmdline
527 int main(int argc, char * argv[])
530 lyxerr.setStream(cerr);
532 char const * const lyxsocket = getenv("LYXSOCKET");
534 cmdline::serverAddress = from_local8bit(lyxsocket);
537 args.helper["-h"] = cmdline::h;
538 args.helper["-c"] = cmdline::c;
539 args.helper["-g"] = cmdline::g;
540 args.helper["-n"] = cmdline::n;
541 args.helper["-a"] = cmdline::a;
542 args.helper["-t"] = cmdline::t;
543 args.helper["-p"] = cmdline::p;
545 // Command line failure conditions:
546 if ((!args.parse(argc, argv))
547 || (args.isset["-c"] && args.isset["-g"])
548 || (args.isset["-a"] && args.isset["-p"])) {
553 scoped_ptr<LyXDataSocket> server;
555 if (!cmdline::serverAddress.empty()) {
556 server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress))));
557 if (!server->connected()) {
558 cerr << "lyxclient: " << "Could not connect to "
559 << to_utf8(cmdline::serverAddress) << endl;
563 // We have to look for an address.
564 // serverPid can be empty.
565 vector<fs::path> addrs = support::lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid);
566 vector<fs::path>::const_iterator addr = addrs.begin();
567 vector<fs::path>::const_iterator end = addrs.end();
568 for (; addr != end; ++addr) {
569 // Caution: addr->string() is in filesystem encoding
570 server.reset(new LyXDataSocket(FileName(to_utf8(from_filesystem8bit(addr->string())))));
571 if (server->connected())
573 lyxerr << "lyxclient: " << "Could not connect to "
574 << addr->string() << endl;
577 lyxerr << "lyxclient: No suitable server found."
581 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
584 int const serverfd = server->fd();
587 iowatch.addfd(serverfd);
589 // Used to read from server
593 server->writeln("HELLO:" + to_utf8(cmdline::clientName));
594 // wait at most 2 seconds until server responds
596 if (iowatch.isset(serverfd) && server->readln(answer)) {
597 if (prefixIs(answer, "BYE:")) {
598 cerr << "lyxclient: Server disconnected." << endl;
599 cout << answer << endl;
603 cerr << "lyxclient: No answer from server." << endl;
607 if (args.isset["-g"] || args.isset["-c"]) {
608 server->writeln(to_utf8(cmdline::singleCommand));
610 if (iowatch.isset(serverfd) && server->readln(answer)) {
612 if (prefixIs(answer, "ERROR:"))
616 cerr << "lyxclient: No answer from server." << endl;
621 // Take commands from stdin
622 iowatch.addfd(0); // stdin
623 bool saidbye = false;
624 while ((!saidbye) && server->connected()) {
626 if (iowatch.isset(0)) {
629 if (command == "BYE:") {
630 server->writeln("BYE:");
633 server->writeln("LYXCMD:" + command);
636 if (iowatch.isset(serverfd)) {
637 while(server->readln(answer))
638 cout << answer << endl;
648 void assertion_failed(char const* a, char const* b, char const* c, long d)
650 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '