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>
58 using namespace lyx::support;
60 using ::boost::scoped_ptr;
66 string itoa(unsigned int i)
69 sprintf(buf, "%d", i);
74 /// Returns the absolute pathnames of all lyx local sockets in
75 /// file system encoding.
76 /// Parts stolen from lyx::support::DirList().
77 FileNameList lyxSockets(string const & dir, string const & pid)
81 FileName dirpath(dir + "/");
83 if (!dirpath.exists() || !dirpath.isDirectory()) {
84 lyxerr << dir << " does not exist or is not a directory."
89 FileNameList dirs = dirpath.dirList("");
90 FileNameList::const_iterator it = dirs.begin();
91 FileNameList::const_iterator end = dirs.end();
93 for (; it != end; ++it) {
94 if (!it->isDirectory())
96 string const tmpdir = it->absFilename();
97 if (!contains(tmpdir, "lyx_tmpdir" + pid))
100 FileName lyxsocket(tmpdir + "/lyxsocket");
101 if (lyxsocket.exists())
102 dirlist.push_back(lyxsocket);
109 namespace socktools {
112 /// Connect to the socket \p name.
113 int connect(FileName const & name)
115 int fd; // File descriptor for the socket
116 sockaddr_un addr; // Structure that hold the socket address
118 string const encoded = name.toFilesystemEncoding();
119 // char sun_path[108]
120 string::size_type len = encoded.size();
122 cerr << "lyxclient: Socket address '" << name
123 << "' too long." << endl;
126 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
127 addr.sun_family = AF_UNIX;
128 encoded.copy(addr.sun_path, 107);
129 addr.sun_path[len] = '\0';
131 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
132 cerr << "lyxclient: Could not create socket descriptor: "
133 << strerror(errno) << endl;
137 reinterpret_cast<struct sockaddr *>(&addr),
138 sizeof(addr)) == -1) {
139 cerr << "lyxclient: Could not connect to socket " << name.absFilename()
140 << ": " << strerror(errno) << endl;
144 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
145 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
146 << strerror(errno) << endl;
154 } // namespace socktools
155 } // namespace support
159 /////////////////////////////////////////////////////////////////////
163 /////////////////////////////////////////////////////////////////////
185 void IOWatch::clear()
191 void IOWatch::addfd(int fd)
197 bool IOWatch::wait(double timeout)
200 to.tv_sec = static_cast<long int>(timeout);
201 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
203 return select(FD_SETSIZE, &act,
204 (fd_set *)0, (fd_set *)0, &to);
211 return select(FD_SETSIZE, &act,
212 (fd_set *)0, (fd_set *)0, (timeval *)0);
216 bool IOWatch::isset(int fd)
218 return FD_ISSET(fd, &act);
223 /////////////////////////////////////////////////////////////////////
227 /////////////////////////////////////////////////////////////////////
229 // Modified LyXDataSocket class for use with the client
230 class LyXDataSocket {
232 LyXDataSocket(FileName const &);
234 // File descriptor of the connection
237 bool connected() const;
238 // Line buffered input from the socket
239 bool readln(string &);
240 // Write the string + '\n' to the socket
241 void writeln(string const &);
243 // File descriptor for the data socket
245 // True if the connection is up
247 // buffer for input data
252 LyXDataSocket::LyXDataSocket(FileName const & address)
254 if ((fd_ = socktools::connect(address)) == -1) {
262 LyXDataSocket::~LyXDataSocket()
268 int LyXDataSocket::fd() const
274 bool LyXDataSocket::connected() const
280 // Returns true if there was a complete line to input
281 // A line is of the form <key>:<value>
282 // A line not of this form will not be passed
283 // The line read is splitted and stored in 'key' and 'value'
284 bool LyXDataSocket::readln(string & line)
286 int const charbuf_size = 100;
287 char charbuf[charbuf_size]; // buffer for the ::read() system call
289 string::size_type pos;
291 // read and store characters in buffer
292 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
293 charbuf[count] = '\0'; // turn it into a c string
297 // Error conditions. The buffer must still be
298 // processed for lines read
299 if (count == 0) { // EOF -- connection closed
301 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
302 cerr << "lyxclient: IO error." << endl;
306 // Cut a line from buffer
307 if ((pos = buffer.find('\n')) == string::npos)
308 return false; // No complete line stored
309 line = buffer.substr(0, pos);
310 buffer = buffer.substr(pos + 1);
315 // Write a line of the form <key>:<value> to the socket
316 void LyXDataSocket::writeln(string const & line)
318 string linen(line + '\n');
319 int size = linen.size();
320 int written = ::write(fd_, linen.c_str(), size);
321 if (written < size) { // Allways mean end of connection.
322 if ((written == -1) && (errno == EPIPE)) {
323 // The program will also receive a SIGPIPE
324 // that must be catched
325 cerr << "lyxclient: connection closed while writing."
328 // Anything else, including errno == EAGAIN, must be
329 // considered IO error. EAGAIN should never happen
330 // when line is small
331 cerr << "lyxclient: IO error: " << strerror(errno);
338 /////////////////////////////////////////////////////////////////////
342 /////////////////////////////////////////////////////////////////////
344 class CmdLineParser {
346 typedef int (*optfunc)(vector<docstring> const & args);
347 map<string, optfunc> helper;
348 map<string, bool> isset;
349 bool parse(int, char * []);
350 vector<char *> nonopt;
354 bool CmdLineParser::parse(int argc, char * argv[])
358 vector<docstring> args;
359 if (helper[argv[opt]]) {
360 isset[argv[opt]] = true;
362 while ((arg < argc) && (!helper[argv[arg]])) {
363 args.push_back(from_local8bit(argv[arg]));
366 int taken = helper[argv[opt]](args);
371 if (argv[opt][0] == '-') {
372 if ((argv[opt][1] == '-')
373 && (argv[opt][2]== '\0')) {
376 nonopt.push_back(argv[opt]);
381 cerr << "lyxclient: unknown option "
382 << argv[opt] << endl;
386 nonopt.push_back(argv[opt]);
392 // ~Class CmdLineParser -------------------------------------------------------
401 "Usage: lyxclient [options]\n"
403 " -a address set address of the lyx socket\n"
404 " -t directory set system temporary directory\n"
405 " -p pid select a running lyx by pidi\n"
406 " -c command send a single command and quit\n"
407 " -g file row send a command to go to file and row\n"
408 " -n name set client name\n"
409 " -h name display this help end exit\n"
410 "If -a is not used, lyxclient will use the arguments of -t and -p to look for\n"
411 "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set,\n"
412 "lyxclient will connect only to a lyx with the specified pid. Options -c and -g\n"
413 "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient\n"
414 "will read commands from standard input and disconnect when command read is BYE:"
419 int h(vector<docstring> const &)
426 docstring clientName =
427 from_ascii(itoa(::getppid()) + ">" + itoa(::getpid()));
429 int n(vector<docstring> const & arg)
431 if (arg.size() < 1) {
432 cerr << "lyxclient: The option -n requires 1 argument."
441 docstring singleCommand;
444 int c(vector<docstring> const & arg)
446 if (arg.size() < 1) {
447 cerr << "lyxclient: The option -c requires 1 argument."
451 singleCommand = arg[0];
456 int g(vector<docstring> const & arg)
458 if (arg.size() < 2) {
459 cerr << "lyxclient: The option -g requires 2 arguments."
463 singleCommand = "LYXCMD:server-goto-file-row "
470 // empty if LYXSOCKET is not set in the environment
471 docstring serverAddress;
474 int a(vector<docstring> const & arg)
476 if (arg.size() < 1) {
477 cerr << "lyxclient: The option -a requires 1 argument."
481 // -a supercedes LYXSOCKET environment variable
482 serverAddress = arg[0];
487 docstring mainTmp(from_ascii("/tmp"));
490 int t(vector<docstring> const & arg)
492 if (arg.size() < 1) {
493 cerr << "lyxclient: The option -t requires 1 argument."
502 string serverPid; // Init to empty string
505 int p(vector<docstring> const & arg)
507 if (arg.size() < 1) {
508 cerr << "lyxclient: The option -p requires 1 argument."
512 serverPid = to_ascii(arg[0]);
517 } // namespace cmdline
521 int main(int argc, char * argv[])
524 lyxerr.setStream(cerr);
526 char const * const lyxsocket = getenv("LYXSOCKET");
528 cmdline::serverAddress = from_local8bit(lyxsocket);
531 args.helper["-h"] = cmdline::h;
532 args.helper["-c"] = cmdline::c;
533 args.helper["-g"] = cmdline::g;
534 args.helper["-n"] = cmdline::n;
535 args.helper["-a"] = cmdline::a;
536 args.helper["-t"] = cmdline::t;
537 args.helper["-p"] = cmdline::p;
539 // Command line failure conditions:
540 if ((!args.parse(argc, argv))
541 || (args.isset["-c"] && args.isset["-g"])
542 || (args.isset["-a"] && args.isset["-p"])) {
547 scoped_ptr<LyXDataSocket> server;
549 if (!cmdline::serverAddress.empty()) {
550 server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress))));
551 if (!server->connected()) {
552 cerr << "lyxclient: " << "Could not connect to "
553 << to_utf8(cmdline::serverAddress) << endl;
557 // We have to look for an address.
558 // serverPid can be empty.
559 FileNameList addrs = lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid);
560 FileNameList::const_iterator addr = addrs.begin();
561 FileNameList::const_iterator end = addrs.end();
562 for (; addr != end; ++addr) {
563 // Caution: addr->string() is in filesystem encoding
564 server.reset(new LyXDataSocket(*addr));
565 if (server->connected())
567 lyxerr << "lyxclient: " << "Could not connect to "
568 << addr->absFilename() << endl;
571 lyxerr << "lyxclient: No suitable server found."
575 cerr << "lyxclient: " << "Connected to " << addr->absFilename() << endl;
578 int const serverfd = server->fd();
581 iowatch.addfd(serverfd);
583 // Used to read from server
587 server->writeln("HELLO:" + to_utf8(cmdline::clientName));
588 // wait at most 2 seconds until server responds
590 if (iowatch.isset(serverfd) && server->readln(answer)) {
591 if (prefixIs(answer, "BYE:")) {
592 cerr << "lyxclient: Server disconnected." << endl;
593 cout << answer << endl;
597 cerr << "lyxclient: No answer from server." << endl;
601 if (args.isset["-g"] || args.isset["-c"]) {
602 server->writeln(to_utf8(cmdline::singleCommand));
604 if (iowatch.isset(serverfd) && server->readln(answer)) {
606 if (prefixIs(answer, "ERROR:"))
610 cerr << "lyxclient: No answer from server." << endl;
615 // Take commands from stdin
616 iowatch.addfd(0); // stdin
617 bool saidbye = false;
618 while ((!saidbye) && server->connected()) {
620 if (iowatch.isset(0)) {
622 getline(cin, command);
623 if (command == "BYE:") {
624 server->writeln("BYE:");
627 server->writeln("LYXCMD:" + command);
630 if (iowatch.isset(serverfd)) {
631 while(server->readln(answer))
632 cout << answer << endl;
642 void assertion_failed(char const* a, char const* b, char const* c, long d)
644 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '