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.
16 #include "support/lstrings.h"
18 #include <boost/filesystem/operations.hpp>
19 #include <boost/lexical_cast.hpp>
20 #include <boost/scoped_ptr.hpp>
22 // getpid(), getppid()
23 #include <sys/types.h>
27 #include <sys/select.h>
29 // socket(), connect()
30 #include <sys/socket.h>
43 using lyx::support::prefixIs;
45 using boost::scoped_ptr;
46 namespace fs = boost::filesystem;
58 string itoa(unsigned int i)
60 return boost::lexical_cast<string>(i);
64 // Parts stolen from lyx::support::DirList()
65 // Returns the absolute pathnames of all lyx local sockets
66 vector<fs::path> lyxSockets(string const & dir, string const & pid)
68 vector<fs::path> dirlist;
70 fs::path dirpath(dir);
72 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
73 lyxerr << dir << " does not exist or is not a directory."
78 fs::directory_iterator beg((fs::path(dir)));
79 fs::directory_iterator end;
81 for (; beg != end; ++beg) {
82 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
83 fs::path lyxsocket = *beg / "lyxsocket";
84 if (fs::exists(lyxsocket)) {
85 dirlist.push_back(lyxsocket);
97 int connect(string const & name)
99 int fd; // File descriptor for the socket
100 sockaddr_un addr; // Structure that hold the socket address
102 // char sun_path[108]
103 string::size_type len = name.size();
105 cerr << "lyxclient: Socket address '" << name
106 << "' too long." << endl;
109 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
110 addr.sun_family = AF_UNIX;
111 name.copy(addr.sun_path, 107);
112 addr.sun_path[len] = '\0';
114 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
115 cerr << "lyxclient: Could not create socket descriptor: "
116 << strerror(errno) << endl;
120 reinterpret_cast<struct sockaddr *>(&addr),
121 sizeof(addr)) == -1) {
122 cerr << "lyxclient: Could not connect to socket " << name
123 << ": " << strerror(errno) << endl;
127 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
128 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
129 << strerror(errno) << endl;
137 } // namespace socktools
138 } // namespace support
142 // Class IOWatch ------------------------------------------------------------
163 void IOWatch::clear()
169 void IOWatch::addfd(int fd)
175 bool IOWatch::wait(double timeout)
178 to.tv_sec = static_cast<long int>(timeout);
179 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
181 return select(FD_SETSIZE, &act,
182 (fd_set *)0, (fd_set *)0, &to);
189 return select(FD_SETSIZE, &act,
190 (fd_set *)0, (fd_set *)0, (timeval *)0);
194 bool IOWatch::isset(int fd) {
195 return FD_ISSET(fd, &act);
197 // ~Class IOWatch ------------------------------------------------------------
200 // Class LyXDataSocket -------------------------------------------------------
201 // Modified LyXDataSocket class for use with the client
202 class LyXDataSocket {
204 LyXDataSocket(string const &);
206 // File descriptor of the connection
209 bool connected() const;
210 // Line buffered input from the socket
211 bool readln(string &);
212 // Write the string + '\n' to the socket
213 void writeln(string const &);
215 // File descriptor for the data socket
217 // True if the connection is up
219 // buffer for input data
224 LyXDataSocket::LyXDataSocket(string const & address)
226 if ((fd_ = support::socktools::connect(address)) == -1) {
234 LyXDataSocket::~LyXDataSocket()
240 int LyXDataSocket::fd() const
246 bool LyXDataSocket::connected() const
252 // Returns true if there was a complete line to input
253 // A line is of the form <key>:<value>
254 // A line not of this form will not be passed
255 // The line read is splitted and stored in 'key' and 'value'
256 bool LyXDataSocket::readln(string & line)
258 int const charbuf_size = 100;
259 char charbuf[charbuf_size]; // buffer for the ::read() system call
261 string::size_type pos;
263 // read and store characters in buffer
264 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
265 charbuf[count] = '\0'; // turn it into a c string
269 // Error conditions. The buffer must still be
270 // processed for lines read
271 if (count == 0) { // EOF -- connection closed
273 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
274 cerr << "lyxclient: IO error." << endl;
278 // Cut a line from buffer
279 if ((pos = buffer.find('\n')) == string::npos)
280 return false; // No complete line stored
281 line = buffer.substr(0, pos);
282 buffer = buffer.substr(pos + 1);
287 // Write a line of the form <key>:<value> to the socket
288 void LyXDataSocket::writeln(string const & line)
290 string linen(line + '\n');
291 int size = linen.size();
292 int written = ::write(fd_, linen.c_str(), size);
293 if (written < size) { // Allways mean end of connection.
294 if ((written == -1) && (errno == EPIPE)) {
295 // The program will also receive a SIGPIPE
296 // that must be catched
297 cerr << "lyxclient: connection closed while writing."
300 // Anything else, including errno == EAGAIN, must be
301 // considered IO error. EAGAIN should never happen
302 // when line is small
303 cerr << "lyxclient: IO error: " << strerror(errno);
308 // ~Class LyXDataSocket -------------------------------------------------------
311 // Class CmdLineParser -------------------------------------------------------
312 class CmdLineParser {
314 typedef int (*optfunc)(vector<char *> const & args);
315 std::map<string, optfunc> helper;
316 std::map<string, bool> isset;
317 bool parse(int, char * []);
318 vector<char *> nonopt;
322 bool CmdLineParser::parse(int argc, char * argv[])
327 if (helper[argv[opt]]) {
328 isset[argv[opt]] = true;
330 while ((arg < argc) && (!helper[argv[arg]])) {
331 args.push_back(argv[arg]);
334 int taken = helper[argv[opt]](args);
339 if (argv[opt][0] == '-') {
340 if ((argv[opt][1] == '-')
341 && (argv[opt][2]== '\0')) {
344 nonopt.push_back(argv[opt]);
349 cerr << "lyxclient: unknown option "
350 << argv[opt] << endl;
354 nonopt.push_back(argv[opt]);
360 // ~Class CmdLineParser -------------------------------------------------------
368 cerr << "Usage: lyxclient [options]" << endl
369 << "Options are:" << endl
370 << " -a address set address of the lyx socket" << endl
371 << " -t directory set system temporary directory" << endl
372 << " -p pid select a running lyx by pid" << endl
373 << " -c command send a single command and quit" << endl
374 << " -g file row send a command to go to file and row" << endl
375 << " -n name set client name" << endl
376 << " -h name display this help end exit" << endl
377 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
378 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
379 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
380 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
381 << "will read commands from standard input and disconnect when command read is BYE:"
386 int h(vector<char *> const &)
393 string clientName(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
395 int n(vector<char *> const & arg)
397 if (arg.size() < 1) {
398 cerr << "lyxclient: The option -n requires 1 argument."
407 string singleCommand;
410 int c(vector<char *> const & arg)
412 if (arg.size() < 1) {
413 cerr << "lyxclient: The option -c requires 1 argument."
417 singleCommand = arg[0];
422 int g(vector<char *> const & arg)
424 if (arg.size() < 2) {
425 cerr << "lyxclient: The option -g requires 2 arguments."
429 singleCommand = "LYXCMD:server-goto-file-row "
430 + string(arg[0]) + ' '
436 // 0 if LYXSOCKET is not set in the environment
437 char * serverAddress = getenv("LYXSOCKET");
440 int a(vector<char *> const & arg)
442 if (arg.size() < 1) {
443 cerr << "lyxclient: The option -a requires 1 argument."
447 // -a supercedes LYXSOCKET environment variable
448 serverAddress = arg[0];
453 string mainTmp("/tmp");
456 int t(vector<char *> const & arg)
458 if (arg.size() < 1) {
459 cerr << "lyxclient: The option -t requires 1 argument."
468 string serverPid; // Init to empty string
471 int p(vector<char *> const & arg)
473 if (arg.size() < 1) {
474 cerr << "lyxclient: The option -p requires 1 argument."
483 } // namespace cmdline
489 int main(int argc, char * argv[])
491 lyxerr.rdbuf(cerr.rdbuf());
494 args.helper["-h"] = cmdline::h;
495 args.helper["-c"] = cmdline::c;
496 args.helper["-g"] = cmdline::g;
497 args.helper["-n"] = cmdline::n;
498 args.helper["-a"] = cmdline::a;
499 args.helper["-t"] = cmdline::t;
500 args.helper["-p"] = cmdline::p;
502 // Command line failure conditions:
503 if ((!args.parse(argc, argv))
504 || (args.isset["-c"] && args.isset["-g"])
505 || (args.isset["-a"] && args.isset["-p"])) {
510 scoped_ptr<LyXDataSocket> server;
512 if (cmdline::serverAddress) {
513 server.reset(new LyXDataSocket(cmdline::serverAddress));
514 if (!server->connected()) {
515 cerr << "lyxclient: " << "Could not connect to "
516 << cmdline::serverAddress << endl;
520 // We have to look for an address.
521 // serverPid can be empty.
522 vector<fs::path> addrs = support::lyxSockets(cmdline::mainTmp, cmdline::serverPid);
523 vector<fs::path>::const_iterator addr = addrs.begin();
524 vector<fs::path>::const_iterator end = addrs.end();
525 for (; addr != end; ++addr) {
526 server.reset(new LyXDataSocket(addr->string()));
527 if (server->connected())
529 lyxerr << "lyxclient: " << "Could not connect to "
530 << addr->string() << endl;
533 lyxerr << "lyxclient: No suitable server found."
537 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
540 int const serverfd = server->fd();
543 iowatch.addfd(serverfd);
545 // Used to read from server
549 server->writeln("HELLO:" + cmdline::clientName);
550 // wait at most 2 seconds until server responds
552 if (iowatch.isset(serverfd) && server->readln(answer)) {
553 if (prefixIs(answer, "BYE:")) {
554 cerr << "lyxclient: Server disconnected." << endl;
555 cout << answer << endl;
559 cerr << "lyxclient: No answer from server." << endl;
563 if (args.isset["-g"] || args.isset["-c"]) {
564 server->writeln(cmdline::singleCommand);
566 if (iowatch.isset(serverfd) && server->readln(answer)) {
568 if (prefixIs(answer, "ERROR:"))
572 cerr << "lyxclient: No answer from server." << endl;
577 // Take commands from stdin
578 iowatch.addfd(0); // stdin
579 bool saidbye = false;
580 while ((!saidbye) && server->connected()) {
582 if (iowatch.isset(0)) {
585 if (command == "BYE:") {
586 server->writeln("BYE:");
589 server->writeln("LYXCMD:" + command);
592 if (iowatch.isset(serverfd)) {
593 while(server->readln(answer))
594 cout << answer << endl;