2 * Detect media size of given GIOChannel for libcaptive
3 * Copyright (C) 2002 Jan Kratochvil <project-captive@jankratochvil.net>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; exactly version 2 of June 1991 is required
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "captive/storage.h" /* self */
23 #include <glib/gmessages.h>
24 #include <glib/gtypes.h>
27 guint64 captive_giochannel_size(GIOChannel *iochannel)
31 GIOStatus erriostatus;
35 g_return_val_if_fail(iochannel!=NULL,0);
36 /* Default "UTF-8" encoding is not much usable for us */
37 g_return_val_if_fail(g_io_channel_get_encoding(iochannel)==NULL,0);
39 fd=g_io_channel_unix_get_fd(iochannel);
40 g_return_val_if_fail(fd!=-1,0);
42 /* FIXME: TODO: ioctl() detection */
44 /* low ==high: low (high)
45 * low+1==high: mid==low; NORMAL: no change: high
46 * low+1==high: mid==low; EOF : high=mid => 'low==high' case
50 G_MAXINT; /* FIXME: 'G_MAXINT64' fails on g_io_channel_seek_position() */
52 mid=low+(high-low)/2; /* beware of 'gint64' overflow! */
54 erriostatus=g_io_channel_seek_position(iochannel,mid,G_SEEK_SET,
56 /* During seek in block device such as on URL file:///dev/hda1#captive-fastfat.sys-ro:/
57 * we will do llseek(2) on "/dev/hda1" device from captive_giochannel_size().
58 * Although we are allowed to seek behind EOF on regular files
59 * at least linux-kernel-2.4.19-ac4/fs/block_dev.c/block_llseek() will give
60 * EINVAL on seek behind EOF therefore it must be accepted without complaints by us.
62 if (erriostatus!=G_IO_STATUS_NORMAL) {
63 erriostatus=G_IO_STATUS_EOF;
67 g_assert(sizeof(bufchar)==1);
68 erriostatus=g_io_channel_read_chars(iochannel,
70 sizeof(bufchar), /* count */
71 &bufchargot, /* bytes_read */
73 g_assert(erriostatus==G_IO_STATUS_NORMAL || erriostatus==G_IO_STATUS_EOF);
75 || (erriostatus==G_IO_STATUS_NORMAL && bufchargot==1)
76 || (erriostatus==G_IO_STATUS_EOF && bufchargot==0));
79 if (erriostatus==G_IO_STATUS_NORMAL)