Scheduler: Implement PollTimerSource
[senf.git] / Utils / Daemon / Daemon.cc
1 // $Id$
2 //
3 // Copyright (C) 2007
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \file
24     \brief Daemon non-inline non-template implementation */
25
26 #include "Daemon.hh"
27 #include "Daemon.ih"
28
29 // Custom includes
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <unistd.h>
34 #include <limits.h>
35 #include <fcntl.h>
36 #include <errno.h>
37 #include <signal.h>
38 #include <execinfo.h>
39 #include <sstream>
40 #include <algorithm>
41 #include <boost/algorithm/string/predicate.hpp>
42 #include <boost/algorithm/string/trim.hpp>
43 #include <boost/format.hpp>
44 #include "../Exception.hh"
45 #include "../membind.hh"
46 #include "../Backtrace.hh"
47 #include "../signalnames.hh"
48
49 // #define __USE_GNU
50 #include <ucontext.h>
51
52 //#include "Daemon.mpp"
53 #define prefix_
54 ///////////////////////////////cc.p////////////////////////////////////////
55
56 #define LIBC_CALL(fn, args) if (fn args < 0) \
57     SENF_THROW_SYSTEM_EXCEPTION(#fn "()")
58
59 #define LIBC_CALL_RV(var, fn, args) \
60     int var (fn args); if (var < 0) SENF_THROW_SYSTEM_EXCEPTION(#fn "()")
61
62 ///////////////////////////////////////////////////////////////////////////
63 // senf::Daemon
64
65 prefix_ senf::Daemon::~Daemon()
66 {
67     if (pidfileCreated_) {
68         try {
69             LIBC_CALL( ::unlink, (pidfile_.c_str()) );
70         } catch (Exception e) {
71             // e << "; could not unlink " << pidfile_.c_str();
72             // throw;
73         }
74     }
75 }
76
77 prefix_ void senf::Daemon::daemonize(bool v)
78 {
79     daemonize_ = v;
80 }
81
82 prefix_ bool senf::Daemon::daemon()
83 {
84     return daemonize_;
85 }
86
87 prefix_ int senf::Daemon::argc() 
88 {
89     return argc_;
90 }
91
92 prefix_ char const ** senf::Daemon::argv() 
93 {
94     return argv_;
95 }
96
97 namespace {
98
99     struct IsDaemonOpt {
100         bool operator()(std::string const & str) const {
101             return str == "--no-daemon"
102                 || boost::starts_with(str, std::string("--pid-file="))
103                 || boost::starts_with(str, std::string("--console-log="));
104         }
105     };
106 }
107
108 prefix_ void senf::Daemon::removeDaemonArgs()
109 {
110     char const ** last (std::remove_if(argv_+1, argv_+argc_, IsDaemonOpt()));
111     *last = 0;
112     argc_ = last - argv_;
113 }
114
115 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
116 {
117     switch (which) {
118     case StdOut : stdoutLog_ = path; break;
119     case StdErr : stderrLog_ = path; break;
120     case Both : stdoutLog_ = path; stderrLog_ = path; break;
121     }
122 }
123
124
125 prefix_ void senf::Daemon::openLog()
126 {
127     int fd (-1);
128     if (! stdoutLog_.empty()) {
129         fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
130         if (fd < 0)
131             SENF_THROW_SYSTEM_EXCEPTION("")
132                   << " Could not open \"" << stdoutLog_ << "\" for redirecting stdout.";
133         stdout_ = fd;
134     }
135     if (stderrLog_ == stdoutLog_) {
136         stderr_ = ::dup(fd);
137         if (stderr_ < 0)
138             SENF_THROW_SYSTEM_EXCEPTION("::dup()");
139     } 
140     else if (! stderrLog_.empty()) {
141         fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
142         if (fd < 0)
143             SENF_THROW_SYSTEM_EXCEPTION("")
144                   << " Could not open \"" << stderrLog_ << "\" for redirecting stderr.";
145         stderr_ = fd;
146     }
147 }
148
149 prefix_ void senf::Daemon::logReopen()
150 {
151     if (! stdoutLog_.empty()) {
152         int fd (::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
153         if (fd < 0) 
154             goto error;
155         if (::dup2(fd, 1) < 0) 
156             goto error;
157         if (stderrLog_ == stdoutLog_) {
158             if (::dup2(fd, 2) < 0) 
159                 goto error;
160             return;
161         }
162     }
163     if (! stderrLog_.empty()) {
164         int fd (::open(stderrLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
165         if (fd < 0) 
166             goto error;
167         if (::dup2(fd, 2) < 0) 
168             goto error;
169     }
170     return;
171
172  error:
173     SENF_LOG(
174         (senf::log::CRITICAL)
175         ("log-file reopen failed: (" << errno << ") " << ::strerror(errno)) );
176 }
177
178 prefix_ void senf::Daemon::pidFile(std::string const & f)
179 {
180     pidfile_ = f;
181 }
182
183 namespace {
184     bool signaled (false);
185     void waitusr(int) {
186         signaled = true;
187     }
188 }
189
190 prefix_ void senf::Daemon::detach()
191 {
192     if (daemonize_ && ! detached_) {
193         // Wow .. ouch .. 
194         // To ensure all data is written to the console log file in the correct order, we suspend
195         // execution here until the parent process tells us to continue via SIGUSR1: We block
196         // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
197         // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
198         // SIGUSR1 and reinstall the old signal mask and action.
199         ::sigset_t oldsig;
200         ::sigset_t usrsig;
201         ::sigemptyset(&usrsig);
202         LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
203         LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
204         struct ::sigaction oldact;
205         struct ::sigaction usract;
206         ::memset(&usract, 0, sizeof(usract));
207         usract.sa_handler = &waitusr;
208         LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
209         ::sigset_t waitsig (oldsig);
210         LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
211
212         LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
213         LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
214         LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
215         LIBC_CALL( ::close, (nul) );
216
217         signaled = false;
218         while (! signaled) {
219             ::sigsuspend(&waitsig);
220             if (errno != EINTR)
221                 SENF_THROW_SYSTEM_EXCEPTION("::sigsuspend()");
222         }
223
224         LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
225         LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
226
227         detached_ = true;
228     }
229 }
230
231 namespace {
232     /* Purposely *not* derived from std::exception */
233     struct DaemonExitException {
234         DaemonExitException(unsigned c) : code(c) {}
235         unsigned code;
236     };
237 }
238
239 prefix_ void senf::Daemon::exit(unsigned code)
240 {
241     throw DaemonExitException(code);
242 }
243
244 prefix_ int senf::Daemon::start(int argc, char const ** argv)
245 {
246     argc_ = argc;
247     argv_ = argv;
248
249     try {
250         configure();
251
252         if (daemonize_) {
253             openLog();
254             fork();
255         }
256         installSighandlers();
257         if (! pidfile_.empty()) {
258             if (pidfileCreate())
259                 pidfileCreated_ = true;
260             else {
261                 std::cerr << "PID file '" << pidfile_ 
262                           << "' creation failed. Daemon running ?" << std::endl;
263                 return 1;
264             }
265         }
266
267         main();
268     }
269     catch (DaemonExitException & e) {
270         return e.code;
271     }
272
273 #ifndef SENF_DEBUG
274
275     catch (std::exception & e) {
276         std::cerr << "\n*** Fatal exception: " << e.what() << "\n" << std::endl;
277         return 1;
278     }
279     catch (...) {
280         std::cerr << "\n*** Fatal exception: (unknown)" << "\n" << std::endl;
281         return 1;
282     }
283
284 #   endif
285
286     return 0;
287 }
288
289 prefix_ senf::Daemon & senf::Daemon::instance()
290 {
291     BOOST_ASSERT( instance_ );
292     return *instance_;
293 }
294
295 ////////////////////////////////////////
296 // protected members
297
298 prefix_ senf::Daemon::Daemon()
299     : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
300       pidfileCreated_(false), detached_(false)
301 {
302     BOOST_ASSERT( ! instance_ );
303     instance_ = this;
304 }
305
306 senf::Daemon * senf::Daemon::instance_ (0);
307
308 ////////////////////////////////////////
309 // private members
310
311 prefix_ void senf::Daemon::configure()
312 {
313     // int i (not unsigned) since argc_ is int ...
314     for (int i (1); i<argc_; ++i) {
315         if (argv_[i] == std::string("--no-daemon"))
316             daemonize(false);
317         else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
318             std::string arg (std::string(argv_[i]), 14u);
319             std::string::size_type komma (arg.find(','));
320             if (komma == std::string::npos) {
321                 boost::trim(arg);
322                 if (arg == std::string("none")) consoleLog("");
323                 else if (!arg.empty())          consoleLog(arg);
324             } else {
325                 std::string arg1 (arg,0,komma);
326                 std::string arg2 (arg,komma+1);
327                 boost::trim(arg1);
328                 boost::trim(arg2);
329                 if (arg1 == std::string("none")) consoleLog("",StdOut);
330                 else if (! arg1.empty() )        consoleLog(arg1, StdOut);
331                 if (arg2 == std::string("none")) consoleLog("",StdErr);
332                 else if (! arg2.empty() )        consoleLog(arg2, StdErr);
333             }
334         }
335         else if (boost::starts_with(argv_[i], std::string("--pid-file="))) 
336             pidFile(std::string(std::string(argv_[i]), 11u));
337     }
338 }
339
340 prefix_ void senf::Daemon::main()
341 {
342     init();
343     detach();
344     run();
345 }
346
347 prefix_ void senf::Daemon::init()
348 {}
349
350 prefix_ void senf::Daemon::run()
351 {}
352
353 prefix_ void senf::Daemon::fork()
354 {
355     int coutpipe[2];
356     int cerrpipe[2];
357
358     LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
359     LIBC_CALL( ::dup2, (nul, 0) );
360     LIBC_CALL( ::close, (nul) );
361     LIBC_CALL( ::pipe, (coutpipe) );
362     LIBC_CALL( ::pipe, (cerrpipe) );
363
364     // We need to block the SIGCHLD signal here so we don't miss it, if the child
365     // dies immediately
366     ::sigset_t oldsig;
367     ::sigset_t cldsig;
368     ::sigemptyset(&cldsig);
369     LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
370     LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
371
372     if (! senf::scheduler::empty() )
373         std::cerr << 
374             "\n"
375             "*** WARNING ***\n"
376             "Scheduler not empty before fork(). THIS MUST NOT HAPPEN.\n"
377             "The scheduler will be reinitialized by the fork() and lose all registrations.\n"
378             "*** WARNING ***\n"
379             "\n";
380     
381     LIBC_CALL_RV( pid, ::fork, () );
382
383     if (pid == 0) {
384         // Daemon process
385
386         LIBC_CALL( ::dup2, (coutpipe[1],1) );
387         LIBC_CALL( ::dup2, (cerrpipe[1],2) );
388         LIBC_CALL( ::close, (coutpipe[0]) );
389         LIBC_CALL( ::close, (coutpipe[1]) );
390         LIBC_CALL( ::close, (cerrpipe[0]) );
391         LIBC_CALL( ::close, (cerrpipe[1]) );
392         LIBC_CALL( ::setsid, () );
393         LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
394
395         senf::scheduler::restart();
396         return;
397     }
398
399     // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
400     pidfile_ = "";
401     
402     LIBC_CALL( ::close, (coutpipe[1]) );
403     LIBC_CALL( ::close, (cerrpipe[1]) );
404
405     senf::scheduler::restart();
406
407     detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
408     watcher.run();
409
410     ::_exit(0);
411 }
412
413 prefix_ bool senf::Daemon::pidfileCreate()
414 {
415     // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
416     // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
417     // was some race condition, probably over NFS.
418
419     std::string tempname;
420     boost::format linkErrorFormat(" Could not link \"%1%\" to \"%2%\".");
421
422     {
423         char hostname[HOST_NAME_MAX+1];
424         LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
425         hostname[HOST_NAME_MAX] = 0;
426         std::stringstream tempname_s;
427         tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
428         tempname = tempname_s.str();
429     }
430
431     while (1) {
432         {
433             std::ofstream pidf (tempname.c_str());
434             if (! pidf)
435                 SENF_THROW_SYSTEM_EXCEPTION("")
436                       << " Could not open pidfile \"" << tempname << "\" for output.";
437             pidf << ::getpid() << std::endl;
438             if (! pidf)
439                 SENF_THROW_SYSTEM_EXCEPTION("")
440                       << " Could not write to pidfile \"" << tempname << "\".";
441         }
442
443         if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
444             if (errno != EEXIST) 
445                 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % pidfile_ % tempname;
446         }
447         else {
448             struct ::stat s;
449             LIBC_CALL( ::stat, (tempname.c_str(), &s) );
450             LIBC_CALL( ::unlink, (tempname.c_str()) );
451             return s.st_nlink == 2;
452         }
453
454         // pidfile exists. Check, whether the pid in the pidfile still exists.
455         {
456             int old_pid (-1);
457             std::ifstream pidf (pidfile_.c_str());
458             if ( ! (pidf >> old_pid)
459                  || old_pid < 0 
460                  || ::kill(old_pid, 0) >= 0 
461                  || errno == EPERM ) {
462                 LIBC_CALL( ::unlink, (tempname.c_str()) );
463                 return false;
464             }
465         }
466
467         // If we reach this point, the pid file exists but the process mentioned within the
468         // pid file does *not* exists. We assume, the pid file to be stale.
469
470         // I hope, the following procedure is without race condition: We remove our generated
471         // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
472         // the hard-link count of this file is 2. If it is not, we terminate, since someone else
473         // must have already created his hardlink. We then truncate the file and write our pid.
474
475         LIBC_CALL( ::unlink, (tempname.c_str() ));
476         if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
477             if (errno != ENOENT)
478                 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % tempname % pidfile_;
479             // Hmm ... the pidfile mysteriously disappeared ... try again.
480             continue;
481         }
482
483         {
484             struct ::stat s;
485             LIBC_CALL( ::stat, (tempname.c_str(), &s) );
486             if (s.st_nlink != 2) {
487                 LIBC_CALL( ::unlink, (tempname.c_str()) );
488                 return false;
489             }
490         }
491         
492         {
493             std::ofstream pidf (tempname.c_str());
494             pidf << ::getpid() << std::endl;
495         }
496
497         LIBC_CALL( ::unlink, (tempname.c_str()) );
498         break;
499     }
500     return true;
501 }
502
503
504 #ifdef SENF_DEBUG
505
506 namespace {
507     void fatalSignalsHandler(int sig, ::siginfo_t * info, void * arg)
508     {
509         // ::ucontext_t * ucontext = static_cast<ucontext_t*>(arg);
510         std::cerr << "\n" << "Signal " << senf::signalName(sig) << '(' << sig << ')'
511                   << " received\n";
512
513         if (sig == SIGSEGV)
514             std::cerr << "Invalid memory access at " << info->si_addr << "\n";
515
516         static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
517         unsigned nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
518
519         // Hack the callers address into the backtrace
520         // entries[1] = reinterpret_cast<void *>(ucontext->uc_mcontext.gregs[REG_EIP]);
521
522         std::cerr << "Backtrace:\n";
523         senf::formatBacktrace(std::cerr, entries, nEntries);
524         std::cerr << "-- \n";
525
526         if (sig != SIGUSR2) {
527             ::signal(sig, SIG_DFL);
528             ::kill(::getpid(), sig);
529         }
530     }
531
532 }
533
534 #endif
535
536 namespace {
537     void sighupHandler(int sig)
538     {
539         senf::Daemon::instance().logReopen();
540     }
541 }
542
543 prefix_ void senf::Daemon::installSighandlers()
544 {
545     struct ::sigaction sa;
546
547     ::sigemptyset(&sa.sa_mask);
548     sa.sa_handler = &sighupHandler;
549     sa.sa_flags = SA_RESTART;
550
551     ::sigaction(SIGHUP,   &sa, NULL);
552
553     sa.sa_handler = SIG_IGN;
554     ::sigaction(SIGPIPE, &sa, NULL);
555
556 #ifdef SENF_DEBUG
557     sa.sa_sigaction = &fatalSignalsHandler;
558     sa.sa_flags = SA_RESTART | SA_SIGINFO;
559
560     ::sigaction(SIGILL,    &sa, NULL);
561     ::sigaction(SIGTRAP,   &sa, NULL);
562     ::sigaction(SIGABRT,   &sa, NULL);
563     ::sigaction(SIGFPE,    &sa, NULL);
564     ::sigaction(SIGBUS,    &sa, NULL);
565     ::sigaction(SIGSEGV,   &sa, NULL);
566     ::sigaction(SIGSTKFLT, &sa, NULL);
567     ::sigaction(SIGSYS,    &sa, NULL);
568     ::sigaction(SIGUSR2,   &sa, NULL);
569 #endif
570 }
571
572 ///////////////////////////////////////////////////////////////////////////
573 // senf::detail::DaemonWatcher
574
575 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
576                                                    int stdout, int stderr)
577     : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
578       stderr_(stderr), sigChld_(false),
579       cldSignal_ (SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this)),
580       timer_ ("senf::detail::DaemonWatcher::childOk", senf::membind(&DaemonWatcher::childOk, this)),
581       coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)), 
582       cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2)) 
583 {
584     coutForwarder_.addTarget(1);
585     if (stdout_ >= 0)
586         coutForwarder_.addTarget(stdout_);
587     cerrForwarder_.addTarget(2);
588     if (stderr_ >= 0)
589         cerrForwarder_.addTarget(stderr_);
590 }
591
592 prefix_ void senf::detail::DaemonWatcher::run()
593 {
594     scheduler::process();
595 }
596
597 ////////////////////////////////////////
598 // private members
599
600 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
601 {
602     switch (id) {
603     case 1 : coutpipe_ = -1; break;
604     case 2 : cerrpipe_ = -1; break;
605     }
606
607     if (coutpipe_ == -1 && cerrpipe_ == -1) {
608         if (sigChld_)
609             childDied(); // does not return
610         if (::kill(childPid_, SIGUSR1) < 0 && errno != ESRCH)
611             SENF_THROW_SYSTEM_EXCEPTION("::kill()");
612         timer_.timeout(scheduler::eventTime() + ClockService::seconds(1));
613     }
614 }
615
616 prefix_ void senf::detail::DaemonWatcher::sigChld(siginfo_t const &)
617 {
618     sigChld_ = true;
619     if (coutpipe_ == -1 && cerrpipe_ == -1)
620         childDied(); // does not return
621 }
622
623 prefix_ void senf::detail::DaemonWatcher::childDied()
624 {
625     int status (0);
626     if (::waitpid(childPid_,&status,0) < 0) SENF_THROW_SYSTEM_EXCEPTION("::waitpid()");
627     if (WIFSIGNALED(status)) {
628         ::signal(WTERMSIG(status),SIG_DFL);
629         ::kill(::getpid(), WTERMSIG(status));
630         // should not be reached
631         ::_exit(126);
632     }
633     if (WEXITSTATUS(status) == 0)
634         ::_exit(127);
635     ::_exit(WEXITSTATUS(status));
636 }
637
638 prefix_ void senf::detail::DaemonWatcher::childOk()
639 {
640     scheduler::terminate();
641 }
642
643 ///////////////////////////////////////////////////////////////////////////
644 // senf::detail::DaemonWatcher::Forwarder
645
646 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
647     : src_(src), cb_(cb), 
648       readevent_("senf::detail::DaemonWatcher::Forwarder::readevent", senf::membind(&Forwarder::readData, this),
649                  src_, scheduler::FdEvent::EV_READ)
650 {}
651
652 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
653 {
654     targets_.clear_and_destroy(DestroyDelete());
655 }
656
657 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
658 {
659     targets_.push_back(*(new Target(*this, fd)));
660 }
661
662 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(int event)
663 {
664     char buf[1024];
665     int n (0);
666
667     while (1) {
668         n = ::read(src_,buf,1024);
669         if (n<0) {
670             if (errno != EINTR) 
671                 SENF_THROW_SYSTEM_EXCEPTION("::read()");
672         } 
673         else 
674             break;
675     }
676
677     if (n == 0) {
678         if (buffer_.empty())
679             cb_(); 
680         src_ = -1;
681         readevent_.disable();
682         return;
683     }
684
685     if (targets_.empty())
686         return;
687
688     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
689         if (i->offset >= buffer_.size())
690             i->writeevent.enable();
691
692     buffer_.insert(buffer_.end(), buf, buf+n);
693 }
694
695 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(int event, Target * target)
696 {    
697     if (event != scheduler::FdEvent::EV_WRITE) {
698         // Broken pipe while writing data ? Not much, we can do here, we just drop the data
699         targets_.erase_and_destroy(Targets::current(*target),DestroyDelete());
700         if (targets_.empty() && src_ == -1)
701             cb_();
702         return;
703     }
704
705     char buf[1024];
706     int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
707     std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
708
709     int w (::write(target->fd, buf, n));
710     if (w < 0) {
711         if (errno != EINTR) SENF_THROW_SYSTEM_EXCEPTION("::write()");
712         return;
713     }
714     target->offset += w;
715
716     n = std::min_element(
717         targets_.begin(), targets_.end(),
718         boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
719
720     buffer_.erase(buffer_.begin(), buffer_.begin()+n);
721
722     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
723         i->offset -= n;
724
725     if (target->offset >= buffer_.size())
726         target->writeevent.disable();
727     if (src_ == -1 && (buffer_.empty() || targets_.empty()))
728         cb_();
729 }
730
731 #undef LIBC_CALL
732 #undef LIBC_CALL_RV
733
734 ///////////////////////////////cc.e////////////////////////////////////////
735 #undef prefix_
736 //#include "Daemon.mpp"
737
738 \f
739 // Local Variables:
740 // mode: c++
741 // fill-column: 100
742 // comment-column: 40
743 // c-file-style: "senf"
744 // indent-tabs-mode: nil
745 // ispell-local-dictionary: "american"
746 // compile-command: "scons -u test"
747 // End: