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/unicode.h"
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 #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>
60 using lyx::support::prefixIs;
62 using boost::scoped_ptr;
63 namespace fs = boost::filesystem;
73 IconvProcessor & utf8ToUcs4()
75 static IconvProcessor iconv(ucs4_codeset, "UTF-8");
82 string itoa(unsigned int i)
84 return boost::lexical_cast<string>(i);
88 // Parts stolen from lyx::support::DirList()
89 // Returns the absolute pathnames of all lyx local sockets
90 vector<fs::path> lyxSockets(string const & dir, string const & pid)
92 vector<fs::path> dirlist;
94 fs::path dirpath(dir);
96 if (!fs::exists(dirpath) || !fs::is_directory(dirpath)) {
97 lyxerr << dir << " does not exist or is not a directory."
102 fs::directory_iterator beg((fs::path(dir)));
103 fs::directory_iterator end;
105 for (; beg != end; ++beg) {
106 if (prefixIs(beg->leaf(), "lyx_tmpdir" + pid)) {
107 fs::path lyxsocket = beg->path() / "lyxsocket";
108 if (fs::exists(lyxsocket)) {
109 dirlist.push_back(lyxsocket);
118 namespace socktools {
121 int connect(string const & name)
123 int fd; // File descriptor for the socket
124 sockaddr_un addr; // Structure that hold the socket address
126 // char sun_path[108]
127 string::size_type len = name.size();
129 cerr << "lyxclient: Socket address '" << name
130 << "' too long." << endl;
133 // Synonims for AF_UNIX are AF_LOCAL and AF_FILE
134 addr.sun_family = AF_UNIX;
135 name.copy(addr.sun_path, 107);
136 addr.sun_path[len] = '\0';
138 if ((fd = ::socket(PF_UNIX, SOCK_STREAM, 0))== -1) {
139 cerr << "lyxclient: Could not create socket descriptor: "
140 << strerror(errno) << endl;
144 reinterpret_cast<struct sockaddr *>(&addr),
145 sizeof(addr)) == -1) {
146 cerr << "lyxclient: Could not connect to socket " << name
147 << ": " << strerror(errno) << endl;
151 if (::fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
152 cerr << "lyxclient: Could not set O_NONBLOCK for socket: "
153 << strerror(errno) << endl;
161 } // namespace socktools
162 } // namespace support
166 // Class IOWatch ------------------------------------------------------------
187 void IOWatch::clear()
193 void IOWatch::addfd(int fd)
199 bool IOWatch::wait(double timeout)
202 to.tv_sec = static_cast<long int>(timeout);
203 to.tv_usec = static_cast<long int>((timeout - to.tv_sec)*1E6);
205 return select(FD_SETSIZE, &act,
206 (fd_set *)0, (fd_set *)0, &to);
213 return select(FD_SETSIZE, &act,
214 (fd_set *)0, (fd_set *)0, (timeval *)0);
218 bool IOWatch::isset(int fd) {
219 return FD_ISSET(fd, &act);
221 // ~Class IOWatch ------------------------------------------------------------
224 // Class LyXDataSocket -------------------------------------------------------
225 // Modified LyXDataSocket class for use with the client
226 class LyXDataSocket {
228 LyXDataSocket(string const &);
230 // File descriptor of the connection
233 bool connected() const;
234 // Line buffered input from the socket
235 bool readln(string &);
236 // Write the string + '\n' to the socket
237 void writeln(string const &);
239 // File descriptor for the data socket
241 // True if the connection is up
243 // buffer for input data
248 LyXDataSocket::LyXDataSocket(string const & address)
250 if ((fd_ = support::socktools::connect(address)) == -1) {
258 LyXDataSocket::~LyXDataSocket()
264 int LyXDataSocket::fd() const
270 bool LyXDataSocket::connected() const
276 // Returns true if there was a complete line to input
277 // A line is of the form <key>:<value>
278 // A line not of this form will not be passed
279 // The line read is splitted and stored in 'key' and 'value'
280 bool LyXDataSocket::readln(string & line)
282 int const charbuf_size = 100;
283 char charbuf[charbuf_size]; // buffer for the ::read() system call
285 string::size_type pos;
287 // read and store characters in buffer
288 while ((count = ::read(fd_, charbuf, charbuf_size - 1)) > 0) {
289 charbuf[count] = '\0'; // turn it into a c string
293 // Error conditions. The buffer must still be
294 // processed for lines read
295 if (count == 0) { // EOF -- connection closed
297 } else if ((count == -1) && (errno != EAGAIN)) { // IO error
298 cerr << "lyxclient: IO error." << endl;
302 // Cut a line from buffer
303 if ((pos = buffer.find('\n')) == string::npos)
304 return false; // No complete line stored
305 line = buffer.substr(0, pos);
306 buffer = buffer.substr(pos + 1);
311 // Write a line of the form <key>:<value> to the socket
312 void LyXDataSocket::writeln(string const & line)
314 string linen(line + '\n');
315 int size = linen.size();
316 int written = ::write(fd_, linen.c_str(), size);
317 if (written < size) { // Allways mean end of connection.
318 if ((written == -1) && (errno == EPIPE)) {
319 // The program will also receive a SIGPIPE
320 // that must be catched
321 cerr << "lyxclient: connection closed while writing."
324 // Anything else, including errno == EAGAIN, must be
325 // considered IO error. EAGAIN should never happen
326 // when line is small
327 cerr << "lyxclient: IO error: " << strerror(errno);
332 // ~Class LyXDataSocket -------------------------------------------------------
335 // Class CmdLineParser -------------------------------------------------------
336 class CmdLineParser {
338 typedef int (*optfunc)(vector<char *> const & args);
339 std::map<string, optfunc> helper;
340 std::map<string, bool> isset;
341 bool parse(int, char * []);
342 vector<char *> nonopt;
346 bool CmdLineParser::parse(int argc, char * argv[])
351 if (helper[argv[opt]]) {
352 isset[argv[opt]] = true;
354 while ((arg < argc) && (!helper[argv[arg]])) {
355 args.push_back(argv[arg]);
358 int taken = helper[argv[opt]](args);
363 if (argv[opt][0] == '-') {
364 if ((argv[opt][1] == '-')
365 && (argv[opt][2]== '\0')) {
368 nonopt.push_back(argv[opt]);
373 cerr << "lyxclient: unknown option "
374 << argv[opt] << endl;
378 nonopt.push_back(argv[opt]);
384 // ~Class CmdLineParser -------------------------------------------------------
392 cerr << "Usage: lyxclient [options]" << endl
393 << "Options are:" << endl
394 << " -a address set address of the lyx socket" << endl
395 << " -t directory set system temporary directory" << endl
396 << " -p pid select a running lyx by pid" << endl
397 << " -c command send a single command and quit" << endl
398 << " -g file row send a command to go to file and row" << endl
399 << " -n name set client name" << endl
400 << " -h name display this help end exit" << endl
401 << "If -a is not used, lyxclient will use the arguments of -t and -p to look for" << endl
402 << "a running lyx. If -t is not set, 'directory' defaults to /tmp. If -p is set," << endl
403 << "lyxclient will connect only to a lyx with the specified pid. Options -c and -g" << endl
404 << "cannot be set simultaneoulsly. If no -c or -g options are given, lyxclient" << endl
405 << "will read commands from standard input and disconnect when command read is BYE:"
410 int h(vector<char *> const &)
417 string clientName(support::itoa(::getppid()) + ">" + support::itoa(::getpid()));
419 int n(vector<char *> const & arg)
421 if (arg.size() < 1) {
422 cerr << "lyxclient: The option -n requires 1 argument."
431 string singleCommand;
434 int c(vector<char *> const & arg)
436 if (arg.size() < 1) {
437 cerr << "lyxclient: The option -c requires 1 argument."
441 singleCommand = arg[0];
446 int g(vector<char *> const & arg)
448 if (arg.size() < 2) {
449 cerr << "lyxclient: The option -g requires 2 arguments."
453 singleCommand = "LYXCMD:server-goto-file-row "
454 + string(arg[0]) + ' '
460 // 0 if LYXSOCKET is not set in the environment
461 char * serverAddress = getenv("LYXSOCKET");
464 int a(vector<char *> const & arg)
466 if (arg.size() < 1) {
467 cerr << "lyxclient: The option -a requires 1 argument."
471 // -a supercedes LYXSOCKET environment variable
472 serverAddress = arg[0];
477 string mainTmp("/tmp");
480 int t(vector<char *> const & arg)
482 if (arg.size() < 1) {
483 cerr << "lyxclient: The option -t requires 1 argument."
492 string serverPid; // Init to empty string
495 int p(vector<char *> const & arg)
497 if (arg.size() < 1) {
498 cerr << "lyxclient: The option -p requires 1 argument."
507 } // namespace cmdline
512 int main(int argc, char * argv[])
515 lyxerr.rdbuf(cerr.rdbuf());
518 args.helper["-h"] = cmdline::h;
519 args.helper["-c"] = cmdline::c;
520 args.helper["-g"] = cmdline::g;
521 args.helper["-n"] = cmdline::n;
522 args.helper["-a"] = cmdline::a;
523 args.helper["-t"] = cmdline::t;
524 args.helper["-p"] = cmdline::p;
526 // Command line failure conditions:
527 if ((!args.parse(argc, argv))
528 || (args.isset["-c"] && args.isset["-g"])
529 || (args.isset["-a"] && args.isset["-p"])) {
534 scoped_ptr<LyXDataSocket> server;
536 if (cmdline::serverAddress) {
537 server.reset(new LyXDataSocket(cmdline::serverAddress));
538 if (!server->connected()) {
539 cerr << "lyxclient: " << "Could not connect to "
540 << cmdline::serverAddress << endl;
544 // We have to look for an address.
545 // serverPid can be empty.
546 vector<fs::path> addrs = support::lyxSockets(cmdline::mainTmp, cmdline::serverPid);
547 vector<fs::path>::const_iterator addr = addrs.begin();
548 vector<fs::path>::const_iterator end = addrs.end();
549 for (; addr != end; ++addr) {
550 server.reset(new LyXDataSocket(addr->string()));
551 if (server->connected())
553 lyxerr << "lyxclient: " << "Could not connect to "
554 << addr->string() << endl;
557 lyxerr << "lyxclient: No suitable server found."
561 cerr << "lyxclient: " << "Connected to " << addr->string() << endl;
564 int const serverfd = server->fd();
567 iowatch.addfd(serverfd);
569 // Used to read from server
573 server->writeln("HELLO:" + cmdline::clientName);
574 // wait at most 2 seconds until server responds
576 if (iowatch.isset(serverfd) && server->readln(answer)) {
577 if (prefixIs(answer, "BYE:")) {
578 cerr << "lyxclient: Server disconnected." << endl;
579 cout << answer << endl;
583 cerr << "lyxclient: No answer from server." << endl;
587 if (args.isset["-g"] || args.isset["-c"]) {
588 server->writeln(cmdline::singleCommand);
590 if (iowatch.isset(serverfd) && server->readln(answer)) {
592 if (prefixIs(answer, "ERROR:"))
596 cerr << "lyxclient: No answer from server." << endl;
601 // Take commands from stdin
602 iowatch.addfd(0); // stdin
603 bool saidbye = false;
604 while ((!saidbye) && server->connected()) {
606 if (iowatch.isset(0)) {
609 if (command == "BYE:") {
610 server->writeln("BYE:");
613 server->writeln("LYXCMD:" + command);
616 if (iowatch.isset(serverfd)) {
617 while(server->readln(answer))
618 cout << answer << endl;
628 void assertion_failed(char const* a, char const* b, char const* c, long d)
630 lyx::lyxerr << "Assertion failed: " << a << ' ' << b << ' ' << c << ' '