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;
68 // Keep the linker happy on Windows
74 string itoa(unsigned int i)
77 sprintf(buf, "%d", i);
82 /// Returns the absolute pathnames of all lyx local sockets in
83 /// file system encoding.
84 /// Parts stolen from lyx::support::DirList().
85 FileNameList lyxSockets(string const & dir, string const & pid)
89 FileName dirpath(dir + "/");
91 if (!dirpath.exists() || !dirpath.isDirectory()) {
92 lyxerr << dir << " does not exist or is not a directory."
97 FileNameList dirs = dirpath.dirList("");
98 FileNameList::const_iterator it = dirs.begin();
99 FileNameList::const_iterator end = dirs.end();
101 for (; it != end; ++it) {
102 if (!it->isDirectory())
104 string const tmpdir = it->absFilename();
105 if (!contains(tmpdir, "lyx_tmpdir" + pid))
108 FileName lyxsocket(tmpdir + "/lyxsocket");
109 if (lyxsocket.exists())
110 dirlist.push_back(lyxsocket);
117 namespace socktools {
120 /// Connect to the socket \p name.
121 int connect(FileName const & name)
123 int fd; // File descriptor for the socket
124 sockaddr_un addr; // Structure that hold the socket address
126 string const encoded = name.toFilesystemEncoding();
127 // char sun_path[108]
128 string::size_type len = encoded.size();
130 cerr << "lyxclient: Socket address '" << name
131 << "' too long." << endl;
134 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
135 addr.sun_family = AF_UNIX;
136 encoded.copy(addr.sun_path, 107);
137 addr.sun_path[len] = '\0';
139 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
140 cerr << "lyxclient: Could not create socket descriptor: "
141 << strerror(errno) << endl;
145 reinterpret_cast<struct sockaddr *>(&addr),
146 sizeof(addr)) == -1) {
147 cerr << "lyxclient: Could not connect to socket " << name.absFilename()
148 << ": " << strerror(errno) << endl;
152 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
153 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
154 << strerror(errno) << endl;
162 } // namespace socktools
163 } // namespace support
167 /////////////////////////////////////////////////////////////////////
171 /////////////////////////////////////////////////////////////////////
193 void IOWatch::clear()
199 void IOWatch::addfd(int fd)
205 bool IOWatch::wait(double timeout)
208 to.tv_sec = static_cast<long int>(timeout);
209 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
211 return select(FD_SETSIZE, &act,
212 (fd_set *)0, (fd_set *)0, &to);
219 return select(FD_SETSIZE, &act,
220 (fd_set *)0, (fd_set *)0, (timeval *)0);
224 bool IOWatch::isset(int fd)
226 return FD_ISSET(fd, &act);
231 /////////////////////////////////////////////////////////////////////
235 /////////////////////////////////////////////////////////////////////
237 // Modified LyXDataSocket class for use with the client
238 class LyXDataSocket {
240 LyXDataSocket(FileName const &);
242 // File descriptor of the connection
245 bool connected() const;
246 // Line buffered input from the socket
247 bool readln(string &);
248 // Write the string + '\n' to the socket
249 void writeln(string const &);
251 // File descriptor for the data socket
253 // True if the connection is up
255 // buffer for input data
260 LyXDataSocket::LyXDataSocket(FileName const & address)
262 if ((fd_ = socktools::connect(address)) == -1) {
270 LyXDataSocket::~LyXDataSocket()
276 int LyXDataSocket::fd() const
282 bool LyXDataSocket::connected() const
288 // Returns true if there was a complete line to input
289 // A line is of the form <key>:<value>
290 // A line not of this form will not be passed
291 // The line read is splitted and stored in 'key' and 'value'
292 bool LyXDataSocket::readln(string & line)
294 int const charbuf_size = 100;
295 char charbuf[charbuf_size]; // buffer for the ::read() system call
297 string::size_type pos;
299 // read and store characters in buffer
300 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
301 charbuf[count] = '\0'; // turn it into a c string
305 // Error conditions. The buffer must still be
306 // processed for lines read
307 if (count == 0) { // EOF -- connection closed
309 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
310 cerr << "lyxclient: IO error." << endl;
314 // Cut a line from buffer
315 if ((pos = buffer.find('\n')) == string::npos)
316 return false; // No complete line stored
317 line = buffer.substr(0, pos);
318 buffer = buffer.substr(pos + 1);
323 // Write a line of the form <key>:<value> to the socket
324 void LyXDataSocket::writeln(string const & line)
326 string linen(line + '\n');
327 int size = linen.size();
328 int written = ::write(fd_, linen.c_str(), size);
329 if (written < size) { // Allways mean end of connection.
330 if ((written == -1) && (errno == EPIPE)) {
331 // The program will also receive a SIGPIPE
332 // that must be catched
333 cerr << "lyxclient: connection closed while writing."
336 // Anything else, including errno == EAGAIN, must be
337 // considered IO error. EAGAIN should never happen
338 // when line is small
339 cerr << "lyxclient: IO error: " << strerror(errno);
346 /////////////////////////////////////////////////////////////////////
350 /////////////////////////////////////////////////////////////////////
352 class CmdLineParser {
354 typedef int (*optfunc)(vector<docstring> const & args);
355 map<string, optfunc> helper;
356 map<string, bool> isset;
357 bool parse(int, char * []);
358 vector<char *> nonopt;
362 bool CmdLineParser::parse(int argc, char * argv[])
366 vector<docstring> args;
367 if (helper[argv[opt]]) {
368 isset[argv[opt]] = true;
370 while ((arg < argc) && (!helper[argv[arg]])) {
371 args.push_back(from_local8bit(argv[arg]));
374 int taken = helper[argv[opt]](args);
379 if (argv[opt][0] == '-') {
380 if ((argv[opt][1] == '-')
381 && (argv[opt][2]== '\0')) {
384 nonopt.push_back(argv[opt]);
389 cerr << "lyxclient: unknown option "
390 << argv[opt] << endl;
394 nonopt.push_back(argv[opt]);
400 // ~Class CmdLineParser -------------------------------------------------------
409 "Usage: lyxclient [options]\n"
411 " -a address set address of the lyx socket\n"
412 " -t directory set system temporary directory (for detecting sockets)\n"
413 " -p pid select a running lyx by pidi\n"
414 " -c command send a single command and quit (LYXCMD prefix needed)\n"
415 " -g file row send a command to go to file and row\n"
416 " -n name set client name\n"
417 " -h name display this help end exit\n"
418 "If -a is not used, lyxclient will use the arguments of -t and -p to look for\n"
419 "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set,\n"
420 "lyxclient will connect only to a lyx with the specified pid. Options -c and -g\n"
421 "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient\n"
422 "will read commands from standard input and disconnect when command read is BYE:"
427 int h(vector<docstring> const &)
434 docstring clientName =
435 from_ascii(itoa(::getppid()) + ">" + itoa(::getpid()));
437 int n(vector<docstring> const & arg)
439 if (arg.size() < 1) {
440 cerr << "lyxclient: The option -n requires 1 argument."
449 docstring singleCommand;
452 int c(vector<docstring> const & arg)
454 if (arg.size() < 1) {
455 cerr << "lyxclient: The option -c requires 1 argument."
459 singleCommand = arg[0];
464 int g(vector<docstring> const & arg)
466 if (arg.size() < 2) {
467 cerr << "lyxclient: The option -g requires 2 arguments."
471 singleCommand = "LYXCMD:server-goto-file-row "
478 // empty if LYXSOCKET is not set in the environment
479 docstring serverAddress;
482 int a(vector<docstring> const & arg)
484 if (arg.size() < 1) {
485 cerr << "lyxclient: The option -a requires 1 argument."
489 // -a supercedes LYXSOCKET environment variable
490 serverAddress = arg[0];
495 docstring mainTmp(from_ascii("/tmp"));
498 int t(vector<docstring> const & arg)
500 if (arg.size() < 1) {
501 cerr << "lyxclient: The option -t requires 1 argument."
510 string serverPid; // Init to empty string
513 int p(vector<docstring> const & arg)
515 if (arg.size() < 1) {
516 cerr << "lyxclient: The option -p requires 1 argument."
520 serverPid = to_ascii(arg[0]);
525 } // namespace cmdline
529 int main(int argc, char * argv[])
532 lyxerr.setStream(cerr);
534 char const * const lyxsocket = getenv("LYXSOCKET");
536 cmdline::serverAddress = from_local8bit(lyxsocket);
539 args.helper["-h"] = cmdline::h;
540 args.helper["-c"] = cmdline::c;
541 args.helper["-g"] = cmdline::g;
542 args.helper["-n"] = cmdline::n;
543 args.helper["-a"] = cmdline::a;
544 args.helper["-t"] = cmdline::t;
545 args.helper["-p"] = cmdline::p;
547 // Command line failure conditions:
548 if ((!args.parse(argc, argv))
549 || (args.isset["-c"] && args.isset["-g"])
550 || (args.isset["-a"] && args.isset["-p"])) {
555 scoped_ptr<LyXDataSocket> server;
557 if (!cmdline::serverAddress.empty()) {
558 server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress))));
559 if (!server->connected()) {
560 cerr << "lyxclient: " << "Could not connect to "
561 << to_utf8(cmdline::serverAddress) << endl;
565 // We have to look for an address.
566 // serverPid can be empty.
567 FileNameList addrs = lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid);
568 FileNameList::const_iterator addr = addrs.begin();
569 FileNameList::const_iterator end = addrs.end();
570 for (; addr != end; ++addr) {
571 // Caution: addr->string() is in filesystem encoding
572 server.reset(new LyXDataSocket(*addr));
573 if (server->connected())
575 lyxerr << "lyxclient: " << "Could not connect to "
576 << addr->absFilename() << endl;
579 lyxerr << "lyxclient: No suitable server found."
583 cerr << "lyxclient: " << "Connected to " << addr->absFilename() << endl;
586 int const serverfd = server->fd();
589 iowatch.addfd(serverfd);
591 // Used to read from server
595 server->writeln("HELLO:" + to_utf8(cmdline::clientName));
596 // wait at most 2 seconds until server responds
598 if (iowatch.isset(serverfd) && server->readln(answer)) {
599 if (prefixIs(answer, "BYE:")) {
600 cerr << "lyxclient: Server disconnected." << endl;
601 cout << answer << endl;
605 cerr << "lyxclient: No answer from server." << endl;
609 if (args.isset["-g"] || args.isset["-c"]) {
610 server->writeln(to_utf8(cmdline::singleCommand));
612 if (iowatch.isset(serverfd) && server->readln(answer)) {
614 if (prefixIs(answer, "ERROR:"))
618 cerr << "lyxclient: No answer from server." << endl;
623 // Take commands from stdin
624 iowatch.addfd(0); // stdin
625 bool saidbye = false;
626 while ((!saidbye) && server->connected()) {
628 if (iowatch.isset(0)) {
630 getline(cin, command);
633 if (command == "BYE:") {
634 server->writeln("BYE:");
637 server->writeln("LYXCMD:" + command);
640 if (iowatch.isset(serverfd)) {
641 while(server->readln(answer))
642 cout << answer << endl;
652 void assertion_failed(char const* a, char const* b, char const* c, long d)
654 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '