summaryrefslogtreecommitdiffstats
path: root/kppp/accounting.cpp
blob: 2d7ab5d7bf93041ea857c22bd173237c330cfc89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/* -*- C++ -*-
 *
 *            kPPP: A pppd front end for the KDE project
 *
 * $Id$
 *
 *            Copyright (C) 1997 Bernd Johannes Wuebben
 *                   wuebben@math.cornell.edu
 *
 * This file contributed by: Mario Weilguni, <mweilguni@sime.com>
 * Thanks Mario!
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <tqdir.h>

#include <kstandarddirs.h>
#include <klocale.h>
#include <kdebug.h>
#include <time.h>

#include "accounting.h"
#include "pppdata.h"
#include "pppstats.h"

// defines the maximum duration until the current costs
// are saved again (to prevent loss due to "kill")
// specifying -1 disables the features
#define UPDATE_TIME    (5*60*1000)

extern PPPData gpppdata;

/////////////////////////////////////////////////////////////////////////////
//
// Helper functions
//
/////////////////////////////////////////////////////////////////////////////
static TQString timet2qstring(time_t t) {
  TQString s;

  s.sprintf("%lu", t);
  return s;
}


/////////////////////////////////////////////////////////////////////////////
//
// The base class for the accounting system provides a base set of usefull
// and common functions, but does not do any accounting by itself. The 
// accounting is accomplished withing it's derived classes
//
/////////////////////////////////////////////////////////////////////////////
AccountingBase::AccountingBase(TQObject *parent) :
  TQObject(parent),
  _total(0),
  _session(0)
{
  TQDate dt = TQDate::tqcurrentDate();
  LogFileName = TQString("%1-%2.log")
    .tqarg(TQDate::shortMonthName(dt.month()))
    .tqarg(dt.year(), 4);

  LogFileName = KGlobal::dirs()->saveLocation("appdata", "Log")
    + "/" + LogFileName;

  kdDebug(5002) << "LogFileName: " << LogFileName << endl;
}

AccountingBase::~AccountingBase() {
  if(running())
    slotStop();
}


double AccountingBase::total() const {
  return _total + _session;
}



double AccountingBase::session() const {
  return _session;
}


// set costs back to zero ( typically once per month)
void AccountingBase::resetCosts(const TQString & accountname){
  TQString prev_account = gpppdata.accname();

  gpppdata.setAccount(accountname);
  gpppdata.setTotalCosts("");

  gpppdata.setAccount(prev_account);
}


void AccountingBase::resetVolume(const TQString & accountname){
  TQString prev_account = gpppdata.accname();

  gpppdata.setAccount(accountname);
  gpppdata.setTotalBytes(0);

  gpppdata.setAccount(prev_account);
}


void AccountingBase::logMessage(TQString s, bool newline) {
  int old_umask = umask(0077);

  TQFile f(LogFileName);

  bool result = f.open(IO_ReadWrite);
  if(result) {
    // move to eof, and place \n if necessary
    if(f.size() > 0) {
      if(newline) {
	f.at(f.size());
	char c = 0;
	f.readBlock(&c, 1);
	if(c != '\n')
	  f.writeBlock("\n", 1);
      } else
	f.at(f.size());
    }

    TQCString tmp = s.local8Bit();
    f.writeBlock(tmp, tmp.length());
    f.close();
  }

  // restore umask
  umask(old_umask);
}


TQString AccountingBase::getCosts(const TQString & accountname) {
  TQString prev_account = gpppdata.accname();

  gpppdata.setAccount(accountname);
  TQString val = gpppdata.totalCosts();
  // ### currency from rule file
  //  TQString val = KGlobal::locale()->formatMoney(gpppdata.totalCosts().toDouble(), currency);

  gpppdata.setAccount(prev_account);

  return val;
}



bool AccountingBase::saveCosts() {
  if(!_name.isNull() && _name.length() > 0) {
    TQString val;
    val.setNum(total());

    gpppdata.setTotalCosts(val);
    gpppdata.save();

    return TRUE;
  } else
    return FALSE;
}


bool AccountingBase::loadCosts() {
  TQString val = gpppdata.totalCosts();

  if(val.isNull()) // TQString will segfault if isnull and toDouble called
    _total = 0.0;
  else {
    bool ok;
    _total = val.toDouble(&ok);
    if(!ok)
      _total = 0.0;
  }

  return TRUE;
}


TQString AccountingBase::getAccountingFile(const TQString &accountname) {
  TQString f = "kppp/Rules/";
  f += accountname;
  TQString d = locate("data", f);

  if(d.isNull())
    return "";
  else
    return d;
}


/////////////////////////////////////////////////////////////////////////////
//
// Accounting class for ruleset files
//
/////////////////////////////////////////////////////////////////////////////
Accounting::Accounting(TQObject *parent, PPPStats *st) : 
  AccountingBase(parent),
  acct_timer_id(0),
  update_timer_id(0),
  stats(st)
{
}


bool Accounting::running() const {
  return (bool)(acct_timer_id != 0);
}


void Accounting::timerEvent(TQTimerEvent *t) {
  if(t->timerId() == acct_timer_id) {

    double newCosts;
    double newLen;
    double connect_time = difftime(time(0), start_time);

    rules.getActiveRule(TQDateTime::tqcurrentDateTime(), connect_time, newCosts, newLen);
    if(newLen < 1) { // changed to < 1
      slotStop();
      return; // no default rule found
    }

    // check if we have a new rule. If yes,
    // kill the timer and restart it with new
    // duration
    if((newCosts != _lastcosts) || (newLen != _lastlen)) {

      kdDebug(5002).form("SWITCHING RULES, new costs = %0.2f, new len = %0.2f\n",
	     newCosts, newLen);

      killTimer(acct_timer_id);
      if(newLen > 0)
	acct_timer_id = startTimer((int)(newLen * 1000.0));

      _lastlen = newLen;
      _lastcosts = newCosts;
    }

    // emit changed() signal if necessary
    if(newCosts != 0) {
      _session += newCosts;
       emit changed(rules.currencyString(total()),
		    rules.currencyString(session()));


    }
  } // if(t->timerId() == acct_timer_id)...

  if(t->timerId() == update_timer_id) {
    // just to be sure, save the current costs
    // every n seconds (see UPDATE_TIME)
    saveCosts();
  }
}


void Accounting::slotStart() {
  if(!running()) {
    loadCosts();
    _lastcosts = 0.0;
    _lastlen   = 0.0;
    _session = rules.perConnectionCosts();
    rules.setStartTime(TQDateTime::tqcurrentDateTime());
    acct_timer_id = startTimer(1);
     if(UPDATE_TIME > 0)
       update_timer_id = startTimer(UPDATE_TIME);

    start_time = time(0); 
    TQString s;
    s = timet2qstring(start_time);
    s += ":";
    s += gpppdata.accname();
    s += ":";
    s += rules.currencySymbol();

    logMessage(s, TRUE);
  }
}


void Accounting::slotStop() {
  if(running()) {
    killTimer(acct_timer_id);
    if(update_timer_id != 0)
      killTimer(update_timer_id);
    acct_timer_id = 0;
    update_timer_id = 0;

    TQString s;
    s.sprintf(":%s:%0.4e:%0.4e:%u:%u\n",
	      timet2qstring(time(0)).utf8().data(),
	      session(),
	      total(),
	      stats->ibytes,
	      stats->obytes);

    logMessage(s, FALSE);
    saveCosts();
  }
}


bool Accounting::loadRuleSet(const TQString & name) {

  if (name.isEmpty()) {
    rules.load(""); // delete old rules
    return TRUE;
  }
  
  TQString d = AccountingBase::getAccountingFile(name);

  TQFileInfo fg(d);
   if(fg.exists()) {
     int ret = rules.load(d);
     _name = rules.name();
     return (bool)(ret == 0);
   }

 return FALSE;
}


double Accounting::total() const {
  if(rules.minimumCosts() <= _session)
    return _total + _session;
  else
    return _total + rules.minimumCosts();
}



double Accounting::session() const {
  if(rules.minimumCosts() <= _session)
    return _session;
  else
    return rules.minimumCosts();
}




ExecutableAccounting::ExecutableAccounting(PPPStats *st, TQObject *parent) : 
  AccountingBase(parent),
  proc(0),
  stats(st)
{
}


bool ExecutableAccounting::running() const {
  return (proc != 0) || proc->isRunning();
}


bool ExecutableAccounting::loadRuleSet(const TQString &) {
  TQString s = AccountingBase::getAccountingFile(gpppdata.accountingFile());
  return (access(TQFile::encodeName(s), X_OK) == 0);
}


void ExecutableAccounting::gotData(KProcess */*proc*/, char *buffer, int /*buflen*/) {
  TQString field[8];
  int nFields = 0;
  int pos, last_pos = 0;

  // split string
  TQString b(buffer);
  pos = b.find(':');
  while(pos != -1 && nFields < 8) {
    field[nFields++] = b.mid(last_pos, pos-last_pos);
    last_pos = pos+1;
    pos = b.find(':', last_pos);
  }

  for(int i = 0; i < nFields;i++)
    fprintf(stderr, "FIELD[%d] = %s\n", i, field[i].local8Bit().data());
  
  TQString __total, __session;
  TQString s(buffer);
  int del1, del2, del3;

  del1 = s.find(':');
  del2 = s.find(':', del1+1);
  del3 = s.find(':', del2+1);
  if(del1 == -1 || del2 == -1 || del3 == -1) {
    // TODO: do something usefull here
    return;
  }

  provider = s.left(del1);
  currency = s.mid(del1, del2-del1);
  __total = s.mid(del2, del2-del1);
  __session = s.mid(del3, s.length()-del3+1);

  bool ok1, ok2;
  _total = __total.toDouble(&ok1);
  _session = __session.toDouble(&ok2);
  
  if(!ok1 || !ok2) {
    // TODO: do something usefull here
    return;
  }

  printf("PROVIDER=%s, CURRENCY=%s, TOTAL=%0.3e, SESSION=%0.3e\n", 
	 provider.local8Bit().data(),
	 currency.local8Bit().data(),
	 _total,
	 _session);
}


void ExecutableAccounting::slotStart() {
  if(proc != 0)
    slotStop(); // just to make sure

  loadCosts();
  TQString s = AccountingBase::getAccountingFile(gpppdata.accountingFile());
  proc = new KProcess;

  TQString s_total;
  s_total.sprintf("%0.8f", total());
  *proc << s << s_total;
  connect(proc, TQT_SIGNAL(receivedStdout(KProcess *, char *, int)),
	  this, TQT_SLOT(gotData(KProcess *, char *, int)));
  proc->start();

  time_t start_time = time(0); 
  s = timet2qstring(start_time);
  s += ":";
  s += gpppdata.accname();
  s += ":";
  s += currency;
  
  logMessage(s, TRUE);
}


void ExecutableAccounting::slotStop() {
  if(proc != 0) {
    proc->kill();
    delete proc;
    proc = 0;

    TQString s;
    s.sprintf(":%s:%0.4e:%0.4e:%u:%u\n",
	      timet2qstring(time(0)).local8Bit().data(),
	      session(),
	      total(),
	      stats->ibytes,
	      stats->obytes);

    logMessage(s, FALSE);
    saveCosts();
  }
}

#include "accounting.moc"