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/FileNameList.h"
18 #include "support/lstrings.h"
19 #include "support/unicode.h"
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>
62 using namespace lyx::support;
64 using ::boost::scoped_ptr;
70 string itoa(unsigned int i)
73 sprintf(buf, "%d", i);
78 /// Returns the absolute pathnames of all lyx local sockets in
79 /// file system encoding.
80 /// Parts stolen from lyx::support::DirList().
81 FileNameList lyxSockets(string const & dir, string const & pid)
85 FileName dirpath(dir + "/");
87 if (!dirpath.exists() || !dirpath.isDirectory()) {
88 lyxerr << dir << " does not exist or is not a directory."
93 FileNameList dirs = dirpath.dirList("");
94 FileNameList::const_iterator it = dirs.begin();
95 FileNameList::const_iterator end = dirs.end();
97 for (; it != end; ++it) {
98 if (!it->isDirectory())
100 string const tmpdir = it->absFilename();
101 if (!contains(tmpdir, "lyx_tmpdir" + pid))
104 FileName lyxsocket(tmpdir + "/lyxsocket");
105 if (lyxsocket.exists())
106 dirlist.push_back(lyxsocket);
113 namespace socktools {
116 /// Connect to the socket \p name.
117 int connect(FileName const & name)
119 int fd; // File descriptor for the socket
120 sockaddr_un addr; // Structure that hold the socket address
122 string const encoded = name.toFilesystemEncoding();
123 // char sun_path[108]
124 string::size_type len = encoded.size();
126 cerr << "lyxclient: Socket address '" << name
127 << "' too long." << endl;
130 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
131 addr.sun_family = AF_UNIX;
132 encoded.copy(addr.sun_path, 107);
133 addr.sun_path[len] = '\0';
135 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
136 cerr << "lyxclient: Could not create socket descriptor: "
137 << strerror(errno) << endl;
141 reinterpret_cast<struct sockaddr *>(&addr),
142 sizeof(addr)) == -1) {
143 cerr << "lyxclient: Could not connect to socket " << name.absFilename()
144 << ": " << strerror(errno) << endl;
148 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
149 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
150 << strerror(errno) << endl;
158 } // namespace socktools
159 } // namespace support
163 /////////////////////////////////////////////////////////////////////
167 /////////////////////////////////////////////////////////////////////
189 void IOWatch::clear()
195 void IOWatch::addfd(int fd)
201 bool IOWatch::wait(double timeout)
204 to.tv_sec = static_cast<long int>(timeout);
205 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
207 return select(FD_SETSIZE, &act,
208 (fd_set *)0, (fd_set *)0, &to);
215 return select(FD_SETSIZE, &act,
216 (fd_set *)0, (fd_set *)0, (timeval *)0);
220 bool IOWatch::isset(int fd)
222 return FD_ISSET(fd, &act);
227 /////////////////////////////////////////////////////////////////////
231 /////////////////////////////////////////////////////////////////////
233 // Modified LyXDataSocket class for use with the client
234 class LyXDataSocket {
236 LyXDataSocket(FileName const &);
238 // File descriptor of the connection
241 bool connected() const;
242 // Line buffered input from the socket
243 bool readln(string &);
244 // Write the string + '\n' to the socket
245 void writeln(string const &);
247 // File descriptor for the data socket
249 // True if the connection is up
251 // buffer for input data
256 LyXDataSocket::LyXDataSocket(FileName const & address)
258 if ((fd_ = socktools::connect(address)) == -1) {
266 LyXDataSocket::~LyXDataSocket()
272 int LyXDataSocket::fd() const
278 bool LyXDataSocket::connected() const
284 // Returns true if there was a complete line to input
285 // A line is of the form <key>:<value>
286 // A line not of this form will not be passed
287 // The line read is splitted and stored in 'key' and 'value'
288 bool LyXDataSocket::readln(string & line)
290 int const charbuf_size = 100;
291 char charbuf[charbuf_size]; // buffer for the ::read() system call
293 string::size_type pos;
295 // read and store characters in buffer
296 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
297 charbuf[count] = '\0'; // turn it into a c string
301 // Error conditions. The buffer must still be
302 // processed for lines read
303 if (count == 0) { // EOF -- connection closed
305 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
306 cerr << "lyxclient: IO error." << endl;
310 // Cut a line from buffer
311 if ((pos = buffer.find('\n')) == string::npos)
312 return false; // No complete line stored
313 line = buffer.substr(0, pos);
314 buffer = buffer.substr(pos + 1);
319 // Write a line of the form <key>:<value> to the socket
320 void LyXDataSocket::writeln(string const & line)
322 string linen(line + '\n');
323 int size = linen.size();
324 int written = ::write(fd_, linen.c_str(), size);
325 if (written < size) { // Allways mean end of connection.
326 if ((written == -1) && (errno == EPIPE)) {
327 // The program will also receive a SIGPIPE
328 // that must be catched
329 cerr << "lyxclient: connection closed while writing."
332 // Anything else, including errno == EAGAIN, must be
333 // considered IO error. EAGAIN should never happen
334 // when line is small
335 cerr << "lyxclient: IO error: " << strerror(errno);
342 /////////////////////////////////////////////////////////////////////
346 /////////////////////////////////////////////////////////////////////
348 class CmdLineParser {
350 typedef int (*optfunc)(vector<docstring> const & args);
351 map<string, optfunc> helper;
352 map<string, bool> isset;
353 bool parse(int, char * []);
354 vector<char *> nonopt;
358 bool CmdLineParser::parse(int argc, char * argv[])
362 vector<docstring> args;
363 if (helper[argv[opt]]) {
364 isset[argv[opt]] = true;
366 while ((arg < argc) && (!helper[argv[arg]])) {
367 args.push_back(from_local8bit(argv[arg]));
370 int taken = helper[argv[opt]](args);
375 if (argv[opt][0] == '-') {
376 if ((argv[opt][1] == '-')
377 && (argv[opt][2]== '\0')) {
380 nonopt.push_back(argv[opt]);
385 cerr << "lyxclient: unknown option "
386 << argv[opt] << endl;
390 nonopt.push_back(argv[opt]);
396 // ~Class CmdLineParser -------------------------------------------------------
405 "Usage: lyxclient [options]\n"
407 " -a address set address of the lyx socket\n"
408 " -t directory set system temporary directory (for detecting sockets)\n"
409 " -p pid select a running lyx by pidi\n"
410 " -c command send a single command and quit (LYXCMD prefix needed)\n"
411 " -g file row send a command to go to file and row\n"
412 " -n name set client name\n"
413 " -h name display this help end exit\n"
414 "If -a is not used, lyxclient will use the arguments of -t and -p to look for\n"
415 "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set,\n"
416 "lyxclient will connect only to a lyx with the specified pid. Options -c and -g\n"
417 "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient\n"
418 "will read commands from standard input and disconnect when command read is BYE:"
423 int h(vector<docstring> const &)
430 docstring clientName =
431 from_ascii(itoa(::getppid()) + ">" + itoa(::getpid()));
433 int n(vector<docstring> const & arg)
435 if (arg.size() < 1) {
436 cerr << "lyxclient: The option -n requires 1 argument."
445 docstring singleCommand;
448 int c(vector<docstring> const & arg)
450 if (arg.size() < 1) {
451 cerr << "lyxclient: The option -c requires 1 argument."
455 singleCommand = arg[0];
460 int g(vector<docstring> const & arg)
462 if (arg.size() < 2) {
463 cerr << "lyxclient: The option -g requires 2 arguments."
467 singleCommand = "LYXCMD:server-goto-file-row "
474 // empty if LYXSOCKET is not set in the environment
475 docstring serverAddress;
478 int a(vector<docstring> const & arg)
480 if (arg.size() < 1) {
481 cerr << "lyxclient: The option -a requires 1 argument."
485 // -a supercedes LYXSOCKET environment variable
486 serverAddress = arg[0];
491 docstring mainTmp(from_ascii("/tmp"));
494 int t(vector<docstring> const & arg)
496 if (arg.size() < 1) {
497 cerr << "lyxclient: The option -t requires 1 argument."
506 string serverPid; // Init to empty string
509 int p(vector<docstring> const & arg)
511 if (arg.size() < 1) {
512 cerr << "lyxclient: The option -p requires 1 argument."
516 serverPid = to_ascii(arg[0]);
521 } // namespace cmdline
525 int main(int argc, char * argv[])
528 lyxerr.setStream(cerr);
530 char const * const lyxsocket = getenv("LYXSOCKET");
532 cmdline::serverAddress = from_local8bit(lyxsocket);
535 args.helper["-h"] = cmdline::h;
536 args.helper["-c"] = cmdline::c;
537 args.helper["-g"] = cmdline::g;
538 args.helper["-n"] = cmdline::n;
539 args.helper["-a"] = cmdline::a;
540 args.helper["-t"] = cmdline::t;
541 args.helper["-p"] = cmdline::p;
543 // Command line failure conditions:
544 if ((!args.parse(argc, argv))
545 || (args.isset["-c"] && args.isset["-g"])
546 || (args.isset["-a"] && args.isset["-p"])) {
551 scoped_ptr<LyXDataSocket> server;
553 if (!cmdline::serverAddress.empty()) {
554 server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress))));
555 if (!server->connected()) {
556 cerr << "lyxclient: " << "Could not connect to "
557 << to_utf8(cmdline::serverAddress) << endl;
561 // We have to look for an address.
562 // serverPid can be empty.
563 FileNameList addrs = lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid);
564 FileNameList::const_iterator addr = addrs.begin();
565 FileNameList::const_iterator end = addrs.end();
566 for (; addr != end; ++addr) {
567 // Caution: addr->string() is in filesystem encoding
568 server.reset(new LyXDataSocket(*addr));
569 if (server->connected())
571 lyxerr << "lyxclient: " << "Could not connect to "
572 << addr->absFilename() << endl;
575 lyxerr << "lyxclient: No suitable server found."
579 cerr << "lyxclient: " << "Connected to " << addr->absFilename() << endl;
582 int const serverfd = server->fd();
585 iowatch.addfd(serverfd);
587 // Used to read from server
591 server->writeln("HELLO:" + to_utf8(cmdline::clientName));
592 // wait at most 2 seconds until server responds
594 if (iowatch.isset(serverfd) && server->readln(answer)) {
595 if (prefixIs(answer, "BYE:")) {
596 cerr << "lyxclient: Server disconnected." << endl;
597 cout << answer << endl;
601 cerr << "lyxclient: No answer from server." << endl;
605 if (args.isset["-g"] || args.isset["-c"]) {
606 server->writeln(to_utf8(cmdline::singleCommand));
608 if (iowatch.isset(serverfd) && server->readln(answer)) {
610 if (prefixIs(answer, "ERROR:"))
614 cerr << "lyxclient: No answer from server." << endl;
619 // Take commands from stdin
620 iowatch.addfd(0); // stdin
621 bool saidbye = false;
622 while ((!saidbye) && server->connected()) {
624 if (iowatch.isset(0)) {
626 getline(cin, command);
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 << ' '