Merge commit 'release-4-0-0alpha15' into master4-tmp
[amitay/samba.git] / source4 / smbd / service_stream.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    helper functions for stream based servers
5
6    Copyright (C) Andrew Tridgell 2003-2005
7    Copyright (C) Stefan (metze) Metzmacher      2004
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include <tevent.h>
25 #include "process_model.h"
26 #include "lib/messaging/irpc.h"
27 #include "cluster/cluster.h"
28 #include "param/param.h"
29 #include "../lib/tsocket/tsocket.h"
30 #include "lib/util/util_net.h"
31
32 /* the range of ports to try for dcerpc over tcp endpoints */
33 #define SERVER_TCP_LOW_PORT  1024
34 #define SERVER_TCP_HIGH_PORT 1300
35
36 /* size of listen() backlog in smbd */
37 #define SERVER_LISTEN_BACKLOG 10
38
39
40 /*
41   private structure for a single listening stream socket
42 */
43 struct stream_socket {
44         const struct stream_server_ops *ops;
45         struct loadparm_context *lp_ctx;
46         struct tevent_context *event_ctx;
47         const struct model_ops *model_ops;
48         struct socket_context *sock;
49         void *private_data;
50 };
51
52
53 /*
54   close the socket and shutdown a stream_connection
55 */
56 void stream_terminate_connection(struct stream_connection *srv_conn, const char *reason)
57 {
58         struct tevent_context *event_ctx = srv_conn->event.ctx;
59         const struct model_ops *model_ops = srv_conn->model_ops;
60
61         if (!reason) reason = "unknown reason";
62
63         DEBUG(3,("Terminating connection - '%s'\n", reason));
64
65         srv_conn->terminate = reason;
66
67         if (srv_conn->processing) {
68                 /* 
69                  * if we're currently inside the stream_io_handler(),
70                  * defer the termination to the end of stream_io_hendler()
71                  *
72                  * and we don't want to read or write to the connection...
73                  */
74                 tevent_fd_set_flags(srv_conn->event.fde, 0);
75                 return;
76         }
77
78         talloc_free(srv_conn->event.fde);
79         srv_conn->event.fde = NULL;
80         model_ops->terminate(event_ctx, srv_conn->lp_ctx, reason);
81         talloc_free(srv_conn);
82 }
83
84 /**
85   the select loop has indicated that a stream is ready for IO
86 */
87 static void stream_io_handler(struct stream_connection *conn, uint16_t flags)
88 {
89         conn->processing++;
90         if (flags & TEVENT_FD_WRITE) {
91                 conn->ops->send_handler(conn, flags);
92         } else if (flags & TEVENT_FD_READ) {
93                 conn->ops->recv_handler(conn, flags);
94         }
95         conn->processing--;
96
97         if (conn->terminate) {
98                 stream_terminate_connection(conn, conn->terminate);
99         }
100 }
101
102 void stream_io_handler_fde(struct tevent_context *ev, struct tevent_fd *fde,
103                                   uint16_t flags, void *private_data)
104 {
105         struct stream_connection *conn = talloc_get_type(private_data,
106                                                          struct stream_connection);
107         stream_io_handler(conn, flags);
108 }
109
110 void stream_io_handler_callback(void *private_data, uint16_t flags)
111 {
112         struct stream_connection *conn = talloc_get_type(private_data,
113                                                          struct stream_connection);
114         stream_io_handler(conn, flags);
115 }
116
117 /*
118   this creates a stream_connection from an already existing connection,
119   used for protocols, where a client connection needs to switched into
120   a server connection
121 */
122 NTSTATUS stream_new_connection_merge(struct tevent_context *ev,
123                                      struct loadparm_context *lp_ctx,
124                                      const struct model_ops *model_ops,
125                                      const struct stream_server_ops *stream_ops,
126                                      struct imessaging_context *msg_ctx,
127                                      void *private_data,
128                                      struct stream_connection **_srv_conn)
129 {
130         struct stream_connection *srv_conn;
131
132         srv_conn = talloc_zero(ev, struct stream_connection);
133         NT_STATUS_HAVE_NO_MEMORY(srv_conn);
134
135         srv_conn->private_data  = private_data;
136         srv_conn->model_ops     = model_ops;
137         srv_conn->socket        = NULL;
138         srv_conn->server_id     = cluster_id(0, 0);
139         srv_conn->ops           = stream_ops;
140         srv_conn->msg_ctx       = msg_ctx;
141         srv_conn->event.ctx     = ev;
142         srv_conn->lp_ctx        = lp_ctx;
143         srv_conn->event.fde     = NULL;
144
145         *_srv_conn = srv_conn;
146         return NT_STATUS_OK;
147 }
148
149 /*
150   called when a new socket connection has been established. This is called in the process
151   context of the new process (if appropriate)
152 */
153 static void stream_new_connection(struct tevent_context *ev,
154                                   struct loadparm_context *lp_ctx,
155                                   struct socket_context *sock, 
156                                   struct server_id server_id, void *private_data)
157 {
158         struct stream_socket *stream_socket = talloc_get_type(private_data, struct stream_socket);
159         struct stream_connection *srv_conn;
160
161         srv_conn = talloc_zero(ev, struct stream_connection);
162         if (!srv_conn) {
163                 DEBUG(0,("talloc(mem_ctx, struct stream_connection) failed\n"));
164                 return;
165         }
166
167         talloc_steal(srv_conn, sock);
168
169         srv_conn->private_data  = stream_socket->private_data;
170         srv_conn->model_ops     = stream_socket->model_ops;
171         srv_conn->socket        = sock;
172         srv_conn->server_id     = server_id;
173         srv_conn->ops           = stream_socket->ops;
174         srv_conn->event.ctx     = ev;
175         srv_conn->lp_ctx        = lp_ctx;
176
177         if (!socket_check_access(sock, "smbd", lpcfg_hostsallow(NULL, lpcfg_default_service(lp_ctx)), lpcfg_hostsdeny(NULL, lpcfg_default_service(lp_ctx)))) {
178                 stream_terminate_connection(srv_conn, "denied by access rules");
179                 return;
180         }
181
182         srv_conn->event.fde     = tevent_add_fd(ev, srv_conn, socket_get_fd(sock),
183                                                 0, stream_io_handler_fde, srv_conn);
184         if (!srv_conn->event.fde) {
185                 stream_terminate_connection(srv_conn, "tevent_add_fd() failed");
186                 return;
187         }
188
189         /* setup to receive internal messages on this connection */
190         srv_conn->msg_ctx = imessaging_init(srv_conn,
191                                            lpcfg_imessaging_path(srv_conn, lp_ctx),
192                                            srv_conn->server_id, ev);
193         if (!srv_conn->msg_ctx) {
194                 stream_terminate_connection(srv_conn, "imessaging_init() failed");
195                 return;
196         }
197
198         srv_conn->remote_address = socket_get_remote_addr(srv_conn->socket, srv_conn);
199         if (!srv_conn->remote_address) {
200                 stream_terminate_connection(srv_conn, "socket_get_remote_addr() failed");
201                 return;
202         }
203
204         srv_conn->local_address = socket_get_local_addr(srv_conn->socket, srv_conn);
205         if (!srv_conn->local_address) {
206                 stream_terminate_connection(srv_conn, "socket_get_local_addr() failed");
207                 return;
208         }
209
210         {
211                 TALLOC_CTX *tmp_ctx;
212                 const char *title;
213
214                 tmp_ctx = talloc_new(srv_conn);
215
216                 title = talloc_asprintf(tmp_ctx, "conn[%s] c[%s] s[%s] server_id[%s]",
217                                         stream_socket->ops->name, 
218                                         tsocket_address_string(srv_conn->remote_address, tmp_ctx),
219                                         tsocket_address_string(srv_conn->local_address, tmp_ctx),
220                                         server_id_str(tmp_ctx, &server_id));
221                 if (title) {
222                         stream_connection_set_title(srv_conn, title);
223                 }
224                 talloc_free(tmp_ctx);
225         }
226
227         /* we're now ready to start receiving events on this stream */
228         TEVENT_FD_READABLE(srv_conn->event.fde);
229
230         /* call the server specific accept code */
231         stream_socket->ops->accept_connection(srv_conn);
232 }
233
234
235 /*
236   called when someone opens a connection to one of our listening ports
237 */
238 static void stream_accept_handler(struct tevent_context *ev, struct tevent_fd *fde, 
239                                   uint16_t flags, void *private_data)
240 {
241         struct stream_socket *stream_socket = talloc_get_type(private_data, struct stream_socket);
242
243         /* ask the process model to create us a process for this new
244            connection.  When done, it calls stream_new_connection()
245            with the newly created socket */
246         stream_socket->model_ops->accept_connection(ev, stream_socket->lp_ctx,
247                                                     stream_socket->sock, 
248                                                     stream_new_connection, stream_socket);
249 }
250
251 /*
252   setup a listen stream socket
253   if you pass *port == 0, then a port > 1024 is used
254
255   FIXME: This function is TCP/IP specific - uses an int rather than 
256          a string for the port. Should leave allocating a port nr 
257          to the socket implementation - JRV20070903
258  */
259 NTSTATUS stream_setup_socket(TALLOC_CTX *mem_ctx,
260                              struct tevent_context *event_context,
261                              struct loadparm_context *lp_ctx,
262                              const struct model_ops *model_ops,
263                              const struct stream_server_ops *stream_ops,
264                              const char *family,
265                              const char *sock_addr,
266                              uint16_t *port,
267                              const char *socket_options,
268                              void *private_data)
269 {
270         NTSTATUS status;
271         struct stream_socket *stream_socket;
272         struct socket_address *socket_address;
273         struct tevent_fd *fde;
274         int i;
275         struct sockaddr_storage ss;
276
277         stream_socket = talloc_zero(mem_ctx, struct stream_socket);
278         NT_STATUS_HAVE_NO_MEMORY(stream_socket);
279
280         if (strcmp(family, "ip") == 0) {
281                 /* we will get the real family from the address itself */
282                 if (!interpret_string_addr(&ss, sock_addr, 0)) {
283                         talloc_free(stream_socket);
284                         return NT_STATUS_INVALID_ADDRESS;
285                 }
286
287                 socket_address = socket_address_from_sockaddr_storage(stream_socket, &ss, port?*port:0);
288                 NT_STATUS_HAVE_NO_MEMORY_AND_FREE(socket_address, stream_socket);
289
290                 status = socket_create(socket_address->family, SOCKET_TYPE_STREAM, &stream_socket->sock, 0);
291                 NT_STATUS_NOT_OK_RETURN(status);
292         } else {
293                 status = socket_create(family, SOCKET_TYPE_STREAM, &stream_socket->sock, 0);
294                 NT_STATUS_NOT_OK_RETURN(status);
295
296                 /* this is for non-IP sockets, eg. unix domain sockets */
297                 socket_address = socket_address_from_strings(stream_socket,
298                                                              stream_socket->sock->backend_name,
299                                                              sock_addr, port?*port:0);
300                 NT_STATUS_HAVE_NO_MEMORY(socket_address);
301         }
302
303
304         talloc_steal(stream_socket, stream_socket->sock);
305
306         stream_socket->lp_ctx = talloc_reference(stream_socket, lp_ctx);
307
308         /* ready to listen */
309         status = socket_set_option(stream_socket->sock, "SO_KEEPALIVE", NULL);
310         NT_STATUS_NOT_OK_RETURN(status);
311
312         if (socket_options != NULL) {
313                 status = socket_set_option(stream_socket->sock, socket_options, NULL);
314                 NT_STATUS_NOT_OK_RETURN(status);
315         }
316
317         /* TODO: set socket ACL's (host allow etc) here when they're
318          * implemented */
319
320         /* Some sockets don't have a port, or are just described from
321          * the string.  We are indicating this by having port == NULL */
322         if (!port) {
323                 status = socket_listen(stream_socket->sock, socket_address, SERVER_LISTEN_BACKLOG, 0);
324         } else if (*port == 0) {
325                 for (i=SERVER_TCP_LOW_PORT;i<= SERVER_TCP_HIGH_PORT;i++) {
326                         socket_address->port = i;
327                         status = socket_listen(stream_socket->sock, socket_address, 
328                                                SERVER_LISTEN_BACKLOG, 0);
329                         if (NT_STATUS_IS_OK(status)) {
330                                 *port = i;
331                                 break;
332                         }
333                 }
334         } else {
335                 status = socket_listen(stream_socket->sock, socket_address, SERVER_LISTEN_BACKLOG, 0);
336         }
337
338         if (!NT_STATUS_IS_OK(status)) {
339                 DEBUG(0,("Failed to listen on %s:%u - %s\n",
340                          sock_addr, port ? (unsigned int)(*port) : 0,
341                          nt_errstr(status)));
342                 talloc_free(stream_socket);
343                 return status;
344         }
345
346         /* Add the FD from the newly created socket into the event
347          * subsystem.  it will call the accept handler whenever we get
348          * new connections */
349
350         fde = tevent_add_fd(event_context, stream_socket->sock,
351                             socket_get_fd(stream_socket->sock),
352                             TEVENT_FD_READ,
353                             stream_accept_handler, stream_socket);
354         if (!fde) {
355                 DEBUG(0,("Failed to setup fd event\n"));
356                 talloc_free(stream_socket);
357                 return NT_STATUS_NO_MEMORY;
358         }
359
360         /* we let events system to the close on the socket. This avoids
361          * nasty interactions with waiting for talloc to close the socket. */
362         tevent_fd_set_close_fn(fde, socket_tevent_fd_close_fn);
363         socket_set_flags(stream_socket->sock, SOCKET_FLAG_NOCLOSE);
364
365         stream_socket->private_data     = talloc_reference(stream_socket, private_data);
366         stream_socket->ops              = stream_ops;
367         stream_socket->event_ctx        = event_context;
368         stream_socket->model_ops        = model_ops;
369
370         return NT_STATUS_OK;
371 }
372
373
374 /*
375   setup a connection title 
376 */
377 void stream_connection_set_title(struct stream_connection *conn, const char *title)
378 {
379         conn->model_ops->set_title(conn->event.ctx, title);
380 }