libzypp  11.13.5
ExternalDataSource.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
15 #define _GNU_SOURCE 1 // for ::getline
16 
17 #include <signal.h>
18 #include <errno.h>
19 #include <unistd.h>
20 #include <sys/wait.h>
21 #include <fcntl.h>
22 #include <iostream>
23 #include <stdlib.h>
24 #include <string.h>
25 
26 #include <sstream>
27 #include <string>
28 
29 #include "zypp/base/Logger.h"
31 
32 using namespace std;
33 
34 namespace zypp {
35  namespace externalprogram {
36 
37  ExternalDataSource::ExternalDataSource (FILE *ifile, FILE *ofile)
38  : inputfile (ifile),
39  outputfile (ofile),
40  linebuffer (0),
41  linebuffer_size (0)
42  {
43  }
44 
45 
47  {
48  if (linebuffer)
49  free (linebuffer);
50  close ();
51  }
52 
53 
54  bool
55  ExternalDataSource::send (const char *buffer, size_t length)
56  {
57  if (outputfile) {
58  bool success = fwrite (buffer, length, 1, outputfile) != 0;
59  fflush (outputfile);
60  return success;
61  }
62  else
63  return false;
64  }
65 
66 
67  bool
68  ExternalDataSource::send (std::string s)
69  {
70  DBG << "send (" << s << ")";
71  return send(s.data(), s.length());
72  }
73 
74 
75  string
77  {
78  if (inputfile && !feof(inputfile))
79  {
80  std::ostringstream datas;
81  while ( true )
82  {
83  int readc = fgetc(inputfile);
84  if (readc == EOF) break;
85  datas << (char)readc;
86  if ((char)readc == c) break;
87  }
88  return datas.str();
89  }
90  return string();
91  }
92 
93 
94  size_t
95  ExternalDataSource::receive (char *buffer, size_t length)
96  {
97  if (inputfile)
98  return fread (buffer, 1, length, inputfile);
99  else
100  return 0;
101  }
102 
104  {
105  if(!inputfile) return;
106 
107  int fd = ::fileno(inputfile);
108 
109  if(fd == -1)
110  { ERR << strerror(errno) << endl; return; }
111 
112  int flags = ::fcntl(fd,F_GETFL);
113 
114  if(flags == -1)
115  { ERR << strerror(errno) << endl; return; }
116 
117  if(!mode)
118  flags = flags | O_NONBLOCK;
119  else if(flags & O_NONBLOCK)
120  flags = flags ^ O_NONBLOCK;
121 
122  flags = ::fcntl(fd,F_SETFL,flags);
123 
124  if(flags == -1)
125  { ERR << strerror(errno) << endl; return; }
126  }
127 
128  string
130  {
131  if (inputfile)
132  {
133  ssize_t nread = getline (&linebuffer, &linebuffer_size, inputfile);
134  if (nread == -1)
135  return "";
136  else
137  return string (linebuffer, nread);
138  }
139  else
140  return "";
141  }
142 
143 
144  int
146  {
147  if (inputfile && inputfile != outputfile)
148  fclose (inputfile);
149  if (outputfile)
150  fclose (outputfile);
151  inputfile = 0;
152  outputfile = 0;
153  return 0;
154  }
155 
156 
157  } // namespace externalprogram
158 } // namespace zypp
159