On 03/01/2010 03:39 AM, Phil Varner wrote:
> Hi, I haven't seen any examples of using the INSTREAM protocol from
> Java code, so I thought I'd post mine here.  The response evaluation
> is done in a different class, and basically blocks the content if
> anything other than "status: OK" is returned.  Comments and critiques
> are welcome.
> 
> I'm not sure what the optimal default chunk size is, so any
> recommendations on that would be appreciated.
> 
> 
> public static final int DEFAULT_CHUNK_SIZE = 2048;
> 
> public static String scanForVirus(byte[] data, int timeout, String
> host, int port) throws IOException {
> 
>         Socket socket = new Socket();
>         socket.connect(new InetSocketAddress(host, port));
> 
>         try {
>             socket.setSoTimeout(timeout);
>         } catch (SocketException e) {
>               log.error("Could not set socket timeout to " + timeout + "ms", 
> e);
>         }
> 
>         DataOutputStream dos = null;
>         BufferedReader reader = null;
>         String response = null;
>         try {
>             dos = new DataOutputStream(socket.getOutputStream());
>             dos.writeBytes("zINSTREAM\0");
> 
>             int cursor = 0;
>             int size = DEFAULT_CHUNK_SIZE;
>             while (cursor < data.length){
>                 if (cursor + size >= data.length){
>                     size = data.length - cursor;
>                 }
>                 dos.writeInt(size);
>                 dos.write(data, cursor, size);
>                 cursor += size;
>             }
> 
>             dos.writeInt(0);
>             dos.write('\0');

The write('\0') is not needed, and even wrong in IDSESSION mode, clamd
doesn't read it. A zero length chunk is just the chunk length as 4 bytes
of 0, which you already sent with writeInt.

>             dos.flush();
> 
>             reader = new BufferedReader(new
> InputStreamReader(socket.getInputStream(), "ASCII"));
> 
>             response = reader.readLine();
>         } finally {
>             if (reader != null) try { reader.close(); } catch
> (IOException e) { }
>             if (dos != null) try { dos.close(); } catch (IOException e) { }
>             if (socket != null) try { socket.close(); } catch
> (IOException e) { }

This is not nice, your method declares that it throws IOException (which
it probably does for creation of socket), but then eats the other
IOExceptions. I think it should rethrow them instead.

>        if (log.isDebugEnabled()) log.debug( "Response: " + response);
>        return response.trim();

And this will throw a nullpointer exception if anything goes wrong prior
to reading the response.

Best regards,
--Edwin
_______________________________________________
Help us build a comprehensive ClamAV guide: visit http://wiki.clamav.net
http://www.clamav.net/support/ml

Reply via email to