Subversion Repositories public

Rev

Rev 65 | Rev 69 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
45 luk 1
 
2
/// inotify cron daemon user tables implementation
3
/**
4
 * \file usertable.cpp
5
 *
6
 * inotify cron system
7
 *
63 luk 8
 * Copyright (C) 2006, 2007 Lukas Jelinek, <lukas@aiken.cz>
45 luk 9
 *
10
 * This program is free software; you can use it, redistribute
11
 * it and/or modify it under the terms of the GNU General Public
12
 * License, version 2 (see LICENSE-GPL).
13
 *  
14
 */
15
 
16
 
17
#include <pwd.h>
18
#include <syslog.h>
19
#include <errno.h>
47 luk 20
#include <sys/wait.h>
65 luk 21
#include <unistd.h>
22
#include <grp.h>
23
#include <sys/stat.h>
45 luk 24
 
25
#include "usertable.h"
26
 
65 luk 27
#ifdef IN_DONT_FOLLOW
67 luk 28
#define DONT_FOLLOW(mask) InotifyEvent::IsType(mask, IN_DONT_FOLLOW)
65 luk 29
#else // IN_DONT_FOLLOW
67 luk 30
#define DONT_FOLLOW(mask) (false)
65 luk 31
#endif // IN_DONT_FOLLOW
45 luk 32
 
65 luk 33
 
47 luk 34
PROC_LIST UserTable::s_procList;
35
 
67 luk 36
extern volatile bool g_fFinish;
37
extern SUT_MAP g_ut;
47 luk 38
 
67 luk 39
 
47 luk 40
void on_proc_done(InotifyWatch* pW)
41
{
42
  pW->SetEnabled(true);
43
}
44
 
45
 
67 luk 46
EventDispatcher::EventDispatcher(int iPipeFd, Inotify* pIn, InotifyWatch* pSys, InotifyWatch* pUser)
45 luk 47
{
67 luk 48
  m_iPipeFd = iPipeFd;
49
  m_iMgmtFd = pIn->GetDescriptor();
50
  m_pIn = pIn;
51
  m_pSys = pSys;
52
  m_pUser = pUser;
53
  m_size = 0;
54
  m_pPoll = NULL;
45 luk 55
}
56
 
67 luk 57
EventDispatcher::~EventDispatcher()
45 luk 58
{
67 luk 59
  if (m_pPoll != NULL)
60
    delete[] m_pPoll;
61
}
62
 
63
bool EventDispatcher::ProcessEvents()
64
{
65
  // consume pipe events if any (and report back)
66
  bool pipe = (m_pPoll[0].revents & POLLIN);
67
  if (pipe) {
68
    char c;
69
    while (read(m_pPoll[0].fd, &c, 1) > 0) {}
70
    m_pPoll[0].revents = 0;
71
  }
72
 
73
  // process table management events if any
74
  if (m_pPoll[1].revents & POLLIN) {
75
    ProcessMgmtEvents();
76
    m_pPoll[1].revents = 0;
77
  }
45 luk 78
 
67 luk 79
  InotifyEvent evt;
45 luk 80
 
67 luk 81
  for (size_t i=2; i<m_size; i++) {
45 luk 82
 
67 luk 83
    // process events if occurred
84
    if (m_pPoll[i].revents & POLLIN) {
85
      FDUT_MAP::iterator it = m_maps.find(m_pPoll[i].fd);
86
      if (it != m_maps.end()) {
87
        Inotify* pIn = ((*it).second)->GetInotify();
88
        pIn->WaitForEvents(true);
89
 
90
        // process events for this object
91
        while (pIn->GetEvent(evt)) {
92
          ((*it).second)->OnEvent(evt);
93
        }
94
      }
95
      m_pPoll[i].revents = 0;
96
    }
97
  }
98
 
99
  return pipe;
45 luk 100
}
101
 
67 luk 102
void EventDispatcher::Register(UserTable* pTab)
45 luk 103
{
67 luk 104
  if (pTab != NULL) {
105
    Inotify* pIn = pTab->GetInotify();
106
    if (pIn != NULL) {
107
      int fd = pIn->GetDescriptor();
108
      if (fd != -1) {
109
        m_maps.insert(FDUT_MAP::value_type(fd, pTab));
110
        Rebuild();
111
      }
112
    }
113
  }
45 luk 114
}
115
 
67 luk 116
void EventDispatcher::Unregister(UserTable* pTab)
45 luk 117
{
67 luk 118
  FDUT_MAP::iterator it = m_maps.find(pTab->GetInotify()->GetDescriptor());
119
  if (it != m_maps.end()) {
55 luk 120
    m_maps.erase(it);
67 luk 121
    Rebuild();
122
  }
45 luk 123
}
67 luk 124
 
125
void EventDispatcher::Rebuild()
126
{
127
  // delete old data if exists
128
  if (m_pPoll != NULL)
129
    delete[] m_pPoll;
130
 
131
  // allocate memory
132
  m_size = m_maps.size() + 2;
133
  m_pPoll = new struct pollfd[m_size];
45 luk 134
 
67 luk 135
  // add pipe descriptor
136
  m_pPoll[0].fd = m_iPipeFd;
137
  m_pPoll[0].events = POLLIN;
138
  m_pPoll[0].revents = 0;
139
 
140
  // add table management descriptor
141
  m_pPoll[1].fd = m_iMgmtFd;
142
  m_pPoll[1].events = POLLIN;
143
  m_pPoll[1].revents = 0;
144
 
145
  // add all inotify descriptors
146
  FDUT_MAP::iterator it = m_maps.begin();
147
  for (size_t i=2; i<m_size; i++, it++) {
148
    m_pPoll[i].fd = (*it).first;
149
    m_pPoll[i].events = POLLIN;
150
    m_pPoll[i].revents = 0;
151
  }
152
}
153
 
154
void EventDispatcher::ProcessMgmtEvents()
45 luk 155
{
67 luk 156
  m_pIn->WaitForEvents(true);
157
 
158
  InotifyEvent e;
159
 
160
  while (m_pIn->GetEvent(e)) {
161
    if (e.GetWatch() == m_pSys) {
162
      if (e.IsType(IN_DELETE_SELF) || e.IsType(IN_UNMOUNT)) {
163
        syslog(LOG_CRIT, "base directory destroyed, exitting");
164
        g_fFinish = true;
165
      }
166
      else if (!e.GetName().empty()) {
167
        SUT_MAP::iterator it = g_ut.find(m_pSys->GetPath() + e.GetName());
168
        if (it != g_ut.end()) {
169
          UserTable* pUt = (*it).second;
170
          if (e.IsType(IN_CLOSE_WRITE) || e.IsType(IN_MOVED_TO)) {
171
            syslog(LOG_INFO, "system table %s changed, reloading", e.GetName().c_str());
172
            pUt->Dispose();
173
            pUt->Load();
174
          }
175
          else if (e.IsType(IN_MOVED_FROM) || e.IsType(IN_DELETE)) {
176
            syslog(LOG_INFO, "system table %s destroyed, removing", e.GetName().c_str());
177
            delete pUt;
178
            g_ut.erase(it);
179
          }
180
        }
181
        else if (e.IsType(IN_CLOSE_WRITE) || e.IsType(IN_MOVED_TO)) {
182
          syslog(LOG_INFO, "system table %s created, loading", e.GetName().c_str());
183
          UserTable* pUt = new UserTable(this, e.GetName(), true);
184
          g_ut.insert(SUT_MAP::value_type(std::string(INCRON_SYS_TABLE_BASE) + e.GetName(), pUt));
185
          pUt->Load();
186
        }
187
      }
45 luk 188
    }
67 luk 189
    else if (e.GetWatch() == m_pUser) {
190
      if (e.IsType(IN_DELETE_SELF) || e.IsType(IN_UNMOUNT)) {
191
        syslog(LOG_CRIT, "base directory destroyed, exitting");
192
        g_fFinish = true;
193
      }
194
      else if (!e.GetName().empty()) {
195
        SUT_MAP::iterator it = g_ut.find(m_pUser->GetPath() + e.GetName());
196
        if (it != g_ut.end()) {
197
          UserTable* pUt = (*it).second;
198
          if (e.IsType(IN_CLOSE_WRITE) || e.IsType(IN_MOVED_TO)) {
199
            syslog(LOG_INFO, "table for user %s changed, reloading", e.GetName().c_str());
200
            pUt->Dispose();
201
            pUt->Load();
202
          }
203
          else if (e.IsType(IN_MOVED_FROM) || e.IsType(IN_DELETE)) {
204
            syslog(LOG_INFO, "table for user %s destroyed, removing",  e.GetName().c_str());
205
            delete pUt;
206
            g_ut.erase(it);
207
          }
208
        }
209
        else if (e.IsType(IN_CLOSE_WRITE) || e.IsType(IN_MOVED_TO)) {
210
          if (UserTable::CheckUser(e.GetName().c_str())) {
211
            syslog(LOG_INFO, "table for user %s created, loading", e.GetName().c_str());
212
            UserTable* pUt = new UserTable(this, e.GetName(), false);
213
            g_ut.insert(SUT_MAP::value_type(std::string(INCRON_USER_TABLE_BASE) + e.GetName(), pUt));
214
            pUt->Load();
215
          }
216
        }
217
      }
45 luk 218
    }
219
  }
220
}
221
 
222
 
223
 
224
 
67 luk 225
UserTable::UserTable(EventDispatcher* pEd, const std::string& rUser, bool fSysTable)
226
: m_user(rUser),
227
  m_fSysTable(fSysTable)
45 luk 228
{
229
  m_pEd = pEd;
67 luk 230
 
231
  m_in.SetNonBlock(true);
232
  m_in.SetCloseOnExec(true);
45 luk 233
}
234
 
235
UserTable::~UserTable()
236
{
237
  Dispose();
238
}
239
 
240
void UserTable::Load()
241
{
67 luk 242
  m_tab.Load(m_fSysTable
243
      ? InCronTab::GetSystemTablePath(m_user)
244
      : InCronTab::GetUserTablePath(m_user));
45 luk 245
 
246
  int cnt = m_tab.GetCount();
247
  for (int i=0; i<cnt; i++) {
248
    InCronTabEntry& rE = m_tab.GetEntry(i);
249
    InotifyWatch* pW = new InotifyWatch(rE.GetPath(), rE.GetMask());
65 luk 250
 
251
    // warning only - permissions may change later
67 luk 252
    if (!(m_fSysTable || MayAccess(rE.GetPath(), DONT_FOLLOW(rE.GetMask()))))
65 luk 253
      syslog(LOG_WARNING, "access denied on %s - events will be discarded silently", rE.GetPath().c_str());
254
 
47 luk 255
    try {
67 luk 256
      m_in.Add(pW);
47 luk 257
      m_map.insert(IWCE_MAP::value_type(pW, &rE));
258
    } catch (InotifyException e) {
67 luk 259
      if (m_fSysTable)
260
        syslog(LOG_ERR, "cannot create watch for system table %s: (%i) %s", m_user.c_str(), e.GetErrorNumber(), strerror(e.GetErrorNumber()));
261
      else
262
        syslog(LOG_ERR, "cannot create watch for user %s: (%i) %s", m_user.c_str(), e.GetErrorNumber(), strerror(e.GetErrorNumber()));
47 luk 263
      delete pW;
264
    }
45 luk 265
  }
67 luk 266
 
267
  m_pEd->Register(this);
45 luk 268
}
269
 
270
void UserTable::Dispose()
271
{
67 luk 272
  m_pEd->Unregister(this);
273
 
45 luk 274
  IWCE_MAP::iterator it = m_map.begin();
275
  while (it != m_map.end()) {
276
    InotifyWatch* pW = (*it).first;
67 luk 277
    m_in.Remove(pW);
45 luk 278
    delete pW;
279
    it++;
280
  }
281
 
282
  m_map.clear();
283
}
284
 
285
void UserTable::OnEvent(InotifyEvent& rEvt)
286
{
287
  InotifyWatch* pW = rEvt.GetWatch();
288
  InCronTabEntry* pE = FindEntry(pW);
289
 
65 luk 290
  // no entry found - this shouldn't occur
45 luk 291
  if (pE == NULL)
292
    return;
293
 
65 luk 294
  // discard event if user has no access rights to watch path
67 luk 295
  if (!(m_fSysTable || MayAccess(pW->GetPath(), DONT_FOLLOW(rEvt.GetMask()))))
65 luk 296
    return;
297
 
45 luk 298
  std::string cmd;
299
  const std::string& cs = pE->GetCmd();
300
  size_t pos = 0;
301
  size_t oldpos = 0;
302
  size_t len = cs.length();
303
  while ((pos = cs.find('$', oldpos)) != std::string::npos) {
304
    if (pos < len - 1) {
305
      size_t px = pos + 1;
306
      if (cs[px] == '$') {
307
        cmd.append(cs.substr(oldpos, pos-oldpos+1));
308
        oldpos = pos + 2;
309
      }
310
      else {
311
        cmd.append(cs.substr(oldpos, pos-oldpos));
55 luk 312
        if (cs[px] == '@') {          // base path
313
          cmd.append(pW->GetPath());
314
          oldpos = pos + 2;
315
        }
316
        else if (cs[px] == '#') {     // file name
317
          cmd.append(rEvt.GetName());
318
          oldpos = pos + 2;
319
        }
320
        else if (cs[px] == '%') {     // mask symbols
321
          std::string s;
322
          rEvt.DumpTypes(s);
323
          cmd.append(s);
324
          oldpos = pos + 2;
325
        }
326
        else if (cs[px] == '&') {     // numeric mask
327
          char* s;
328
          asprintf(&s, "%u", (unsigned) rEvt.GetMask());
329
          cmd.append(s);
330
          free(s);
331
          oldpos = pos + 2;
332
        }
333
        else {
334
          oldpos = pos + 1;
335
        }
45 luk 336
      }
337
    }
338
    else {
339
      cmd.append(cs.substr(oldpos, pos-oldpos));
340
      oldpos = pos + 1;
341
    }
342
  }    
343
  cmd.append(cs.substr(oldpos));
344
 
345
  int argc;
346
  char** argv;
347
  if (!PrepareArgs(cmd, argc, argv)) {
348
    syslog(LOG_ERR, "cannot prepare command arguments");
349
    return;
350
  }
351
 
67 luk 352
  if (m_fSysTable)
353
    syslog(LOG_INFO, "(system::%s) CMD (%s)", m_user.c_str(), cmd.c_str());
354
  else
355
    syslog(LOG_INFO, "(%s) CMD (%s)", m_user.c_str(), cmd.c_str());
45 luk 356
 
47 luk 357
  if (pE->IsNoLoop())
358
    pW->SetEnabled(false);
359
 
360
  ProcData_t pd;
361
  pd.pid = fork();
362
  if (pd.pid == 0) {
45 luk 363
 
67 luk 364
    // for system table
365
    if (m_fSysTable) {
366
      if (execvp(argv[0], argv) != 0) // exec failed
367
      {
368
        syslog(LOG_ERR, "cannot exec process: %s", strerror(errno));
369
        _exit(1);
370
      }
45 luk 371
    }
67 luk 372
    else {
373
      // for user table
374
      struct passwd* pwd = getpwnam(m_user.c_str());
375
      if (    pwd == NULL                 // user not found
376
          ||  setgid(pwd->pw_gid) != 0    // setting GID failed
377
          ||  setuid(pwd->pw_uid) != 0    // setting UID failed
378
          ||  execvp(argv[0], argv) != 0) // exec failed
379
      {
380
        syslog(LOG_ERR, "cannot exec process: %s", strerror(errno));
381
        _exit(1);
382
      }
383
    }
45 luk 384
  }
47 luk 385
  else if (pd.pid > 0) {
386
    if (pE->IsNoLoop()) {
387
      pd.onDone = on_proc_done;
388
      pd.pWatch = pW;
389
    }
390
    else {
391
      pd.onDone = NULL;
392
      pd.pWatch = NULL;
393
    }
45 luk 394
 
47 luk 395
    s_procList.push_back(pd);
45 luk 396
  }
397
  else {
47 luk 398
    if (pE->IsNoLoop())
399
      pW->SetEnabled(true);
400
 
45 luk 401
    syslog(LOG_ERR, "cannot fork process: %s", strerror(errno));
402
  }
51 luk 403
 
404
  CleanupArgs(argc, argv);
45 luk 405
}
406
 
407
InCronTabEntry* UserTable::FindEntry(InotifyWatch* pWatch)
408
{
409
  IWCE_MAP::iterator it = m_map.find(pWatch);
410
  if (it == m_map.end())
411
    return NULL;
412
 
413
  return (*it).second;
414
}
415
 
416
bool UserTable::PrepareArgs(const std::string& rCmd, int& argc, char**& argv)
417
{
418
  if (rCmd.empty())
419
    return false;
420
 
55 luk 421
  StringTokenizer tok(rCmd, ' ', '\\');
45 luk 422
  std::deque<std::string> args;
423
  while (tok.HasMoreTokens()) {
424
    args.push_back(tok.GetNextToken());
425
  }
426
 
427
  if (args.empty())
428
    return false;
429
 
430
  argc = (int) args.size();
431
  argv = new char*[argc+1];
432
  argv[argc] = NULL;
433
 
434
  for (int i=0; i<argc; i++) {
435
    const std::string& s = args[i];
436
    size_t len = s.length();
437
    argv[i] = new char[len+1];
438
    strcpy(argv[i], s.c_str());
439
  }
440
 
441
  return true;
442
}
443
 
51 luk 444
void UserTable::CleanupArgs(int argc, char** argv)
445
{
446
  for (int i=0; i<argc; i++) {
447
    delete[] argv[i];
448
  }
449
 
450
  delete[] argv;
451
}
452
 
47 luk 453
void UserTable::FinishDone()
454
{
455
  PROC_LIST::iterator it = s_procList.begin();
456
  while (it != s_procList.end()) {
457
    ProcData_t& pd = *it;
458
    int status = 0;
459
    int res = waitpid(pd.pid, &status, WNOHANG);
460
    if (res == pd.pid && (WIFEXITED(status) || WIFSIGNALED(status))) {
461
      if (pd.onDone != NULL)
462
        (*pd.onDone)(pd.pWatch);
463
      it = s_procList.erase(it);
464
    }
465
    else {
466
      it++;
467
    }
468
  }  
469
}
470
 
65 luk 471
bool UserTable::MayAccess(const std::string& rPath, bool fNoFollow) const
472
{
473
  // first, retrieve file permissions
474
  struct stat st;
475
  int res = fNoFollow
476
      ? lstat(rPath.c_str(), &st) // don't follow symlink
477
      : stat(rPath.c_str(), &st);
478
  if (res != 0)
479
    return false; // retrieving permissions failed
480
 
481
  // file accessible to everyone
482
  if (st.st_mode & S_IRWXO)
483
    return true;
484
 
485
  // retrieve user data
486
  struct passwd* pwd = getpwnam(m_user.c_str());
487
 
67 luk 488
  // root may always access
489
  if (pwd->pw_uid == 0)
490
    return true;
491
 
65 luk 492
  // file accesible to group
493
  if (st.st_mode & S_IRWXG) {
494
 
495
    // user's primary group
496
    if (pwd != NULL && pwd->pw_gid == st.st_gid)
497
        return true;
498
 
499
    // now check group database
500
    struct group *gr = getgrgid(st.st_gid);
501
    if (gr != NULL) {
502
      int pos = 0;
503
      const char* un;
504
      while ((un = gr->gr_mem[pos]) != NULL) {
505
        if (strcmp(un, m_user.c_str()) == 0)
506
          return true;
507
        pos++;
508
      }
509
    }
510
  }
511
 
512
  // file accessible to owner
513
  if (st.st_mode & S_IRWXU) {  
514
    if (pwd != NULL && pwd->pw_uid == st.st_uid)
515
      return true;
516
  }
517
 
518
  return false; // no access right found
519
}
47 luk 520
 
65 luk 521
 
522