File: pyclamav.c

package info (click to toggle)
python-clamav 0.4.1-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 124 kB
  • ctags: 61
  • sloc: ansic: 317; python: 102; makefile: 69
file content (302 lines) | stat: -rw-r--r-- 8,069 bytes parent folder | download | duplicates (5)
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
/*
 *  Copyright (C) 2005 Alexandre Norman <norman@xael.org>
 *
 *  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.
 */


/* Tested with python 2.4 and clamav 0.86.1
 * Should work with any version of python from 2.1
 */

#include <Python.h>
#include <clamav.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>


#define PYCLAMAV_VERSION "0.4.1"


/* ********************************************************* */

/* For python prior to 2.3 */
#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif

/* ********************************************************* */


/* Exception object for python */
static PyObject *PyclamavError;


/* Signature number */
unsigned int signumber = 0;
 
/* Structures for clamav */
struct cl_engine *engine = NULL;
struct cl_stat dbstat;

/*
 * If the virus database has been changed, then
 * free the current tree and reload the new one
 */
int if_database_have_changed_then_reload(void)
{
  int ret = 0;
 
  /* Test if the database have changed */
  /* If yes : reload DB                */
  if (cl_statchkdir(&dbstat) == 1)
    {
      /* free the engine */
      cl_engine_free(engine); 
      signumber=0;
      engine=NULL;

      /* Load DB */
      if((ret = cl_load(cl_retdbdir(), engine, &signumber, CL_DB_STDOPT)) != CL_SUCCESS) {
	/* Raise exception with error message */
	PyErr_SetString(PyclamavError,  cl_strerror(ret));
	return -2;
      }

      /* prepare the engine */
      if((ret = cl_engine_compile(engine))) {
	/* free the engine */
	cl_engine_free(engine); 
	/* Raise exception with error message */
	PyErr_SetString(PyclamavError, cl_strerror(ret));
	return -2;
      }

      /* Reinit db status update check */
      cl_statfree(&dbstat);
      cl_statinidir(cl_retdbdir(), &dbstat);

      return -1;
    }
  else
    {
      return 0;
    }

  return 0;
}




/*
 * Checks if the given filename is a directory or not 
 */
int filename_is_dir(char *file)
{
#ifdef __linux__
        struct stat64 buf;
        if(stat64(file, &buf) < 0) return(0);
#else  /* For FreeBSD */
#warning Not a Linux system... 
        struct stat buf;
        if(stat(file, &buf) < 0) return(0);	
#endif
        return(S_ISDIR(buf.st_mode));
}



/*
 * Return pyclamav version
 */

static PyObject *pyclamav_version(PyObject *self, PyObject *args)
{
    return Py_BuildValue("s", PYCLAMAV_VERSION);
}



/*
 * Return clamav version
 */

static PyObject *pyclamav_get_version(PyObject *self, PyObject *args)
{
    const char *version;
    int daily_version = 0;
    int daily_date = 0;

    const char *dbdir;
    char *path = NULL;
    struct cl_cvd *daily;

    //Clamav version
    version = cl_retver();

    //Database version
    dbdir = cl_retdbdir();
    if((path = malloc(strlen(dbdir) + 11))){
        
        sprintf(path, "%s/daily.cvd", dbdir);

        if((daily = cl_cvdhead(path))){

            daily_date    = daily->stime;
            daily_version = daily->version;

            cl_cvdfree(daily);
        }
    }

    return Py_BuildValue("(s,i,i)", version, daily_version, daily_date);
}
    

/*
 * Return number of signature in the database as integer
 */
static PyObject *pyclamav_get_numsig(PyObject *self, PyObject *args)
{
  /* Raise exception if database error */
  if (if_database_have_changed_then_reload() == -2) {
    return NULL;
  }

  return Py_BuildValue("i", signumber);
}




/*
 * Scan a file given as a parameter
 */
static PyObject *pyclamav_scanfile(PyObject *self, PyObject *args)
{
  char *file_to_scan;
  unsigned long int size = 0;
  const char *virname;
  int ret = 0;

  /* Raise exception if database error */
  if (if_database_have_changed_then_reload() == -2) {
    return NULL;
  }

  if (!PyArg_ParseTuple(args, "s", &file_to_scan)) {
    /* Raise exception with error message */
    PyErr_SetString(PyExc_TypeError,  "Pass filename to scan (string) as argument");
    return NULL; 
  }
  
  /* Test if the filename is really an existing file and not a directory for example */
  if (filename_is_dir(file_to_scan)) {
    PyErr_SetString(PyExc_ValueError,  "Argument is not a filename");
    return NULL;     
  }

  ret = cl_scanfile(file_to_scan, &virname, &size, engine, CL_SCAN_STDOPT);

  /* Test return code */
  switch (ret) {
  case CL_VIRUS : /* File contains a virus */
    return Py_BuildValue("(i,s)",1, virname);
    break;
  case CL_CLEAN : /* File is clean */
    return Py_BuildValue("(i,s)",0, "");
    break;
  default: /* Error : raise exception with message */
    PyErr_SetString(PyExc_ValueError,  cl_strerror(ret));
    return NULL;
  }

}





static PyMethodDef ClamavMethods[] = {
    {"scanfile",  pyclamav_scanfile, METH_VARARGS, "scanfile(filename) : Scan a file for virus.\nArguments : filename (string)\n Return a tupple (status, virusname) where status=0 when no virus found\n or status=1 if a virus was found\n May raise a ValueError exception if an error occurs\n May raise a TypeError exception if wrong arguments are passed\n"},
    {"get_numsig",  pyclamav_get_numsig, METH_VARARGS, "get_numsig() : Get the number of know virii signatures\nArguments : None\n Return the number of known signatures.\n"},
    {"get_version",  pyclamav_get_version, METH_VARARGS, "get_version() : Get Clamav version.\nArguments : None\n Return the version of Clamav as a tupple (version, daily_version, daily_date).\n"},
    {"version",  pyclamav_version, METH_VARARGS, "version() : Get pyclamav version.\nArguments : None\n Return the version of pyclamav.\n"},
    {NULL, NULL, 0, NULL}    
};




PyMODINIT_FUNC initpyclamav(void)
{
  int ret= 0;

  PyObject *module, *dict;
  module=Py_InitModule("pyclamav", ClamavMethods);
  dict = PyModule_GetDict(module);

  PyclamavError = PyErr_NewException("pyclamav.error", NULL, NULL);
  PyDict_SetItemString(dict, "error", PyclamavError);


  /* Set documentation string for the module */
  PyDict_SetItemString(dict, "__doc__", PyString_FromString("pyclamav :\n\n  This is a python binding to the C libclamav library\n  (from the Clamav project - http://www.clamav.net).\n  It can be used to easily allow a Python script to scan\n  a file or a buffer against known viruses.\n\nAuthor : Alexandre Norman [norman@xael.org]\n\nFunctions :\n  - scanfile(string filename) : Scan a file for virus.\n  - get_numsig() : Return the number of known signatures.\n  - get_version() : Return the version of Clamav.\n  - version() : Return the version of pyclamav.\n"));

  /* initialize libclamav */
  cl_init(CL_INIT_DEFAULT);
  engine = cl_engine_new();

  if((ret = cl_load(cl_retdbdir(), engine, &signumber, CL_DB_STDOPT))) {
    /* Raise exception with error message */
    PyErr_SetString(PyclamavError,  cl_strerror(ret));
    cl_engine_free(engine);
    return;
  }

  /* prepare the engine */
  if((ret = cl_engine_compile(engine)) != CL_SUCCESS) {
    /* free up the engine resources */
    cl_engine_free(engine); 
    /* Raise exception with error message */
    PyErr_SetString(PyclamavError, cl_strerror(ret));
    return;
  }


  /* Set dbstat to get notification of database changes */
  memset(&dbstat, 0, sizeof(struct cl_stat));
  cl_statinidir(cl_retdbdir(), &dbstat);

  return ;
}



int main(int argc, char *argv[])
{
  /* Pass argv[0] to the Python interpreter */
  Py_SetProgramName(argv[0]);

  /* Initialize the Python interpreter.  Required. */
  Py_Initialize();
  
  /* Add a static module */
  initpyclamav();
  
  return 0;
}