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>
59 using namespace lyx::support;
61 using ::boost::scoped_ptr;
67 string itoa(unsigned int i)
70 sprintf(buf, "%d", i);
75 /// Returns the absolute pathnames of all lyx local sockets in
76 /// file system encoding.
77 /// Parts stolen from lyx::support::DirList().
78 FileNameList lyxSockets(string const & dir, string const & pid)
82 FileName dirpath(dir + "/");
84 if (!dirpath.exists() || !dirpath.isDirectory()) {
85 lyxerr << dir << " does not exist or is not a directory."
90 FileNameList dirs = dirpath.dirList("");
91 FileNameList::const_iterator it = dirs.begin();
92 FileNameList::const_iterator end = dirs.end();
94 for (; it != end; ++it) {
95 if (!it->isDirectory())
97 string const tmpdir = it->absFilename();
98 if (!contains(tmpdir, "lyx_tmpdir" + pid))
101 FileName lyxsocket(tmpdir + "/lyxsocket");
102 if (lyxsocket.exists())
103 dirlist.push_back(lyxsocket);
110 namespace socktools {
113 /// Connect to the socket \p name.
114 int connect(FileName const & name)
116 int fd; // File descriptor for the socket
117 sockaddr_un addr; // Structure that hold the socket address
119 string const encoded = name.toFilesystemEncoding();
120 // char sun_path[108]
121 string::size_type len = encoded.size();
123 cerr << "lyxclient: Socket address '" << name
124 << "' too long." << endl;
127 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
128 addr.sun_family = AF_UNIX;
129 encoded.copy(addr.sun_path, 107);
130 addr.sun_path[len] = '\0';
132 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
133 cerr << "lyxclient: Could not create socket descriptor: "
134 << strerror(errno) << endl;
138 reinterpret_cast<struct sockaddr *>(&addr),
139 sizeof(addr)) == -1) {
140 cerr << "lyxclient: Could not connect to socket " << name.absFilename()
141 << ": " << strerror(errno) << endl;
145 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
146 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
147 << strerror(errno) << endl;
155 } // namespace socktools
156 } // namespace support
160 /////////////////////////////////////////////////////////////////////
164 /////////////////////////////////////////////////////////////////////
186 void IOWatch::clear()
192 void IOWatch::addfd(int fd)
198 bool IOWatch::wait(double timeout)
201 to.tv_sec = static_cast<long int>(timeout);
202 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
204 return select(FD_SETSIZE, &act,
205 (fd_set *)0, (fd_set *)0, &to);
212 return select(FD_SETSIZE, &act,
213 (fd_set *)0, (fd_set *)0, (timeval *)0);
217 bool IOWatch::isset(int fd)
219 return FD_ISSET(fd, &act);
224 /////////////////////////////////////////////////////////////////////
228 /////////////////////////////////////////////////////////////////////
230 // Modified LyXDataSocket class for use with the client
231 class LyXDataSocket {
233 LyXDataSocket(FileName const &);
235 // File descriptor of the connection
238 bool connected() const;
239 // Line buffered input from the socket
240 bool readln(string &);
241 // Write the string + '\n' to the socket
242 void writeln(string const &);
244 // File descriptor for the data socket
246 // True if the connection is up
248 // buffer for input data
253 LyXDataSocket::LyXDataSocket(FileName const & address)
255 if ((fd_ = socktools::connect(address)) == -1) {
263 LyXDataSocket::~LyXDataSocket()
269 int LyXDataSocket::fd() const
275 bool LyXDataSocket::connected() const
281 // Returns true if there was a complete line to input
282 // A line is of the form <key>:<value>
283 // A line not of this form will not be passed
284 // The line read is splitted and stored in 'key' and 'value'
285 bool LyXDataSocket::readln(string & line)
287 int const charbuf_size = 100;
288 char charbuf[charbuf_size]; // buffer for the ::read() system call
290 string::size_type pos;
292 // read and store characters in buffer
293 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
294 charbuf[count] = '\0'; // turn it into a c string
298 // Error conditions. The buffer must still be
299 // processed for lines read
300 if (count == 0) { // EOF -- connection closed
302 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
303 cerr << "lyxclient: IO error." << endl;
307 // Cut a line from buffer
308 if ((pos = buffer.find('\n')) == string::npos)
309 return false; // No complete line stored
310 line = buffer.substr(0, pos);
311 buffer = buffer.substr(pos + 1);
316 // Write a line of the form <key>:<value> to the socket
317 void LyXDataSocket::writeln(string const & line)
319 string linen(line + '\n');
320 int size = linen.size();
321 int written = ::write(fd_, linen.c_str(), size);
322 if (written < size) { // Allways mean end of connection.
323 if ((written == -1) && (errno == EPIPE)) {
324 // The program will also receive a SIGPIPE
325 // that must be catched
326 cerr << "lyxclient: connection closed while writing."
329 // Anything else, including errno == EAGAIN, must be
330 // considered IO error. EAGAIN should never happen
331 // when line is small
332 cerr << "lyxclient: IO error: " << strerror(errno);
339 /////////////////////////////////////////////////////////////////////
343 /////////////////////////////////////////////////////////////////////
345 class CmdLineParser {
347 typedef int (*optfunc)(vector<docstring> const & args);
348 map<string, optfunc> helper;
349 map<string, bool> isset;
350 bool parse(int, char * []);
351 vector<char *> nonopt;
355 bool CmdLineParser::parse(int argc, char * argv[])
359 vector<docstring> args;
360 if (helper[argv[opt]]) {
361 isset[argv[opt]] = true;
363 while ((arg < argc) && (!helper[argv[arg]])) {
364 args.push_back(from_local8bit(argv[arg]));
367 int taken = helper[argv[opt]](args);
372 if (argv[opt][0] == '-') {
373 if ((argv[opt][1] == '-')
374 && (argv[opt][2]== '\0')) {
377 nonopt.push_back(argv[opt]);
382 cerr << "lyxclient: unknown option "
383 << argv[opt] << endl;
387 nonopt.push_back(argv[opt]);
393 // ~Class CmdLineParser -------------------------------------------------------
402 "Usage: lyxclient [options]\n"
404 " -a address set address of the lyx socket\n"
405 " -t directory set system temporary directory\n"
406 " -p pid select a running lyx by pidi\n"
407 " -c command send a single command and quit\n"
408 " -g file row send a command to go to file and row\n"
409 " -n name set client name\n"
410 " -h name display this help end exit\n"
411 "If -a is not used, lyxclient will use the arguments of -t and -p to look for\n"
412 "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set,\n"
413 "lyxclient will connect only to a lyx with the specified pid. Options -c and -g\n"
414 "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient\n"
415 "will read commands from standard input and disconnect when command read is BYE:"
420 int h(vector<docstring> const &)
427 docstring clientName =
428 from_ascii(itoa(::getppid()) + ">" + itoa(::getpid()));
430 int n(vector<docstring> const & arg)
432 if (arg.size() < 1) {
433 cerr << "lyxclient: The option -n requires 1 argument."
442 docstring singleCommand;
445 int c(vector<docstring> const & arg)
447 if (arg.size() < 1) {
448 cerr << "lyxclient: The option -c requires 1 argument."
452 singleCommand = arg[0];
457 int g(vector<docstring> const & arg)
459 if (arg.size() < 2) {
460 cerr << "lyxclient: The option -g requires 2 arguments."
464 singleCommand = "LYXCMD:server-goto-file-row "
471 // empty if LYXSOCKET is not set in the environment
472 docstring serverAddress;
475 int a(vector<docstring> const & arg)
477 if (arg.size() < 1) {
478 cerr << "lyxclient: The option -a requires 1 argument."
482 // -a supercedes LYXSOCKET environment variable
483 serverAddress = arg[0];
488 docstring mainTmp(from_ascii("/tmp"));
491 int t(vector<docstring> const & arg)
493 if (arg.size() < 1) {
494 cerr << "lyxclient: The option -t requires 1 argument."
503 string serverPid; // Init to empty string
506 int p(vector<docstring> const & arg)
508 if (arg.size() < 1) {
509 cerr << "lyxclient: The option -p requires 1 argument."
513 serverPid = to_ascii(arg[0]);
518 } // namespace cmdline
522 int main(int argc, char * argv[])
525 lyxerr.setStream(cerr);
527 char const * const lyxsocket = getenv("LYXSOCKET");
529 cmdline::serverAddress = from_local8bit(lyxsocket);
532 args.helper["-h"] = cmdline::h;
533 args.helper["-c"] = cmdline::c;
534 args.helper["-g"] = cmdline::g;
535 args.helper["-n"] = cmdline::n;
536 args.helper["-a"] = cmdline::a;
537 args.helper["-t"] = cmdline::t;
538 args.helper["-p"] = cmdline::p;
540 // Command line failure conditions:
541 if ((!args.parse(argc, argv))
542 || (args.isset["-c"] && args.isset["-g"])
543 || (args.isset["-a"] && args.isset["-p"])) {
548 scoped_ptr<LyXDataSocket> server;
550 if (!cmdline::serverAddress.empty()) {
551 server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress))));
552 if (!server->connected()) {
553 cerr << "lyxclient: " << "Could not connect to "
554 << to_utf8(cmdline::serverAddress) << endl;
558 // We have to look for an address.
559 // serverPid can be empty.
560 FileNameList addrs = lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid);
561 FileNameList::const_iterator addr = addrs.begin();
562 FileNameList::const_iterator end = addrs.end();
563 for (; addr != end; ++addr) {
564 // Caution: addr->string() is in filesystem encoding
565 server.reset(new LyXDataSocket(*addr));
566 if (server->connected())
568 lyxerr << "lyxclient: " << "Could not connect to "
569 << addr->absFilename() << endl;
572 lyxerr << "lyxclient: No suitable server found."
576 cerr << "lyxclient: " << "Connected to " << addr->absFilename() << endl;
579 int const serverfd = server->fd();
582 iowatch.addfd(serverfd);
584 // Used to read from server
588 server->writeln("HELLO:" + to_utf8(cmdline::clientName));
589 // wait at most 2 seconds until server responds
591 if (iowatch.isset(serverfd) && server->readln(answer)) {
592 if (prefixIs(answer, "BYE:")) {
593 cerr << "lyxclient: Server disconnected." << endl;
594 cout << answer << endl;
598 cerr << "lyxclient: No answer from server." << endl;
602 if (args.isset["-g"] || args.isset["-c"]) {
603 server->writeln(to_utf8(cmdline::singleCommand));
605 if (iowatch.isset(serverfd) && server->readln(answer)) {
607 if (prefixIs(answer, "ERROR:"))
611 cerr << "lyxclient: No answer from server." << endl;
616 // Take commands from stdin
617 iowatch.addfd(0); // stdin
618 bool saidbye = false;
619 while ((!saidbye) && server->connected()) {
621 if (iowatch.isset(0)) {
623 getline(cin, command);
624 if (command == "BYE:") {
625 server->writeln("BYE:");
628 server->writeln("LYXCMD:" + command);
631 if (iowatch.isset(serverfd)) {
632 while(server->readln(answer))
633 cout << answer << endl;
643 void assertion_failed(char const* a, char const* b, char const* c, long d)
645 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '