Switch to unified view

a b/src/netcon.h
1
#ifndef _NETCON_H_
2
#define _NETCON_H_
3
/* Copyright (C) 2002 Jean-Francois Dockes
4
 *   This program is free software; you can redistribute it and/or modify
5
 *   it under the terms of the GNU General Public License as published by
6
 *   the Free Software Foundation; either version 2 of the License, or
7
 *   (at your option) any later version.
8
 *
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.
13
 *
14
 *   You should have received a copy of the GNU General Public License
15
 *   along with this program; if not, write to the
16
 *   Free Software Foundation, Inc.,
17
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
 */
19
#include <sys/time.h>
20
#include <map>
21
#include <memory>
22
23
24
/// A set of classes to manage client-server communication over a
25
/// connection-oriented network, or a pipe.
26
///
27
/// The listening/connection-accepting code currently only uses
28
/// TCP. The classes include client-side and server-side (accepting)
29
/// endpoints. Netcon also has server-side static code to handle a set
30
/// of client connections in parallel. This should be moved to a
31
/// friend class.
32
///
33
/// The client data transfer class can also be used for
34
/// timeout-protected/asynchronous io using a given fd (ie a pipe
35
/// descriptor)
36
37
/// Base class for all network endpoints:
38
class Netcon;
39
typedef std::shared_ptr<Netcon> NetconP;
40
class SelectLoop;
41
42
class Netcon {
43
public:
44
    enum Event {NETCONPOLL_READ = 0x1, NETCONPOLL_WRITE = 0x2};
45
    Netcon()
46
        : m_peer(0), m_fd(-1), m_ownfd(true), m_didtimo(0), m_wantedEvents(0),
47
          m_loop(0) {
48
    }
49
    virtual ~Netcon();
50
    /// Remember whom we're talking to. We let external code do this because
51
    /// the application may have a non-dns method to find the peer name.
52
    virtual void setpeer(const char *hostname);
53
    /// Retrieve the peer's hostname. Only works if it was set before !
54
    virtual const char *getpeer() {
55
        return m_peer ? (const char *)m_peer : "none";
56
    }
57
    /// Set or reset the TCP_NODELAY option.
58
    virtual int settcpnodelay(int on = 1);
59
    /// Did the last receive() call time out ? Resets the flag.
60
    virtual int timedout() {
61
        int s = m_didtimo;
62
        m_didtimo = 0;
63
        return s;
64
    }
65
    /// Return string version of last syscall error
66
    virtual char *sterror();
67
    /// Return the socket descriptor
68
    virtual int getfd() {
69
        return m_fd;
70
    }
71
    /// Close the current connection if it is open
72
    virtual void closeconn();
73
    /// Set/reset the non-blocking flag on the underlying fd. Returns
74
    /// prev state The default is that sockets are blocking except
75
    /// when added to the selectloop, or, transparently, to handle
76
    /// connection timeout issues.
77
    virtual int set_nonblock(int onoff);
78
79
    /// Decide what events the connection will be looking for
80
    /// (NETCONPOLL_READ, NETCONPOLL_WRITE)
81
    int setselevents(int evs) {
82
        return m_wantedEvents = evs;
83
    }
84
    /// Retrieve the connection's currently monitored set of events
85
    int getselevents() {
86
        return m_wantedEvents;
87
    }
88
    /// Add events to current set
89
    int addselevents(int evs) {
90
        return m_wantedEvents |= evs;
91
    }
92
    /// Clear events from current set
93
    int clearselevents(int evs) {
94
        return m_wantedEvents &= ~evs;
95
    }
96
97
    friend class SelectLoop;
98
    SelectLoop *getloop() {
99
        return m_loop;
100
    }
101
102
    /// Utility function for a simplified select() interface: check one fd
103
    /// for reading or writing, for a specified maximum number of seconds.
104
    static int select1(int fd, int secs, int writing = 0);
105
106
protected:
107
    char *m_peer;   // Name of the connected host
108
    int   m_fd;
109
    bool  m_ownfd;
110
    int   m_didtimo;
111
    // Used when part of the selectloop map.
112
    short m_wantedEvents;
113
    SelectLoop *m_loop;
114
    // Method called by the selectloop when something can be done with a netcon
115
    virtual int cando(Netcon::Event reason) = 0;
116
    // Called when added to loop
117
    virtual void setloop(SelectLoop *loop) {
118
        m_loop = loop;
119
    }
120
};
121
122
123
/// The selectloop interface is used to implement parallel servers.
124
// The select loop mechanism allows several netcons to be used for io
125
// in a program without blocking as long as there is data to be read
126
// or written. In a multithread program which is also using select, it
127
// would typically make sense to have one SelectLoop active per
128
// thread.
129
class SelectLoop {
130
public:
131
    SelectLoop()
132
        : m_selectloopDoReturn(false), m_selectloopReturnValue(0),
133
          m_placetostart(0),
134
          m_periodichandler(0), m_periodicparam(0), m_periodicmillis(0) {
135
    }
136
137
    /// Loop waiting for events on the connections and call the
138
    /// cando() method on the object when something happens (this will in
139
    /// turn typically call the app callback set on the netcon). Possibly
140
    /// call the periodic handler (if set) at regular intervals.
141
    /// @return -1 for error. 0 if no descriptors left for i/o. 1 for periodic
142
    ///  timeout (should call back in after processing)
143
    int doLoop();
144
145
    /// Call from data handler: make selectloop return the param value
146
    void loopReturn(int value) {
147
        m_selectloopDoReturn = true;
148
        m_selectloopReturnValue = value;
149
    }
150
    /// Add a connection to be monitored (this will usually be called
151
    /// from the server's listen connection's accept callback)
152
    int addselcon(NetconP con, int events);
153
    /// Remove a connection from the monitored set. This is
154
    /// automatically called when EOF is detected on a connection.
155
    int remselcon(NetconP con);
156
157
    /// Set a function to be called periodically, or a time before return.
158
    /// @param handler the function to be called.
159
    ///  - if it is 0, selectloop() will return after ms mS (and can be called
160
    ///    again
161
    ///  - if it is not 0, it will be called at ms mS intervals. If its return
162
    ///    value is <= 0, selectloop will return.
163
    /// @param clp client data to be passed to handler at every call.
164
    /// @param ms milliseconds interval between handler calls or
165
    ///   before return. Set to 0 for no periodic handler.
166
    void setperiodichandler(int (*handler)(void *), void *clp, int ms);
167
168
private:
169
    // Set by client callback to tell selectloop to return.
170
    bool m_selectloopDoReturn;
171
    int  m_selectloopReturnValue;
172
    int  m_placetostart;
173
174
    // Map of NetconP indexed by fd
175
    std::map<int, NetconP> m_polldata;
176
177
    // The last time we did the periodic thing. Initialized by setperiodic()
178
    struct timeval m_lasthdlcall;
179
    // The call back function and its parameter
180
    int (*m_periodichandler)(void *);
181
    void *m_periodicparam;
182
    // The periodic interval
183
    int m_periodicmillis;
184
    void periodictimeout(struct timeval *tv);
185
    int maybecallperiodic();
186
};
187
188
///////////////////////
189
class NetconData;
190
191
/// Class for the application callback routine (when in selectloop).
192
///
193
/// This is set by the app on the NetconData by calling
194
/// setcallback(). It is then called from the NetconData's cando()
195
/// routine, itself called by selectloop.
196
///
197
/// It would be nicer to override cando() in a subclass instead of
198
/// setting a callback, but this can't be done conveniently because
199
/// accept() always creates a base NetconData (another approach would
200
/// be to pass a factory function to the listener, to create
201
/// NetconData derived classes).
202
class NetconWorker {
203
public:
204
    virtual ~NetconWorker() {}
205
    virtual int data(NetconData *con, Netcon::Event reason) = 0;
206
};
207
208
/// Base class for connections that actually transfer data. T
209
class NetconData : public Netcon {
210
public:
211
    NetconData() : m_buf(0), m_bufbase(0), m_bufbytes(0), m_bufsize(0) {
212
    }
213
    virtual ~NetconData();
214
215
    /// Write data to the connection.
216
    /// @param buf the data buffer
217
    /// @param cnt the number of bytes we should try to send
218
    /// @param expedited send data in as 'expedited' data.
219
    /// @return the count of bytes actually transferred, -1 if an
220
    ///  error occurred.
221
    virtual int send(const char *buf, int cnt, int expedited = 0);
222
223
    /// Read from the connection
224
    /// @param buf the data buffer
225
    /// @param cnt the number of bytes we should try to read (but we return
226
    ///   as soon as we get data)
227
    /// @param timeo maximum number of seconds we should be waiting for data.
228
    /// @return the count of bytes actually read. 0 for timeout (call
229
    ///        didtimo() to discriminate from EOF). -1 if an error occurred.
230
    virtual int receive(char *buf, int cnt, int timeo = -1);
231
    /// Loop on receive until cnt bytes are actually read or a timeout occurs
232
    virtual int doreceive(char *buf, int cnt, int timeo = -1);
233
    /// Check for data being available for reading
234
    virtual int readready();
235
    /// Check for data being available for writing
236
    virtual int writeready();
237
    /// Read a line of text on an ascii connection
238
    virtual int getline(char *buf, int cnt, int timeo = -1);
239
    /// Set handler to be called when the connection is placed in the
240
    /// selectloop and an event occurs.
241
    virtual void setcallback(std::shared_ptr<NetconWorker> user) {
242
        m_user = user;
243
    }
244
245
private:
246
    char *m_buf;    // Buffer. Only used when doing getline()s
247
    char *m_bufbase;    // Pointer to current 1st byte of useful data
248
    int m_bufbytes; // Bytes of data.
249
    int m_bufsize;  // Total buffer size
250
    std::shared_ptr<NetconWorker> m_user;
251
    virtual int cando(Netcon::Event reason); // Selectloop slot
252
};
253
254
/// Network endpoint, client side.
255
class NetconCli : public NetconData {
256
public:
257
    NetconCli(int silent = 0) {
258
        m_silentconnectfailure = silent;
259
    }
260
261
    /// Open connection to specified host and named service.
262
    int openconn(const char *host, char *serv, int timeo = -1);
263
264
    /// Open connection to specified host and numeric port. port is in
265
    /// HOST byte order
266
    int openconn(const char *host, unsigned int port, int timeo = -1);
267
268
    /// Reuse existing fd.
269
    /// We DONT take ownership of the fd, and do no closin' EVEN on an
270
    /// explicit closeconn() or setconn() (use getfd(), close,
271
    /// setconn(-1) if you need to really close the fd and have no
272
    /// other copy).
273
    int setconn(int fd);
274
275
    /// Do not log message if openconn() fails.
276
    void setSilentFail(int onoff) {
277
        m_silentconnectfailure = onoff;
278
    }
279
280
private:
281
    int m_silentconnectfailure; // No logging of connection failures if set
282
};
283
284
class NetconServCon;
285
#ifdef NETCON_ACCESSCONTROL
286
struct intarrayparam {
287
    int len;
288
    unsigned int *intarray;
289
};
290
#endif /* NETCON_ACCESSCONTROL */
291
292
/// Server listening end point.
293
///
294
/// if NETCON_ACCESSCONTROL is defined during compilation,
295
/// NetconServLis has primitive access control features: okaddrs holds
296
/// the host addresses for the hosts which we allow to connect to
297
/// us. okmasks holds the masks to be used for comparison.  okmasks
298
/// can be shorter than okaddrs, in which case we use the last entry
299
/// for all addrs beyond the masks array length. Both arrays are
300
/// retrieved from the configuration file when we create the endpoint
301
/// the key is either based on the service name (ex: cdpathdb_okaddrs,
302
/// cdpathdb_okmasks), or "default" if the service name is not found
303
/// (ex: default_okaddrs, default_okmasks)
304
class NetconServLis : public Netcon {
305
public:
306
    NetconServLis() {
307
#ifdef NETCON_ACCESSCONTROL
308
        permsinit = 0;
309
        okaddrs.len = okmasks.len = 0;
310
        okaddrs.intarray = okmasks.intarray = 0;
311
#endif /* NETCON_ACCESSCONTROL */
312
    }
313
    ~NetconServLis();
314
    /// Open named service.
315
    int openservice(char *serv, int backlog = 10);
316
    /// Open service by port number.
317
    int openservice(int port, int backlog = 10);
318
    /// Wait for incoming connection. Returned connected Netcon
319
    NetconServCon *accept(int timeo = -1);
320
321
protected:
322
    /// This should be overriden in a derived class to handle incoming
323
    /// connections. It will usually call NetconServLis::accept(), and
324
    /// insert the new connection in the selectloop.
325
    virtual int cando(Netcon::Event reason);
326
327
private:
328
#ifdef NETCON_ACCESSCONTROL
329
    int permsinit;
330
    struct intarrayparam okaddrs;
331
    struct intarrayparam okmasks;
332
    int initperms(char *servicename);
333
    int initperms(int port);
334
    int checkperms(void *cli, int clilen);
335
#endif /* NETCON_ACCESSCONTROL */
336
};
337
338
/// Server-side accepted client connection. The only specific code
339
/// allows closing the listening endpoint in the child process (in the
340
/// case of a forking server)
341
class NetconServCon : public NetconData {
342
public:
343
    NetconServCon(int newfd, Netcon* lis = 0) {
344
        m_liscon = lis;
345
        m_fd = newfd;
346
    }
347
    /// This is for forked servers that want to get rid of the main socket
348
    void closeLisCon() {
349
        if (m_liscon) {
350
            m_liscon->closeconn();
351
        }
352
    }
353
private:
354
    Netcon* m_liscon;
355
};
356
357
#endif /* _NETCON_H_ */