File: linux-data.c

package info (click to toggle)
netmon-applet 0.4-11
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 524 kB
  • ctags: 115
  • sloc: sh: 3,348; ansic: 684; makefile: 79
file content (325 lines) | stat: -rw-r--r-- 9,440 bytes parent folder | download | duplicates (2)
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
/*
 * This file was taken from xnetload, with minor modifications.
 * The original comments are below
 *  
 * --------------------------------------------------------------------
 * This file is part of xnetload, a program to monitor network traffic,
 * and display it in an X window.
 *
 * Copyright (C) 1997 - 2000  R.F. Smith <rsmith@xs4all.nl>
 *
 * You can contact the author at the following address:
 *      email: rsmith@xs4all.nl
 * snail-mail: R.F. Smith
 *             Dr. Hermansweg 36
 *             5624 HR Eindhoven
 *             The Netherlands
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 * 
 */

#include "config.h"

#ifdef __LINUX__

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <math.h>
#include "data.h"


/* size of buffer to copy /proc/net/xxx to */
#define BUFSIZE 2048

/********** Global variables **********/
int type = 0;			/* What kind of data is gathered */
count_t average = {(float)0,(float)0};   /* average count */
count_t max = {(float)0,(float)0};       /* maximum count */
count_t total = {(float)0,(float)0};     /* total count   */

/********** Static variables **********/
static char *iface_name;   /* Name of the interface to be queried. */
static count_t last = {(float)0,(float)0};	/* Previously read values. */
static float *inarray;     /* Array for receive counts. */
static float *outarray;	   /* Array for transmit counts. */
static int numavg;         /* number of samples to average */

/********** Function definitions **********/

/* return values for read_*  */
#define READ_ALLOC_ERR    -5	/* Not enough memory on the stack */
#define READ_FOPEN_ERR    -4	/* Can't open file */
#define READ_FREAD_ERR    -3	/* Can't read file */
#define READ_IFACE_ERR    -2	/* Interface not found */
#define READ_SCAN_ERR     -1	/* Unknown file layout */
#define READ_BYTES         1	/* Function reads byte counts */
#define READ_PACKETS       2	/* Function reads packet counts */

/* Read the byte or packet count for the network interface  
   named in `iface' from /proc/net/dev, store it in the  
   variable pointed to by `pcnt', if `pcnt' is not NULL. */
static int read_dev(count_t * pcnt, char *iface);

/********** Function implementations **********/

void report_error(char *msg)
{
  /* cleanup for ip_acct */
  /* cleanup(); */
  /* Open connection to system logfile. */
  /* openlog("xnetload", LOG_CONS, LOG_USER); */
  /* Write a log message. */
  /* syslog(LOG_ERR, "%s.\n", msg); */
  /* Close the logfile. */
  /* closelog(); */
  /* Write the message to stderr. */
  fprintf(stderr, "gnome netmon_applet: %s.\n", msg);
  /* Terminate the program. */
//  exit(1);
}

int initialize(char *iface, int num_avg/*  , int kb */)
{
  int r;
  
  /* Initialize global variables. */
  iface_name = iface;
  numavg = num_avg;
  average.in = (float)0;
  average.out = (float)0;
  total.in  = (float)0;
  total.out = (float)0;
  last.in = (float)0;
  last.out = (float)0;

  inarray = (float*)malloc(numavg*sizeof(float));
  outarray = (float*)malloc(numavg*sizeof(float));
  if (inarray == 0 || outarray == 0) {
    report_error("Memory allocation failed");
  }
  for (r = 0; r < numavg; r++) {
    inarray[r] = (float)0;
    outarray[r] = (float)0;
  }

  /* return 0; */

  r = read_dev(&last, iface);
  switch (r) {
  case READ_FOPEN_ERR:
    report_error("Could not open /proc/net/dev");
    type = ERROR_TYPE;
    break;
  case READ_IFACE_ERR:
    report_error("Interface not found in /proc/net/dev");
    type = ERROR_TYPE;
    break;
  case READ_SCAN_ERR:
    report_error("Error scanning /proc/net/dev");
    type = ERROR_TYPE;
    break;
  case READ_BYTES:
    type = BYTES_TYPE;
    break;
  case READ_PACKETS:
    type = PACKETS_TYPE;
    break;
  default:
    report_error("Unknown return value from read_dev");
    type = ERROR_TYPE;
  }    
  return type;
}  

int cleanup(void)
{
  free(inarray);
  free(outarray);
  return (0);
}

void update_avg(int seconds)
{
  count_t current = {0.0,0.0};
  count_t diff;
  int i;
  static int index;

  /* Quit if invalid number of seconds is given */
  if (seconds <= 0)
    return;
  /* Read the data. */
  i = read_dev(&current, iface_name);
  switch (i) {
  case READ_FOPEN_ERR:
    report_error("Could not open /proc/net/dev");
    break;
  case READ_IFACE_ERR:
    //exit(0);
    break;
  case READ_SCAN_ERR:
    report_error("Error scanning /proc/net/dev");
    break;
  }

  /* Try to detect counter overrun. current and last are floating point
   * values, but current is filled from a %u, and so capped to UINT_MAX */
  if (current.in < last.in) {
    diff.in = current.in + (UINT_MAX - last.in);
    printf("xnetload warning: incoming counter overrun.\n");
  } else {
    diff.in = current.in - last.in;
  }
  if (current.out < last.out) {
    diff.out = current.out + (UINT_MAX - last.out);
    printf("xnetload warning: outgoing counter overrun.\n");
  } else {
    diff.out = current.out - last.out;
  }

  /* Add that to the total */
  total.in  += diff.in;
  total.out += diff.out;

  /* Calculate the difference per update */
  diff.in /= seconds;
  diff.out /= seconds;
  /* Update the arrays. */
  inarray[index] = diff.in;
  outarray[index++] = diff.out;
  if (index == numavg) {
    index = 0;
  }

  /* Calculate the average */
  average.in = average.out = (float)0;
  for (i = 0; i < numavg; i++) {
    average.in += inarray[i];
    average.out += outarray[i];
  }
  average.in /= numavg;
  average.out /= numavg;

  /* Update the maximum. */
  if (average.in > max.in)
    max.in = average.in;
  if (average.out > max.out)
    max.out = average.out;

  /* Store current count for further reference. */
  memcpy(&last, &current, sizeof(count_t));
}

int read_dev(count_t * pcnt, char *iface)
{
  FILE *f;
  char buf[BUFSIZE];
  int num, retval;
  char *pch;
  unsigned long int values[16];
  
  /* Try to open /proc/net/dev for reading. */
  f = fopen("/proc/net/dev", "r");
  if (f == 0) {
    /* Unable to open file. */
    return READ_FOPEN_ERR;
  } 
  /* Read the file into a buffer. */
  num = fread(buf, 1, BUFSIZE - 1, f);
  /* Check for read errors. */
  if (ferror(f)) {
    fclose(f);
    return READ_FREAD_ERR;
  }
  /* Terminate the buffer with 0. */
  buf[num] = 0;
  /* Close the file. */
  fclose(f);

  /* Seek the interface we're looking for. */
  pch = strstr(buf, iface);
  if (pch == 0) {
    /* Interface not found. */
    return READ_IFACE_ERR;
  }
  /* Skip the interface name. */
  pch += strlen(iface);
  /* Skip the ":" after the interface name. */
  pch++;

  /* There are different layouts for /proc/net/dev:
   * there are several fields for received and transmitted bytes
   * on 2.0.32:          on 2.1.>90            on 2.1.<90
   *              RECEIVE  (and 2.2.x)        
   *  > 1 packets         >  1 bytes          > 1 bytes
   *    2 errs               2 packets          2 packets
   *    3 drop               3 errs             3 errs
   *    4 fifo               4 drop             4 drop
   *    5 frame              5 fifo             5 fifo
   *                         6 frame            6 frame
   *                         7 compressed
   *                         8  multicast
   *              TRANSMIT
   *  > 6 packets         >  9 bytes          > 7 bytes
   *    7 errs              10 packets          8 packets
   *    8 drop              11 errs             9 errs
   *    9 fifo              12 drop            10 drop
   *   10 colls             13 fifo            11 fifo
   *   11 carrier           14 colls           12 colls
   *                        15 carrier         13 carrier
   *                        16 compressed      14 multicast
   */
  num = sscanf(pch, 
           "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
               &values[0], &values[1], &values[2], &values[3],
               &values[4], &values[5], &values[6], &values[7],
               &values[8], &values[9], &values[10], &values[11],
               &values[12], &values[13], &values[14], &values[15]);
  switch (num) {
  case 11:			/* 2.0.xx kernel, can only read packets. */
    retval = READ_PACKETS;
    if (pcnt) {
      pcnt->in = (float) values[0];
      pcnt->out = (float) values[5];
    }
    break;
  case 14:			/* 2.1.<90 kernel, can read byte counts. */
    retval = READ_BYTES;
    if (pcnt) {
      pcnt->in = (float) values[0];
      pcnt->out = (float) values[6];
    }
    break;
  case 16:			/* 2.1.90+ kernel, can read byte counts. */
    retval = READ_BYTES;
    if (pcnt) {
      pcnt->in = (float) values[0];
      pcnt->out = (float) values[8];
    }
    break;
  default:
    /* Unknown layout/scan error. */
    return READ_SCAN_ERR;
  }

  /* probe went OK */
  return retval;
}

#endif /* __LINUX__ */