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.
17 #include "support/lstrings.h"
19 #include <boost/filesystem/operations.hpp>
20 #include <boost/lexical_cast.hpp>
21 #include <boost/scoped_ptr.hpp>
23 // getpid(), getppid()
24 #include <sys/types.h>
28 #include <sys/select.h>
30 // socket(), connect()
31 #include <sys/socket.h>
44 using lyx::support::prefixIs;
46 using boost::scoped_ptr;
47 namespace fs = boost::filesystem;
57 // hack to link in libsupport
63 string itoa(unsigned int i)
65 return boost::lexical_cast<string>(i);
69 // Parts stolen from lyx::support::DirList()
70 // Returns the absolute pathnames of all lyx local sockets
71 vector<fs::path> lyxSockets(string const & dir, string const & pid)
73 vector<fs::path> dirlist;
75 fs::path dirpath(dir);
77 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
78 lyxerr << dir << " does not exist or is not a directory."
83 fs::directory_iterator beg((fs::path(dir)));
84 fs::directory_iterator end;
86 for (; beg != end; ++beg) {
87 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
88 fs::path lyxsocket = *beg / "lyxsocket";
89 if (fs::exists(lyxsocket)) {
90 dirlist.push_back(lyxsocket);
102 int connect(string const & name)
104 int fd; // File descriptor for the socket
105 sockaddr_un addr; // Structure that hold the socket address
107 // char sun_path[108]
108 string::size_type len = name.size();
110 cerr << "lyxclient: Socket address '" << name
111 << "' too long." << endl;
114 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
115 addr.sun_family = AF_UNIX;
116 name.copy(addr.sun_path, 107);
117 addr.sun_path[len] = '\0';
119 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
120 cerr << "lyxclient: Could not create socket descriptor: "
121 << strerror(errno) << endl;
125 reinterpret_cast<struct sockaddr *>(&addr),
126 sizeof(addr)) == -1) {
127 cerr << "lyxclient: Could not connect to socket " << name
128 << ": " << strerror(errno) << endl;
132 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
133 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
134 << strerror(errno) << endl;
142 } // namespace socktools
143 } // namespace support
147 // Class IOWatch ------------------------------------------------------------
168 void IOWatch::clear()
174 void IOWatch::addfd(int fd)
180 bool IOWatch::wait(double timeout)
183 to.tv_sec = static_cast<long int>(timeout);
184 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
186 return select(FD_SETSIZE, &act,
187 (fd_set *)0, (fd_set *)0, &to);
194 return select(FD_SETSIZE, &act,
195 (fd_set *)0, (fd_set *)0, (timeval *)0);
199 bool IOWatch::isset(int fd) {
200 return FD_ISSET(fd, &act);
202 // ~Class IOWatch ------------------------------------------------------------
205 // Class LyXDataSocket -------------------------------------------------------
206 // Modified LyXDataSocket class for use with the client
207 class LyXDataSocket {
209 LyXDataSocket(string const &);
211 // File descriptor of the connection
214 bool connected() const;
215 // Line buffered input from the socket
216 bool readln(string &);
217 // Write the string + '\n' to the socket
218 void writeln(string const &);
220 // File descriptor for the data socket
222 // True if the connection is up
224 // buffer for input data
229 LyXDataSocket::LyXDataSocket(string const & address)
231 if ((fd_ = support::socktools::connect(address)) == -1) {
239 LyXDataSocket::~LyXDataSocket()
245 int LyXDataSocket::fd() const
251 bool LyXDataSocket::connected() const
257 // Returns true if there was a complete line to input
258 // A line is of the form <key>:<value>
259 // A line not of this form will not be passed
260 // The line read is splitted and stored in 'key' and 'value'
261 bool LyXDataSocket::readln(string & line)
263 int const charbuf_size = 100;
264 char charbuf[charbuf_size]; // buffer for the ::read() system call
266 string::size_type pos;
268 // read and store characters in buffer
269 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
270 charbuf[count] = '\0'; // turn it into a c string
274 // Error conditions. The buffer must still be
275 // processed for lines read
276 if (count == 0) { // EOF -- connection closed
278 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
279 cerr << "lyxclient: IO error." << endl;
283 // Cut a line from buffer
284 if ((pos = buffer.find('\n')) == string::npos)
285 return false; // No complete line stored
286 line = buffer.substr(0, pos);
287 buffer = buffer.substr(pos + 1);
292 // Write a line of the form <key>:<value> to the socket
293 void LyXDataSocket::writeln(string const & line)
295 string linen(line + '\n');
296 int size = linen.size();
297 int written = ::write(fd_, linen.c_str(), size);
298 if (written < size) { // Allways mean end of connection.
299 if ((written == -1) && (errno == EPIPE)) {
300 // The program will also receive a SIGPIPE
301 // that must be catched
302 cerr << "lyxclient: connection closed while writing."
305 // Anything else, including errno == EAGAIN, must be
306 // considered IO error. EAGAIN should never happen
307 // when line is small
308 cerr << "lyxclient: IO error: " << strerror(errno);
313 // ~Class LyXDataSocket -------------------------------------------------------
316 // Class CmdLineParser -------------------------------------------------------
317 class CmdLineParser {
319 typedef int (*optfunc)(vector<char *> const & args);
320 std::map<string, optfunc> helper;
321 std::map<string, bool> isset;
322 bool parse(int, char * []);
323 vector<char *> nonopt;
327 bool CmdLineParser::parse(int argc, char * argv[])
332 if (helper[argv[opt]]) {
333 isset[argv[opt]] = true;
335 while ((arg < argc) && (!helper[argv[arg]])) {
336 args.push_back(argv[arg]);
339 int taken = helper[argv[opt]](args);
344 if (argv[opt][0] == '-') {
345 if ((argv[opt][1] == '-')
346 && (argv[opt][2]== '\0')) {
349 nonopt.push_back(argv[opt]);
354 cerr << "lyxclient: unknown option "
355 << argv[opt] << endl;
359 nonopt.push_back(argv[opt]);
365 // ~Class CmdLineParser -------------------------------------------------------
373 cerr << "Usage: lyxclient [options]" << endl
374 << "Options are:" << endl
375 << " -a address set address of the lyx socket" << endl
376 << " -t directory set system temporary directory" << endl
377 << " -p pid select a running lyx by pid" << endl
378 << " -c command send a single command and quit" << endl
379 << " -g file row send a command to go to file and row" << endl
380 << " -n name set client name" << endl
381 << " -h name display this help end exit" << endl
382 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
383 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
384 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
385 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
386 << "will read commands from standard input and disconnect when command read is BYE:"
391 int h(vector<char *> const &)
398 string clientName(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
400 int n(vector<char *> const & arg)
402 if (arg.size() < 1) {
403 cerr << "lyxclient: The option -n requires 1 argument."
412 string singleCommand;
415 int c(vector<char *> const & arg)
417 if (arg.size() < 1) {
418 cerr << "lyxclient: The option -c requires 1 argument."
422 singleCommand = arg[0];
427 int g(vector<char *> const & arg)
429 if (arg.size() < 2) {
430 cerr << "lyxclient: The option -g requires 2 arguments."
434 singleCommand = "LYXCMD:server-goto-file-row "
435 + string(arg[0]) + ' '
441 // 0 if LYXSOCKET is not set in the environment
442 char * serverAddress = getenv("LYXSOCKET");
445 int a(vector<char *> const & arg)
447 if (arg.size() < 1) {
448 cerr << "lyxclient: The option -a requires 1 argument."
452 // -a supercedes LYXSOCKET environment variable
453 serverAddress = arg[0];
458 string mainTmp("/tmp");
461 int t(vector<char *> const & arg)
463 if (arg.size() < 1) {
464 cerr << "lyxclient: The option -t requires 1 argument."
473 string serverPid; // Init to empty string
476 int p(vector<char *> const & arg)
478 if (arg.size() < 1) {
479 cerr << "lyxclient: The option -p requires 1 argument."
488 } // namespace cmdline
494 int main(int argc, char * argv[])
496 lyxerr.rdbuf(cerr.rdbuf());
499 args.helper["-h"] = cmdline::h;
500 args.helper["-c"] = cmdline::c;
501 args.helper["-g"] = cmdline::g;
502 args.helper["-n"] = cmdline::n;
503 args.helper["-a"] = cmdline::a;
504 args.helper["-t"] = cmdline::t;
505 args.helper["-p"] = cmdline::p;
507 // Command line failure conditions:
508 if ((!args.parse(argc, argv))
509 || (args.isset["-c"] && args.isset["-g"])
510 || (args.isset["-a"] && args.isset["-p"])) {
515 scoped_ptr<LyXDataSocket> server;
517 if (cmdline::serverAddress) {
518 server.reset(new LyXDataSocket(cmdline::serverAddress));
519 if (!server->connected()) {
520 cerr << "lyxclient: " << "Could not connect to "
521 << cmdline::serverAddress << endl;
525 // We have to look for an address.
526 // serverPid can be empty.
527 vector<fs::path> addrs = support::lyxSockets(cmdline::mainTmp, cmdline::serverPid);
528 vector<fs::path>::const_iterator addr = addrs.begin();
529 vector<fs::path>::const_iterator end = addrs.end();
530 for (; addr != end; ++addr) {
531 server.reset(new LyXDataSocket(addr->string()));
532 if (server->connected())
534 lyxerr << "lyxclient: " << "Could not connect to "
535 << addr->string() << endl;
538 lyxerr << "lyxclient: No suitable server found."
542 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
545 int const serverfd = server->fd();
548 iowatch.addfd(serverfd);
550 // Used to read from server
554 server->writeln("HELLO:" + cmdline::clientName);
555 // wait at most 2 seconds until server responds
557 if (iowatch.isset(serverfd) && server->readln(answer)) {
558 if (prefixIs(answer, "BYE:")) {
559 cerr << "lyxclient: Server disconnected." << endl;
560 cout << answer << endl;
564 cerr << "lyxclient: No answer from server." << endl;
568 if (args.isset["-g"] || args.isset["-c"]) {
569 server->writeln(cmdline::singleCommand);
571 if (iowatch.isset(serverfd) && server->readln(answer)) {
573 if (prefixIs(answer, "ERROR:"))
577 cerr << "lyxclient: No answer from server." << endl;
582 // Take commands from stdin
583 iowatch.addfd(0); // stdin
584 bool saidbye = false;
585 while ((!saidbye) && server->connected()) {
587 if (iowatch.isset(0)) {
590 if (command == "BYE:") {
591 server->writeln("BYE:");
594 server->writeln("LYXCMD:" + command);
597 if (iowatch.isset(serverfd)) {
598 while(server->readln(answer))
599 cout << answer << endl;