[HQ](Debian) Package version up
[external/glib2.0.git] / glib / giounix.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * giounix.c: IO Channels using unix file descriptors
5  * Copyright 1998 Owen Taylor
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /*
24  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GLib Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
28  */
29
30 /* 
31  * MT safe
32  */
33
34 #include "config.h"
35
36 #define _POSIX_SOURCE           /* for SSIZE_MAX */
37
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <stdio.h>
41 #include <unistd.h>
42 #include <errno.h>
43 #include <string.h>
44 #include <fcntl.h>
45
46 #include "glib.h"
47 #include "galias.h"
48
49 /*
50  * Unix IO Channels
51  */
52
53 typedef struct _GIOUnixChannel GIOUnixChannel;
54 typedef struct _GIOUnixWatch GIOUnixWatch;
55
56 struct _GIOUnixChannel
57 {
58   GIOChannel channel;
59   gint fd;
60 };
61
62 struct _GIOUnixWatch
63 {
64   GSource       source;
65   GPollFD       pollfd;
66   GIOChannel   *channel;
67   GIOCondition  condition;
68 };
69
70
71 static GIOStatus        g_io_unix_read          (GIOChannel   *channel,
72                                                  gchar        *buf,
73                                                  gsize         count,
74                                                  gsize        *bytes_read,
75                                                  GError      **err);
76 static GIOStatus        g_io_unix_write         (GIOChannel   *channel,
77                                                  const gchar  *buf,
78                                                  gsize         count,
79                                                  gsize        *bytes_written,
80                                                  GError      **err);
81 static GIOStatus        g_io_unix_seek          (GIOChannel   *channel,
82                                                  gint64        offset,
83                                                  GSeekType     type,
84                                                  GError      **err);
85 static GIOStatus        g_io_unix_close         (GIOChannel   *channel,
86                                                  GError      **err);
87 static void             g_io_unix_free          (GIOChannel   *channel);
88 static GSource*         g_io_unix_create_watch  (GIOChannel   *channel,
89                                                  GIOCondition  condition);
90 static GIOStatus        g_io_unix_set_flags     (GIOChannel   *channel,
91                                                  GIOFlags      flags,
92                                                  GError      **err);
93 static GIOFlags         g_io_unix_get_flags     (GIOChannel   *channel);
94
95 static gboolean g_io_unix_prepare  (GSource     *source,
96                                     gint        *timeout);
97 static gboolean g_io_unix_check    (GSource     *source);
98 static gboolean g_io_unix_dispatch (GSource     *source,
99                                     GSourceFunc  callback,
100                                     gpointer     user_data);
101 static void     g_io_unix_finalize (GSource     *source);
102
103 GSourceFuncs g_io_watch_funcs = {
104   g_io_unix_prepare,
105   g_io_unix_check,
106   g_io_unix_dispatch,
107   g_io_unix_finalize
108 };
109
110 static GIOFuncs unix_channel_funcs = {
111   g_io_unix_read,
112   g_io_unix_write,
113   g_io_unix_seek,
114   g_io_unix_close,
115   g_io_unix_create_watch,
116   g_io_unix_free,
117   g_io_unix_set_flags,
118   g_io_unix_get_flags,
119 };
120
121 static gboolean 
122 g_io_unix_prepare (GSource  *source,
123                    gint     *timeout)
124 {
125   GIOUnixWatch *watch = (GIOUnixWatch *)source;
126   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
127
128   *timeout = -1;
129
130   /* Only return TRUE here if _all_ bits in watch->condition will be set
131    */
132   return ((watch->condition & buffer_condition) == watch->condition);
133 }
134
135 static gboolean 
136 g_io_unix_check (GSource  *source)
137 {
138   GIOUnixWatch *watch = (GIOUnixWatch *)source;
139   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
140   GIOCondition poll_condition = watch->pollfd.revents;
141
142   return ((poll_condition | buffer_condition) & watch->condition);
143 }
144
145 static gboolean
146 g_io_unix_dispatch (GSource     *source,
147                     GSourceFunc  callback,
148                     gpointer     user_data)
149
150 {
151   GIOFunc func = (GIOFunc)callback;
152   GIOUnixWatch *watch = (GIOUnixWatch *)source;
153   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
154
155   if (!func)
156     {
157       g_warning ("IO watch dispatched without callback\n"
158                  "You must call g_source_connect().");
159       return FALSE;
160     }
161   
162   return (*func) (watch->channel,
163                   (watch->pollfd.revents | buffer_condition) & watch->condition,
164                   user_data);
165 }
166
167 static void 
168 g_io_unix_finalize (GSource *source)
169 {
170   GIOUnixWatch *watch = (GIOUnixWatch *)source;
171
172   g_io_channel_unref (watch->channel);
173 }
174
175 static GIOStatus
176 g_io_unix_read (GIOChannel *channel, 
177                 gchar      *buf, 
178                 gsize       count,
179                 gsize      *bytes_read,
180                 GError    **err)
181 {
182   GIOUnixChannel *unix_channel = (GIOUnixChannel *)channel;
183   gssize result;
184
185   if (count > SSIZE_MAX) /* At least according to the Debian manpage for read */
186     count = SSIZE_MAX;
187
188  retry:
189   result = read (unix_channel->fd, buf, count);
190
191   if (result < 0)
192     {
193       int errsv = errno;
194       *bytes_read = 0;
195
196       switch (errsv)
197         {
198 #ifdef EINTR
199           case EINTR:
200             goto retry;
201 #endif
202 #ifdef EAGAIN
203           case EAGAIN:
204             return G_IO_STATUS_AGAIN;
205 #endif
206           default:
207             g_set_error_literal (err, G_IO_CHANNEL_ERROR,
208                                  g_io_channel_error_from_errno (errsv),
209                                  g_strerror (errsv));
210             return G_IO_STATUS_ERROR;
211         }
212     }
213
214   *bytes_read = result;
215
216   return (result > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
217 }
218
219 static GIOStatus
220 g_io_unix_write (GIOChannel  *channel, 
221                  const gchar *buf, 
222                  gsize       count,
223                  gsize      *bytes_written,
224                  GError    **err)
225 {
226   GIOUnixChannel *unix_channel = (GIOUnixChannel *)channel;
227   gssize result;
228
229  retry:
230   result = write (unix_channel->fd, buf, count);
231
232   if (result < 0)
233     {
234       int errsv = errno;
235       *bytes_written = 0;
236
237       switch (errsv)
238         {
239 #ifdef EINTR
240           case EINTR:
241             goto retry;
242 #endif
243 #ifdef EAGAIN
244           case EAGAIN:
245             return G_IO_STATUS_AGAIN;
246 #endif
247           default:
248             g_set_error_literal (err, G_IO_CHANNEL_ERROR,
249                                  g_io_channel_error_from_errno (errsv),
250                                  g_strerror (errsv));
251             return G_IO_STATUS_ERROR;
252         }
253     }
254
255   *bytes_written = result;
256
257   return G_IO_STATUS_NORMAL;
258 }
259
260 static GIOStatus
261 g_io_unix_seek (GIOChannel *channel,
262                 gint64      offset, 
263                 GSeekType   type,
264                 GError    **err)
265 {
266   GIOUnixChannel *unix_channel = (GIOUnixChannel *)channel;
267   int whence;
268   off_t tmp_offset;
269   off_t result;
270
271   switch (type)
272     {
273     case G_SEEK_SET:
274       whence = SEEK_SET;
275       break;
276     case G_SEEK_CUR:
277       whence = SEEK_CUR;
278       break;
279     case G_SEEK_END:
280       whence = SEEK_END;
281       break;
282     default:
283       whence = -1; /* Shut the compiler up */
284       g_assert_not_reached ();
285     }
286
287   tmp_offset = offset;
288   if (tmp_offset != offset)
289     {
290       g_set_error_literal (err, G_IO_CHANNEL_ERROR,
291                            g_io_channel_error_from_errno (EINVAL),
292                            g_strerror (EINVAL));
293       return G_IO_STATUS_ERROR;
294     }
295   
296   result = lseek (unix_channel->fd, tmp_offset, whence);
297
298   if (result < 0)
299     {
300       int errsv = errno;
301       g_set_error_literal (err, G_IO_CHANNEL_ERROR,
302                            g_io_channel_error_from_errno (errsv),
303                            g_strerror (errsv));
304       return G_IO_STATUS_ERROR;
305     }
306
307   return G_IO_STATUS_NORMAL;
308 }
309
310
311 static GIOStatus
312 g_io_unix_close (GIOChannel *channel,
313                  GError    **err)
314 {
315   GIOUnixChannel *unix_channel = (GIOUnixChannel *)channel;
316
317   if (close (unix_channel->fd) < 0)
318     {
319       int errsv = errno;
320       g_set_error_literal (err, G_IO_CHANNEL_ERROR,
321                            g_io_channel_error_from_errno (errsv),
322                            g_strerror (errsv));
323       return G_IO_STATUS_ERROR;
324     }
325
326   return G_IO_STATUS_NORMAL;
327 }
328
329 static void 
330 g_io_unix_free (GIOChannel *channel)
331 {
332   GIOUnixChannel *unix_channel = (GIOUnixChannel *)channel;
333
334   g_free (unix_channel);
335 }
336
337 static GSource *
338 g_io_unix_create_watch (GIOChannel   *channel,
339                         GIOCondition  condition)
340 {
341   GIOUnixChannel *unix_channel = (GIOUnixChannel *)channel;
342   GSource *source;
343   GIOUnixWatch *watch;
344
345
346   source = g_source_new (&g_io_watch_funcs, sizeof (GIOUnixWatch));
347   watch = (GIOUnixWatch *)source;
348   
349   watch->channel = channel;
350   g_io_channel_ref (channel);
351   
352   watch->condition = condition;
353
354   watch->pollfd.fd = unix_channel->fd;
355   watch->pollfd.events = condition;
356
357   g_source_add_poll (source, &watch->pollfd);
358
359   return source;
360 }
361
362 static GIOStatus
363 g_io_unix_set_flags (GIOChannel *channel,
364                      GIOFlags    flags,
365                      GError    **err)
366 {
367   glong fcntl_flags;
368   GIOUnixChannel *unix_channel = (GIOUnixChannel *) channel;
369
370   fcntl_flags = 0;
371
372   if (flags & G_IO_FLAG_APPEND)
373     fcntl_flags |= O_APPEND;
374   if (flags & G_IO_FLAG_NONBLOCK)
375 #ifdef O_NONBLOCK
376     fcntl_flags |= O_NONBLOCK;
377 #else
378     fcntl_flags |= O_NDELAY;
379 #endif
380
381   if (fcntl (unix_channel->fd, F_SETFL, fcntl_flags) == -1)
382     {
383       int errsv = errno;
384       g_set_error_literal (err, G_IO_CHANNEL_ERROR,
385                            g_io_channel_error_from_errno (errsv),
386                            g_strerror (errsv));
387       return G_IO_STATUS_ERROR;
388     }
389
390   return G_IO_STATUS_NORMAL;
391 }
392
393 static GIOFlags
394 g_io_unix_get_flags (GIOChannel *channel)
395 {
396   GIOFlags flags = 0;
397   glong fcntl_flags;
398   GIOUnixChannel *unix_channel = (GIOUnixChannel *) channel;
399
400   fcntl_flags = fcntl (unix_channel->fd, F_GETFL);
401
402   if (fcntl_flags == -1)
403     {
404       int err = errno;
405       g_warning (G_STRLOC "Error while getting flags for FD: %s (%d)\n",
406                  g_strerror (err), err);
407       return 0;
408     }
409
410   if (fcntl_flags & O_APPEND)
411     flags |= G_IO_FLAG_APPEND;
412 #ifdef O_NONBLOCK
413   if (fcntl_flags & O_NONBLOCK)
414 #else
415   if (fcntl_flags & O_NDELAY)
416 #endif
417     flags |= G_IO_FLAG_NONBLOCK;
418
419   switch (fcntl_flags & (O_RDONLY | O_WRONLY | O_RDWR))
420     {
421       case O_RDONLY:
422         channel->is_readable = TRUE;
423         channel->is_writeable = FALSE;
424         break;
425       case O_WRONLY:
426         channel->is_readable = FALSE;
427         channel->is_writeable = TRUE;
428         break;
429       case O_RDWR:
430         channel->is_readable = TRUE;
431         channel->is_writeable = TRUE;
432         break;
433       default:
434         g_assert_not_reached ();
435     }
436
437   return flags;
438 }
439
440 GIOChannel *
441 g_io_channel_new_file (const gchar *filename,
442                        const gchar *mode,
443                        GError     **error)
444 {
445   int fid, flags;
446   mode_t create_mode;
447   GIOChannel *channel;
448   enum { /* Cheesy hack */
449     MODE_R = 1 << 0,
450     MODE_W = 1 << 1,
451     MODE_A = 1 << 2,
452     MODE_PLUS = 1 << 3
453   } mode_num;
454   struct stat buffer;
455
456   g_return_val_if_fail (filename != NULL, NULL);
457   g_return_val_if_fail (mode != NULL, NULL);
458   g_return_val_if_fail ((error == NULL) || (*error == NULL), NULL);
459
460   switch (mode[0])
461     {
462       case 'r':
463         mode_num = MODE_R;
464         break;
465       case 'w':
466         mode_num = MODE_W;
467         break;
468       case 'a':
469         mode_num = MODE_A;
470         break;
471       default:
472         g_warning ("Invalid GIOFileMode %s.\n", mode);
473         return NULL;
474     }
475
476   switch (mode[1])
477     {
478       case '\0':
479         break;
480       case '+':
481         if (mode[2] == '\0')
482           {
483             mode_num |= MODE_PLUS;
484             break;
485           }
486         /* Fall through */
487       default:
488         g_warning ("Invalid GIOFileMode %s.\n", mode);
489         return NULL;
490     }
491
492   switch (mode_num)
493     {
494       case MODE_R:
495         flags = O_RDONLY;
496         break;
497       case MODE_W:
498         flags = O_WRONLY | O_TRUNC | O_CREAT;
499         break;
500       case MODE_A:
501         flags = O_WRONLY | O_APPEND | O_CREAT;
502         break;
503       case MODE_R | MODE_PLUS:
504         flags = O_RDWR;
505         break;
506       case MODE_W | MODE_PLUS:
507         flags = O_RDWR | O_TRUNC | O_CREAT;
508         break;
509       case MODE_A | MODE_PLUS:
510         flags = O_RDWR | O_APPEND | O_CREAT;
511         break;
512       default:
513         g_assert_not_reached ();
514         flags = 0;
515     }
516
517   create_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
518   fid = open (filename, flags, create_mode);
519   if (fid == -1)
520     {
521       int err = errno;
522       g_set_error_literal (error, G_FILE_ERROR,
523                            g_file_error_from_errno (err),
524                            g_strerror (err));
525       return (GIOChannel *)NULL;
526     }
527
528   if (fstat (fid, &buffer) == -1) /* In case someone opens a FIFO */
529     {
530       int err = errno;
531       close (fid);
532       g_set_error_literal (error, G_FILE_ERROR,
533                            g_file_error_from_errno (err),
534                            g_strerror (err));
535       return (GIOChannel *)NULL;
536     }
537
538   channel = (GIOChannel *) g_new (GIOUnixChannel, 1);
539
540   channel->is_seekable = S_ISREG (buffer.st_mode) || S_ISCHR (buffer.st_mode)
541                          || S_ISBLK (buffer.st_mode);
542
543   switch (mode_num)
544     {
545       case MODE_R:
546         channel->is_readable = TRUE;
547         channel->is_writeable = FALSE;
548         break;
549       case MODE_W:
550       case MODE_A:
551         channel->is_readable = FALSE;
552         channel->is_writeable = TRUE;
553         break;
554       case MODE_R | MODE_PLUS:
555       case MODE_W | MODE_PLUS:
556       case MODE_A | MODE_PLUS:
557         channel->is_readable = TRUE;
558         channel->is_writeable = TRUE;
559         break;
560       default:
561         g_assert_not_reached ();
562     }
563
564   g_io_channel_init (channel);
565   channel->close_on_unref = TRUE; /* must be after g_io_channel_init () */
566   channel->funcs = &unix_channel_funcs;
567
568   ((GIOUnixChannel *) channel)->fd = fid;
569   return channel;
570 }
571
572 /**
573  * g_io_channel_unix_new:
574  * @fd: a file descriptor.
575  * @Returns: a new #GIOChannel.
576  *
577  * Creates a new #GIOChannel given a file descriptor. On UNIX systems
578  * this works for plain files, pipes, and sockets.
579  *
580  * The returned #GIOChannel has a reference count of 1.
581  *
582  * The default encoding for #GIOChannel is UTF-8. If your application
583  * is reading output from a command using via pipe, you may need to set
584  * the encoding to the encoding of the current locale (see
585  * g_get_charset()) with the g_io_channel_set_encoding() function.
586  *
587  * If you want to read raw binary data without interpretation, then
588  * call the g_io_channel_set_encoding() function with %NULL for the
589  * encoding argument.
590  *
591  * This function is available in GLib on Windows, too, but you should
592  * avoid using it on Windows. The domain of file descriptors and
593  * sockets overlap. There is no way for GLib to know which one you mean
594  * in case the argument you pass to this function happens to be both a
595  * valid file descriptor and socket. If that happens a warning is
596  * issued, and GLib assumes that it is the file descriptor you mean.
597  **/
598 GIOChannel *
599 g_io_channel_unix_new (gint fd)
600 {
601   struct stat buffer;
602   GIOUnixChannel *unix_channel = g_new (GIOUnixChannel, 1);
603   GIOChannel *channel = (GIOChannel *)unix_channel;
604
605   g_io_channel_init (channel);
606   channel->funcs = &unix_channel_funcs;
607
608   unix_channel->fd = fd;
609
610   /* I'm not sure if fstat on a non-file (e.g., socket) works
611    * it should be safe to say if it fails, the fd isn't seekable.
612    */
613   /* Newer UNIX versions support S_ISSOCK(), fstat() will probably
614    * succeed in most cases.
615    */
616   if (fstat (unix_channel->fd, &buffer) == 0)
617     channel->is_seekable = S_ISREG (buffer.st_mode) || S_ISCHR (buffer.st_mode)
618                            || S_ISBLK (buffer.st_mode);
619   else /* Assume not seekable */
620     channel->is_seekable = FALSE;
621
622   g_io_unix_get_flags (channel); /* Sets is_readable, is_writeable */
623
624   return channel;
625 }
626
627 /**
628  * g_io_channel_unix_get_fd:
629  * @channel: a #GIOChannel, created with g_io_channel_unix_new().
630  * @Returns: the file descriptor of the #GIOChannel.
631  *
632  * Returns the file descriptor of the #GIOChannel.
633  *
634  * On Windows this function returns the file descriptor or socket of
635  * the #GIOChannel.
636  **/
637 gint
638 g_io_channel_unix_get_fd (GIOChannel *channel)
639 {
640   GIOUnixChannel *unix_channel = (GIOUnixChannel *)channel;
641   return unix_channel->fd;
642 }
643
644 #define __G_IO_UNIX_C__
645 #include "galiasdef.c"