Navigation


source: freeDiameter/include/freeDiameter/freeDiameter.h @ 20:277ec00d793e

Last change on this file since 20:277ec00d793e was 20:277ec00d793e, checked in by Sebastien Decugis <sdecugis@nict.go.jp>, 12 years ago

Backup before typhoon... Progress on server side

File size: 20.4 KB
Line 
1/*********************************************************************************************************
2* Software License Agreement (BSD License)                                                               *
3* Author: Sebastien Decugis <sdecugis@nict.go.jp>                                                        *
4*                                                                                                        *
5* Copyright (c) 2009, WIDE Project and NICT                                                              *
6* All rights reserved.                                                                                   *
7*                                                                                                        *
8* Redistribution and use of this software in source and binary forms, with or without modification, are  *
9* permitted provided that the following conditions are met:                                              *
10*                                                                                                        *
11* * Redistributions of source code must retain the above                                                 *
12*   copyright notice, this list of conditions and the                                                    *
13*   following disclaimer.                                                                                *
14*                                                                                                        *
15* * Redistributions in binary form must reproduce the above                                              *
16*   copyright notice, this list of conditions and the                                                    *
17*   following disclaimer in the documentation and/or other                                               *
18*   materials provided with the distribution.                                                            *
19*                                                                                                        *
20* * Neither the name of the WIDE Project or NICT nor the                                                 *
21*   names of its contributors may be used to endorse or                                                  *
22*   promote products derived from this software without                                                  *
23*   specific prior written permission of WIDE Project and                                                *
24*   NICT.                                                                                                *
25*                                                                                                        *
26* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED *
27* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *
28* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR *
29* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT     *
30* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS    *
31* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR *
32* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF   *
33* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                                                             *
34*********************************************************************************************************/
35
36#ifndef _FREEDIAMETER_H
37#define _FREEDIAMETER_H
38
39
40#include <freeDiameter/libfreeDiameter.h>
41#include <gnutls/gnutls.h>
42#include <gnutls/x509.h>
43
44/* GNUTLS version */
45#ifndef GNUTLS_VERSION
46#define GNUTLS_VERSION LIBGNUTLS_VERSION
47#endif /* GNUTLS_VERSION */
48
49/* Check the return value of a GNUTLS function, log and propagate */
50#define CHECK_GNUTLS_DO( __call__, __fallback__ ) {                                             \
51        int __ret__;                                                                            \
52        TRACE_DEBUG_ALL( "Check FCT: " #__call__ );                                             \
53        __ret__ = (__call__);                                                                   \
54        if (__ret__ < 0) {                                                                      \
55                TRACE_DEBUG(INFO, "Error in '" #__call__ "':\t%s", gnutls_strerror(__ret__));   \
56                __fallback__;                                                                   \
57        }                                                                                       \
58}
59
60
61/* Structure to hold the configuration of the freeDiameter daemon */
62struct fd_config {
63        int              cnf_eyec;      /* Eye catcher: EYEC_CONFIG */
64                        #define EYEC_CONFIG     0xC011F16
65       
66        char            *cnf_file;      /* Configuration file to parse, default is DEFAULT_CONF_FILE */
67       
68        char            *cnf_diamid;    /* Diameter Identity of the local peer (FQDN -- UTF-8) */
69        size_t           cnf_diamid_len;        /* length of the previous string */
70        char            *cnf_diamrlm;   /* Diameter realm of the local peer, default to realm part of diam_id */
71        size_t           cnf_diamrlm_len;/* length of the previous string */
72       
73        unsigned int     cnf_timer_tc;  /* The value in seconds of the default Tc timer */
74        unsigned int     cnf_timer_tw;  /* The value in seconds of the default Tw timer */
75       
76        uint16_t         cnf_port;      /* the local port for legacy Diameter (default: 3868) in host byte order */
77        uint16_t         cnf_port_tls;  /* the local port for Diameter/TLS (default: 3869) in host byte order */
78        uint16_t         cnf_sctp_str;  /* default max number of streams for SCTP associations (def: 30) */
79        struct fd_list   cnf_endpoints; /* the local endpoints to bind the server to. list of struct fd_endpoint. default is empty (bind all) */
80        struct fd_list   cnf_apps;      /* Applications locally supported (except relay, see flags). Use fd_disp_app_support to add one. list of struct fd_app. */
81        struct {
82                unsigned no_fwd : 1;    /* the peer does not relay messages (0xffffff app id) */
83                unsigned no_ip4 : 1;    /* disable IP */
84                unsigned no_ip6 : 1;    /* disable IPv6 */
85                unsigned no_tcp : 1;    /* disable use of TCP */
86                unsigned no_sctp: 1;    /* disable the use of SCTP */
87                unsigned pr_tcp : 1;    /* prefer TCP over SCTP */
88                unsigned tls_alg: 1;    /* TLS algorithm for initiated cnx. 0: separate port. 1: inband-security (old) */
89        }                cnf_flags;
90       
91        struct {
92                /* Credentials parameters (backup) */
93                char *                           cert_file;
94                char *                           key_file;
95               
96                char *                           ca_file;
97                char *                           crl_file;
98               
99                char *                           prio_string;
100                unsigned int                     dh_bits;
101               
102                /* GNUTLS parameters */
103                gnutls_priority_t                prio_cache;
104                gnutls_dh_params_t               dh_cache;
105               
106                /* GNUTLS server credential(s) */
107                gnutls_certificate_credentials_t credentials;
108               
109        }                cnf_sec_data;
110       
111        uint32_t         cnf_orstateid; /* The value to use in Origin-State-Id, default to random value */
112        struct dictionary *cnf_dict;    /* pointer to the global dictionary */
113        struct fifo       *cnf_main_ev; /* events for the daemon's main (struct fd_event items) */
114};
115extern struct fd_config *fd_g_config; /* The pointer to access the global configuration, initalized in main */
116
117/* Endpoints */
118struct fd_endpoint {
119        struct fd_list  chain;  /* link in cnf_endpoints list */
120        sSS             ss;     /* the socket information. List is always ordered by ss value (memcmp) */
121        struct {
122                unsigned conf : 1; /* This endpoint is statically configured in a configuration file */
123                unsigned disc : 1; /* This endpoint was resolved from the Diameter Identity or other DNS query */
124                unsigned adv  : 1; /* This endpoint was advertized in Diameter CER/CEA exchange */
125                unsigned ll   : 1; /* Lower layer mechanism provided this endpoint */
126               
127                /* To add: a validity timestamp for DNS records ? How do we retrieve this lifetime from DNS ? */
128
129        }               meta;   /* Additional information about the endpoint */
130};
131
132/* Applications */
133struct fd_app {
134        struct fd_list   chain; /* link in cnf_apps list. List ordered by appid. */
135        struct {
136                unsigned auth   : 1;
137                unsigned acct   : 1;
138                unsigned common : 1;
139        }                flags;
140        vendor_id_t      vndid; /* if not 0, Vendor-Specific-App-Id AVP will be used */
141        application_id_t appid; /* The identifier of the application */
142};
143       
144
145/* Events */
146struct fd_event {
147        int      code; /* codespace depends on the queue */
148        void    *data;
149};
150
151static __inline__ int fd_event_send(struct fifo *queue, int code, void * data)
152{
153        struct fd_event * ev;
154        CHECK_MALLOC( ev = malloc(sizeof(struct fd_event)) );
155        ev->code = code;
156        ev->data = data;
157        CHECK_FCT( fd_fifo_post(queue, &ev) );
158        return 0;
159}
160static __inline__ int fd_event_get(struct fifo *queue, int *code, void ** data)
161{
162        struct fd_event * ev;
163        CHECK_FCT( fd_fifo_get(queue, &ev) );
164        if (code)
165                *code = ev->code;
166        if (data)
167                *data = ev->data;
168        free(ev);
169        return 0;
170}
171
172/* Events codespace for fd_g_config->cnf_main_ev */
173enum {
174         FDEV_TERMINATE = 1000  /* request to terminate */
175        ,FDEV_DUMP_DICT         /* Dump the content of the dictionary */
176        ,FDEV_DUMP_EXT          /* Dump state of extensions */
177        ,FDEV_DUMP_SERV         /* Dump the server socket status */
178        ,FDEV_DUMP_QUEUES       /* Dump the message queues */
179        ,FDEV_DUMP_CONFIG       /* Dump the configuration */
180        ,FDEV_DUMP_PEERS        /* Dump the list of peers */
181};
182const char * fd_ev_str(int event); /* defined in freeDiameter/main.c */
183
184
185/***************************************/
186/*   Peers information                 */
187/***************************************/
188
189/* States of a peer */
190enum peer_state {
191        /* Stable states */
192        STATE_NEW = 0,          /* The peer has been just been created, PSM thread not started yet */
193        STATE_OPEN,             /* Connexion established */
194       
195        /* Peer state machine */
196        STATE_CLOSED,           /* No connection established, will re-attempt after TcTimer. */
197        STATE_CLOSING,          /* the connection is being shutdown (DPR/DPA in progress) */
198        STATE_WAITCNXACK,       /* Attempting to establish transport-level connection */
199        STATE_WAITCNXACK_ELEC,  /* Received a CER from this same peer on an incoming connection (other peer object), while we were waiting for cnx ack */
200        STATE_WAITCEA,          /* Connection established, CER sent, waiting for CEA */
201        /* STATE_WAITRETURNS_ELEC, */   /* This state is not stable and therefore deprecated:
202                                   We have sent a CER on our initiated connection, and received a CER from the remote peer on another connection. Election.
203                                   If we win the election, we must disconnect the initiated connection and send a CEA on the other => we go to OPEN state.
204                                   If we lose, we disconnect the other connection (receiver) and fallback to WAITCEA state. */
205        STATE_OPEN_HANDSHAKE,   /* TLS Handshake and validation are in progress in open state */
206       
207        /* Failover state machine */
208        STATE_SUSPECT,          /* A DWR was sent and not answered within TwTime. Failover in progress. */
209        STATE_REOPEN,           /* Connection has been re-established, waiting for 3 DWR/DWA exchanges before putting back to service */
210       
211        /* Error state */
212        STATE_ZOMBIE            /* The PSM thread is not running anymore; it must be re-started or peer should be deleted. */
213#define STATE_MAX STATE_ZOMBIE
214};
215extern const char *peer_state_str[]; /* defined in freeDiameter/p_psm.c */
216#define STATE_STR(state) \
217        (((unsigned)(state)) <= STATE_MAX ? peer_state_str[((unsigned)(state)) ] : "<Invalid>")
218
219/* Information about a remote peer. Same structure is used for creating a new entry, but not all fields are meaningful in that case */
220struct peer_info {
221       
222        char *          pi_diamid;      /* UTF-8, \0 terminated. The Diameter Identity of the remote peer */
223        char *          pi_realm;       /* Its realm, as received in CER/CEA exchange. */
224       
225        struct {
226                #define PI_P3_DEFAULT   0       /* Use the default L3 protocol configured for the host */
227                #define PI_P3_IP        1       /* Use only IP to connect to this peer */
228                #define PI_P3_IPv6      2       /* resp, IPv6 */
229                unsigned        pro3 :2;
230               
231                #define PI_P4_DEFAULT   0       /* Use the default L4 proto configured for the host */
232                #define PI_P4_TCP       1       /* Only use TCP */
233                #define PI_P4_SCTP      2       /* Only use SCTP */
234                unsigned        pro4 :2;
235               
236                #define PI_ALGPREF_SCTP 0       /* SCTP is initially attempted */
237                #define PI_ALGPREF_TCP  1       /* TCP is initially attempted */
238                unsigned        alg :1;
239               
240                #define PI_SEC_DEFAULT  0       /* New TLS security (dedicated port protecting also CER/CEA) */
241                #define PI_SEC_NONE     1       /* Transparent security with this peer (IPsec) */
242                #define PI_SEC_TLS_OLD  2       /* Old TLS security (inband on default port) */
243                unsigned        sec :2;
244               
245                #define PI_EXP_NONE     0       /* the peer entry does not expire */
246                #define PI_EXP_INACTIVE 1       /* the peer entry expires (i.e. is deleted) after pi_lft seconds without activity */
247                unsigned        exp :1;
248               
249                unsigned        inband_none :1; /* This is only meaningful with pi_flags.sec == 3 */
250                unsigned        inband_tls  :1; /* This is only meaningful with pi_flags.sec == 3 */
251               
252                unsigned        relay :1;       /* The remote peer advertized the relay application */
253
254        }               pi_flags;       /* Some flags */
255       
256        /* Additional parameters */
257        uint32_t        pi_lft;         /* lifetime of this peer when inactive (see pi_flags.exp definition) */
258        uint16_t        pi_streams;     /* number of streams for SCTP. 0 = default */
259        uint16_t        pi_port;        /* port to connect to. 0: default. */
260        int             pi_tctimer;     /* use this value for TcTimer instead of global, if != 0 */
261        int             pi_twtimer;     /* use this value for TwTimer instead of global, if != 0 */
262       
263        struct fd_list  pi_endpoints;   /* Endpoint(s) of the remote peer (configured, discovered, or advertized). list of struct fd_endpoint. DNS resolved if empty. */
264       
265        /* The remaining information must not be modified, and is not used for peer creation */
266        enum peer_state pi_state;
267        uint32_t        pi_vendorid;    /* Content of the Vendor-Id AVP, or 0 by default */
268        uint32_t        pi_orstate;     /* Origin-State-Id value */
269        char *          pi_prodname;    /* copy of UTF-8 Product-Name AVP (\0 terminated) */
270        uint32_t        pi_firmrev;     /* Content of the Firmware-Revision AVP */
271        struct fd_list  pi_apps;        /* applications advertised by the remote peer, except relay (pi_flags.relay) */
272        struct {
273                /* This is inspired from http://www.gnu.org/software/gnutls/manual/gnutls.html#ex_003ax509_002dinfo */
274                const gnutls_datum_t    *cert_list;     /* The (valid) credentials that the peer has presented */
275                unsigned int             cert_list_size;/* Number of certificates in the list */
276        }               pi_sec_data;
277};
278
279struct peer_hdr {
280        struct fd_list   chain; /* List of all the peers, ordered by their Diameter Id */
281        struct peer_info info;  /* The public data */
282       
283        /* This header is followed by more data in the private peer structure definition */
284};
285
286/* the global list of peers.
287  Since we are not expecting so many connections, we don't use a hash, but it might be changed.
288  The list items are peer_hdr structures (actually, fd_peer, but the cast is OK) */
289extern struct fd_list fd_g_peers;
290extern pthread_rwlock_t fd_g_peers_rw; /* protect the list */
291
292/*
293 * FUNCTION:    fd_peer_add
294 *
295 * PARAMETERS:
296 *  info        : Information to create the peer.
297 *  orig_dbg    : A string indicating the origin of the peer information, for debug (ex: conf, redirect, ...)
298 *  cb          : optional, a callback to call (once) when the peer connection is established or failed
299 *  cb_data     : opaque data to pass to the callback.
300 *
301 * DESCRIPTION:
302 *  Add a peer to the list of peers to which the daemon must maintain a connexion.
303 *
304 *  The content of info parameter is copied, except for the list of endpoints if
305 * not empty, which is simply moved into the created object. It means that the list
306 * items must have been malloc'd, so that they can be freed.
307 *
308 *  If cb is not null, the callback is called when the connection is in OPEN state or
309 * when an error has occurred. The callback should use the pi_state information to
310 * determine which one it is. If the first parameter of the called callback is NULL, it
311 * means that the peer is being destroyed before attempt success / failure.
312 * cb is called to allow freeing cb_data in  * this case.
313 *
314 *  The orig_dbg string is only useful for easing debug, and can be left to NULL.
315 *
316 * RETURN VALUE:
317 *  0           : The peer is added.
318 *  EINVAL      : A parameter is invalid.
319 *  EEXIST      : A peer with the same Diameter-Id is already in the list.
320 *  (other standard errors may be returned, too, with their standard meaning. Example:
321 *    ENOMEM    : Memory allocation for the new object element failed.)
322 */
323int fd_peer_add ( struct peer_info * info, char * orig_dbg, void (*cb)(struct peer_info *, void *), void * cb_data );
324
325/*
326 * FUNCTION:    peer_validate_register
327 *
328 * PARAMETERS:
329 *  peer_validate       : Callback as defined bellow.
330 *
331 * DESCRIPTION:
332 *  Add a callback to authorize / reject incoming peer connections.
333 * All registered callbacks are called until a callback sets auth = -1 or auth = 1.
334 * If no callback returns a clear decision, the default behavior is applied (reject unknown connections)
335 *
336 * RETURN VALUE:
337 *  0   : The callback is added.
338 * !0   : An error occurred.
339 */
340int fd_peer_validate_register ( int (*peer_validate)(struct peer_info * /* info */, int * /* auth */, int (**cb2)(struct peer_info *)) );
341/*
342 * CALLBACK:    peer_validate
343 *
344 * PARAMETERS:
345 *   info     : Structure containing information about the peer attempting the connection.
346 *   auth     : Store there the result if the peer is accepted (1), rejected (-1), or unknown (0).
347 *   cb2      : If != NULL and in case of PI_SEC_TLS_OLD, another callback to call after handshake (if auth = 1).
348 *
349 * DESCRIPTION:
350 *   This callback is called when a new connection is being established from an unknown peer,
351 * after the CER is received. An extension must register such callback with peer_validate_register.
352 *
353 *   If (info->pi_flags.sec == PI_SEC_TLS_OLD) the extension may instruct the daemon explicitely
354 * to not use TLS by clearing info->pi_flags.inband_tls -- only if inband_none is set.
355 *
356 *   If (info->pi_flags.sec == PI_SEC_TLS_OLD) and info->pi_flags.inband_tls is set,
357 * the extension may also need to check the credentials provided during the TLS
358 * exchange (remote certificate). For this purpose, it may set the address of a new callback
359 * to be called once the handshake is completed. This new callback receives the information
360 * structure as parameter (with pi_sec_data set) and returns 0 if the credentials are correct,
361 * or an error code otherwise. If the error code is received, the connection is closed and the
362 * peer is destroyed.
363 *
364 * RETURN VALUE:
365 *  0           : The authorization decision has been written in the location pointed by auth.
366 *  !0          : An error occurred.
367 */
368
369/***************************************/
370/*   Sending a message on the network  */
371/***************************************/
372
373/*
374 * FUNCTION:    fd_msg_send
375 *
376 * PARAMETERS:
377 *  pmsg        : Location of the message to be sent on the network (set to NULL on function return to avoid double deletion).
378 *  anscb       : A callback to be called when answer is received, if msg is a request (optional)
379 *  anscb_data  : opaque data to be passed back to the anscb when it is called.
380 *
381 * DESCRIPTION:
382 *   Sends a message on the network. (actually simply queues it in a global queue, to be picked by a daemon's thread)
383 * For requests, the end-to-end id must be set (see fd_msg_get_eteid / MSGFL_ALLOC_ETEID).
384 * For answers, the message must be created with function fd_msg_new_answ.
385 *
386 * The routing module will handle sending to the correct peer, usually based on the Destination-Realm / Destination-Host AVP.
387 *
388 * If the msg is a request, there are two ways of receiving the answer:
389 *  - either having registered a callback in the dispatch module (see disp_register)
390 *  - or provide a callback as parameter here. If such callback is provided, it is called before the dispatch callbacks.
391 *    The prototype for this callback function is:
392 *     void anscb(void * data, struct msg ** answer)
393 *      where:
394 *              data   : opaque data that was registered along with the callback.
395 *              answer : location of the pointer to the answer.
396 *      note1: on function return, if *answer is not NULL, the message is passed to the dispatch module for regular callbacks.
397 *             otherwise, the callback must take care of freeing the message (msg_free).
398 *      note2: the opaque data is not freed by the daemon in any case, extensions should ensure clean handling in waaad_ext_fini.
399 *
400 * If no callback is registered to handle an answer, the message is discarded and an error is logged.
401 *
402 * RETURN VALUE:
403 *  0           : The message has been queued for sending (sending may fail asynchronously).
404 *  EINVAL      : A parameter is invalid (ex: anscb provided but message is not a request).
405 *  ...
406 */
407int fd_msg_send ( struct msg ** pmsg, void (*anscb)(void *, struct msg **), void * data );
408
409/*
410 * FUNCTION:    fd_msg_rescode_set
411 *
412 * PARAMETERS:
413 *  msg         : A msg object -- it must be an answer.
414 *  rescode     : The name of the returned error code (ex: "DIAMETER_INVALID_AVP")
415 *  errormsg    : (optional) human-readable error message to put in Error-Message AVP
416 *  optavp      : (optional) If provided, the content will be put inside a Failed-AVP
417 *  type_id     : 0 => nothing; 1 => adds Origin-Host and Origin-Realm with local info. 2=> adds Error-Reporting-Host.
418 *
419 * DESCRIPTION:
420 *   This function adds a Result-Code AVP to a message, and optionally
421 *  - sets the 'E' error flag in the header,
422 *  - adds Error-Message, Error-Reporting-Host and Failed-AVP AVPs.
423 *
424 * RETURN VALUE:
425 *  0           : Operation complete.
426 *  !0          : an error occurred.
427 */
428int fd_msg_rescode_set( struct msg * msg, char * rescode, char * errormsg, struct avp * optavp, int type_id );
429
430/* Add Origin-Host, Origin-Realm, (if osi) Origin-State-Id AVPS at the end of the message */
431int fd_msg_add_origin ( struct msg * msg, int osi ); 
432
433
434
435/***************************************/
436/*   Dispatch module, daemon's part    */
437/***************************************/
438
439/*
440 * FUNCTION:    fd_disp_app_support
441 *
442 * PARAMETERS:
443 *  app         : The dictionary object corresponding to the Application.
444 *  vendor      : (Optional) the dictionary object of a Vendor to claim support in Vendor-Specific-Application-Id
445 *  auth        : Support auth app part.
446 *  acct        : Support acct app part.
447 *
448 * DESCRIPTION:
449 *   Registers an application to be advertized in CER/CEA exchanges.
450 *  Messages with an application-id matching a registered value are passed to the dispatch module,
451 * while other messages are simply relayed or an error is returned (if local node does not relay)
452 *
453 * RETURN VALUE:
454 *  0           : The application support is registered.
455 *  EINVAL      : A parameter is invalid.
456 */
457int fd_disp_app_support ( struct dict_object * app, struct dict_object * vendor, int auth, int acct );
458
459/* Note: if we want to support capabilities updates, we'll have to add possibility to remove an app as well... */
460
461
462#endif /* _FREEDIAMETER_H */
Note: See TracBrowser for help on using the repository browser.