Apply clang-format

This commit is contained in:
Riza Sulistyo 2022-08-02 08:58:40 +07:00
parent 6ff18b4f8a
commit 0f0162396c
1174 changed files with 198942 additions and 219145 deletions

99
.clang-format Normal file
View File

@ -0,0 +1,99 @@
Language: Cpp
AlignConsecutiveMacros: AcrossEmptyLinesAndComments
AlignEscapedNewlines: DontAlign
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
BasedOnStyle: Google
BreakBeforeBraces: Custom
BraceWrapping:
AfterControlStatement: MultiLine
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: true
BeforeCatch: false
BeforeElse: false
BeforeWhile: false
SplitEmptyFunction: false
BreakBeforeTernaryOperators: false
ContinuationIndentWidth: 2
Cpp11BracedListStyle: false
DerivePointerAlignment: false
IncludeBlocks: Preserve
IndentCaseLabels: false
IndentPPDirectives: AfterHash
IndentWidth: 4
MaxEmptyLinesToKeep: 1
PointerAlignment: Left
SortIncludes: Never
---
Language: ObjC
AlignConsecutiveMacros: AcrossEmptyLinesAndComments
AlignEscapedNewlines: DontAlign
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
ColumnLimit: 80
BreakBeforeBraces: Custom
BraceWrapping:
AfterControlStatement: MultiLine
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: true
BeforeCatch: false
BeforeElse: false
BeforeWhile: false
SplitEmptyFunction: false
BreakBeforeTernaryOperators: false
ContinuationIndentWidth: 2
Cpp11BracedListStyle: false
DerivePointerAlignment: false
IncludeBlocks: Preserve
IndentCaseLabels: false
IndentPPDirectives: AfterHash
IndentWidth: 4
MaxEmptyLinesToKeep: 1
PointerAlignment: Left
SortIncludes: Never
---
Language: Java
AlignConsecutiveMacros: AcrossEmptyLinesAndComments
AlignEscapedNewlines: DontAlign
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
ColumnLimit: 80
BreakBeforeBraces: Custom
BraceWrapping:
AfterControlStatement: MultiLine
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: true
BeforeCatch: false
BeforeElse: false
BeforeWhile: false
SplitEmptyFunction: false
BreakBeforeTernaryOperators: false
ContinuationIndentWidth: 2
Cpp11BracedListStyle: false
DerivePointerAlignment: false
IncludeBlocks: Preserve
IndentCaseLabels: false
IndentPPDirectives: AfterHash
IndentWidth: 4
MaxEmptyLinesToKeep: 1
PointerAlignment: Left
SortIncludes: Never
...

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_H__
#define __PJLIB_UTIL_H__
@ -75,5 +74,4 @@
#include <pjlib-util/cli_console.h>
#include <pjlib-util/cli_telnet.h>
#endif /* __PJLIB_UTIL_H__ */
#endif /* __PJLIB_UTIL_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_BASE64_H__
#define __PJLIB_UTIL_BASE64_H__
@ -40,14 +39,13 @@ PJ_BEGIN_DECL
* Helper macro to calculate the approximate length required for base256 to
* base64 conversion.
*/
#define PJ_BASE256_TO_BASE64_LEN(len) (len * 4 / 3 + 3)
#define PJ_BASE256_TO_BASE64_LEN(len) (len * 4 / 3 + 3)
/**
* Helper macro to calculate the approximage length required for base64 to
* base256 conversion.
*/
#define PJ_BASE64_TO_BASE256_LEN(len) (len * 3 / 4)
#define PJ_BASE64_TO_BASE256_LEN(len) (len * 3 / 4)
/**
* Encode a buffer into base64 encoding.
@ -56,15 +54,15 @@ PJ_BEGIN_DECL
* @param in_len Size of the input buffer.
* @param output Output buffer. Caller must allocate this buffer with
* the appropriate size.
* @param out_len On entry, it specifies the length of the output buffer.
* @param out_len On entry, it specifies the length of the output buffer.
* Upon return, this will be filled with the actual
* length of the output buffer.
*
* @return PJ_SUCCESS on success.
*/
PJ_DECL(pj_status_t) pj_base64_encode(const pj_uint8_t *input, int in_len,
char *output, int *out_len);
PJ_DECL(pj_status_t)
pj_base64_encode(const pj_uint8_t* input, int in_len, char* output,
int* out_len);
/**
* Decode base64 string.
@ -72,14 +70,12 @@ PJ_DECL(pj_status_t) pj_base64_encode(const pj_uint8_t *input, int in_len,
* @param input Input string.
* @param out Buffer to store the output. Caller must allocate
* this buffer with the appropriate size.
* @param out_len On entry, it specifies the length of the output buffer.
* @param out_len On entry, it specifies the length of the output buffer.
* Upon return, this will be filled with the actual
* length of the output.
*/
PJ_DECL(pj_status_t) pj_base64_decode(const pj_str_t *input,
pj_uint8_t *out, int *out_len);
PJ_DECL(pj_status_t)
pj_base64_decode(const pj_str_t* input, pj_uint8_t* out, int* out_len);
/**
* @}
@ -87,6 +83,4 @@ PJ_DECL(pj_status_t) pj_base64_decode(const pj_str_t *input,
PJ_END_DECL
#endif /* __PJLIB_UTIL_BASE64_H__ */
#endif /* __PJLIB_UTIL_BASE64_H__ */

View File

@ -1,4 +1,3 @@
/* $Id$ */
/*
* Copyright (C) 2010 Teluu Inc. (http://www.teluu.com)
*
@ -27,18 +26,17 @@
#include <pjlib-util/types.h>
#include <pj/list.h>
PJ_BEGIN_DECL
/**
* @defgroup PJLIB_UTIL_CLI Command Line Interface Framework
* @{
* A CLI framework features an interface for defining command specification,
* parsing, and executing a command.
* It also features an interface to communicate with various front-ends,
* A CLI framework features an interface for defining command specification,
* parsing, and executing a command.
* It also features an interface to communicate with various front-ends,
* such as console, telnet.
* Application normally needs only one CLI instance to be created.
* On special cases, application could also create multiple CLI
* Application normally needs only one CLI instance to be created.
* On special cases, application could also create multiple CLI
* instances, with each instance has specific command structure.
*
\verbatim
@ -60,12 +58,12 @@ PJ_BEGIN_DECL
</CMD>
</CMD>
<CMD name='disable_codec' id=0 desc="">
<ARG name='codec_list' type='choice' id='3'>
<CHOICE value='g711'/>
<CHOICE value='g722'/>
</ARG>
<ARG name='codec_list' type='choice' id='3'>
<CHOICE value='g711'/>
<CHOICE value='g722'/>
</ARG>
</CMD>
\endverbatim
\endverbatim
*/
/**
@ -104,7 +102,7 @@ typedef struct pj_cli_cfg
* The pool factory where all memory allocations will be taken from.
* This field is mandatory.
*/
pj_pool_factory *pf;
pj_pool_factory* pf;
} pj_cli_cfg;
@ -139,10 +137,10 @@ typedef struct pj_cli_arg_spec pj_cli_arg_spec;
typedef struct pj_cli_cmd_val
{
/** The session on which the command was executed on. */
pj_cli_sess *sess;
pj_cli_sess* sess;
/** The command specification being executed. */
const pj_cli_cmd_spec *cmd;
const pj_cli_cmd_spec* cmd;
/** Number of argvs. */
int argc;
@ -153,7 +151,7 @@ typedef struct pj_cli_cmd_val
} pj_cli_cmd_val;
/**
* This structure contains the hints information for the end user.
* This structure contains the hints information for the end user.
* This structure could contain either command or argument information.
* The front-end will format the information and present it to the user.
*/
@ -170,7 +168,7 @@ typedef struct pj_cli_hint_info
pj_str_t type;
/**
* Helpful description of the hint value.
* Helpful description of the hint value.
*/
pj_str_t desc;
@ -209,10 +207,10 @@ typedef struct pj_cli_exec_info
unsigned hint_cnt;
/**
* If pj_cli_sess_parse() fails because of a missing argument or ambigous
* command/argument, the function returned PJ_CLI_EMISSINGARG or
* PJ_CLI_EAMBIGUOUS error.
* This field will contain the hint information. This is useful to give
* If pj_cli_sess_parse() fails because of a missing argument or ambigous
* command/argument, the function returned PJ_CLI_EMISSINGARG or
* PJ_CLI_EAMBIGUOUS error.
* This field will contain the hint information. This is useful to give
* helpful information to the end_user.
*/
pj_cli_hint_info hint[PJ_CLI_MAX_HINTS];
@ -220,7 +218,7 @@ typedef struct pj_cli_exec_info
} pj_cli_exec_info;
/**
* This structure contains the information returned from the dynamic
* This structure contains the information returned from the dynamic
* argument callback.
*/
typedef struct pj_cli_arg_choice_val
@ -246,12 +244,12 @@ typedef struct pj_cli_dyn_choice_param
/**
* The session on which the command was executed on.
*/
pj_cli_sess *sess;
pj_cli_sess* sess;
/**
* The command being processed.
*/
pj_cli_cmd_spec *cmd;
pj_cli_cmd_spec* cmd;
/**
* The argument id.
@ -266,7 +264,7 @@ typedef struct pj_cli_dyn_choice_param
/**
* The pool to allocate memory from.
*/
pj_pool_t *pool;
pj_pool_t* pool;
/**
* The choice values count.
@ -283,7 +281,7 @@ typedef struct pj_cli_dyn_choice_param
* This specifies the callback type for argument handlers, which will be
* called to get the valid values of the choice type arguments.
*/
typedef void (*pj_cli_get_dyn_choice) (pj_cli_dyn_choice_param *param);
typedef void (*pj_cli_get_dyn_choice)(pj_cli_dyn_choice_param* param);
/**
* This specifies the callback type for command handlers, which will be
@ -293,7 +291,7 @@ typedef void (*pj_cli_get_dyn_choice) (pj_cli_dyn_choice_param *param);
*
* @return Return the status of the command execution.
*/
typedef pj_status_t (*pj_cli_cmd_handler)(pj_cli_cmd_val *cval);
typedef pj_status_t (*pj_cli_cmd_handler)(pj_cli_cmd_val* cval);
/**
* Write a log message to the CLI application. The CLI application
@ -304,10 +302,8 @@ typedef pj_status_t (*pj_cli_cmd_handler)(pj_cli_cmd_val *cval);
* @param buffer The message itself.
* @param len Length of this message.
*/
PJ_DECL(void) pj_cli_write_log(pj_cli_t *cli,
int level,
const char *buffer,
int len);
PJ_DECL(void)
pj_cli_write_log(pj_cli_t* cli, int level, const char* buffer, int len);
/**
* Create a new CLI application instance.
@ -317,17 +313,16 @@ PJ_DECL(void) pj_cli_write_log(pj_cli_t *cli,
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_cli_create(pj_cli_cfg *cfg,
pj_cli_t **p_cli);
PJ_DECL(pj_status_t) pj_cli_create(pj_cli_cfg* cfg, pj_cli_t** p_cli);
/**
* This specifies the function to get the id of the specified command
*
*
* @param cmd The specified command.
*
* @return The command id
*/
PJ_DECL(pj_cli_cmd_id) pj_cli_get_cmd_id(const pj_cli_cmd_spec *cmd);
PJ_DECL(pj_cli_cmd_id) pj_cli_get_cmd_id(const pj_cli_cmd_spec* cmd);
/**
* Get the internal parameter of the CLI instance.
@ -336,7 +331,7 @@ PJ_DECL(pj_cli_cmd_id) pj_cli_get_cmd_id(const pj_cli_cmd_spec *cmd);
*
* @return CLI parameter instance.
*/
PJ_DECL(pj_cli_cfg*) pj_cli_get_param(pj_cli_t *cli);
PJ_DECL(pj_cli_cfg*) pj_cli_get_param(pj_cli_t* cli);
/**
* Call this to signal application shutdown. Typically application would
@ -351,8 +346,7 @@ PJ_DECL(pj_cli_cfg*) pj_cli_get_param(pj_cli_t *cli);
* received.
* @param restart Indicate whether application restart is wanted.
*/
PJ_DECL(void) pj_cli_quit(pj_cli_t *cli, pj_cli_sess *req,
pj_bool_t restart);
PJ_DECL(void) pj_cli_quit(pj_cli_t* cli, pj_cli_sess* req, pj_bool_t restart);
/**
* Check if application shutdown or restart has been requested.
*
@ -360,7 +354,7 @@ PJ_DECL(void) pj_cli_quit(pj_cli_t *cli, pj_cli_sess *req,
*
* @return PJ_TRUE if pj_cli_quit() has been called.
*/
PJ_DECL(pj_bool_t) pj_cli_is_quitting(pj_cli_t *cli);
PJ_DECL(pj_bool_t) pj_cli_is_quitting(pj_cli_t* cli);
/**
* Check if application restart has been requested.
@ -370,7 +364,7 @@ PJ_DECL(pj_bool_t) pj_cli_is_quitting(pj_cli_t *cli);
* @return PJ_TRUE if pj_cli_quit() has been called with
* restart parameter set.
*/
PJ_DECL(pj_bool_t) pj_cli_is_restarting(pj_cli_t *cli);
PJ_DECL(pj_bool_t) pj_cli_is_restarting(pj_cli_t* cli);
/**
* Destroy a CLI application instance. This would also close all sessions
@ -378,14 +372,14 @@ PJ_DECL(pj_bool_t) pj_cli_is_restarting(pj_cli_t *cli);
*
* @param cli The CLI application.
*/
PJ_DECL(void) pj_cli_destroy(pj_cli_t *cli);
PJ_DECL(void) pj_cli_destroy(pj_cli_t* cli);
/**
* Initialize a pj_cli_cfg with its default values.
*
* @param param The instance to be initialized.
*/
PJ_DECL(void) pj_cli_cfg_default(pj_cli_cfg *param);
PJ_DECL(void) pj_cli_cfg_default(pj_cli_cfg* param);
/**
* Register a front end to the CLI application.
@ -393,8 +387,7 @@ PJ_DECL(void) pj_cli_cfg_default(pj_cli_cfg *param);
* @param cli The CLI application.
* @param fe The CLI front end to be registered.
*/
PJ_DECL(void) pj_cli_register_front_end(pj_cli_t *cli,
pj_cli_front_end *fe);
PJ_DECL(void) pj_cli_register_front_end(pj_cli_t* cli, pj_cli_front_end* fe);
/**
* Create a new complete command specification from an XML node text and
@ -412,34 +405,32 @@ PJ_DECL(void) pj_cli_register_front_end(pj_cli_t *cli,
* if the command specifies a command group.
* @param p_cmd Optional pointer to store the newly created
* specification.
* @param get_choice Function handler for the argument. Specify this for
* @param get_choice Function handler for the argument. Specify this for
* dynamic choice type arguments.
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_cli_add_cmd_from_xml(pj_cli_t *cli,
pj_cli_cmd_spec *group,
const pj_str_t *xml,
pj_cli_cmd_handler handler,
pj_cli_cmd_spec **p_cmd,
pj_cli_get_dyn_choice get_choice);
PJ_DECL(pj_status_t)
pj_cli_add_cmd_from_xml(pj_cli_t* cli, pj_cli_cmd_spec* group,
const pj_str_t* xml, pj_cli_cmd_handler handler,
pj_cli_cmd_spec** p_cmd,
pj_cli_get_dyn_choice get_choice);
/**
* Initialize pj_cli_exec_info with its default values.
*
* @param param The param to be initialized.
*/
PJ_DECL(void) pj_cli_exec_info_default(pj_cli_exec_info *param);
PJ_DECL(void) pj_cli_exec_info_default(pj_cli_exec_info* param);
/**
* Write a log message to the specific CLI session.
* Write a log message to the specific CLI session.
*
* @param sess The CLI active session.
* @param buffer The message itself.
* @param len Length of this message.
*/
PJ_DECL(void) pj_cli_sess_write_msg(pj_cli_sess *sess,
const char *buffer,
pj_size_t len);
PJ_DECL(void)
pj_cli_sess_write_msg(pj_cli_sess* sess, const char* buffer, pj_size_t len);
/**
* Parse an input cmdline string. The first word of the command line is the
@ -477,23 +468,21 @@ PJ_DECL(void) pj_cli_sess_write_msg(pj_cli_sess *sess,
* the current session. This is a signal for the
* application to end it's main loop.
*/
PJ_DECL(pj_status_t) pj_cli_sess_parse(pj_cli_sess *sess,
char *cmdline,
pj_cli_cmd_val *val,
pj_pool_t *pool,
pj_cli_exec_info *info);
PJ_DECL(pj_status_t)
pj_cli_sess_parse(pj_cli_sess* sess, char* cmdline, pj_cli_cmd_val* val,
pj_pool_t* pool, pj_cli_exec_info* info);
/**
* End the specified session, and destroy it to release all resources used
* by the session.
*
* See also pj_cli_sess and pj_cli_front_end for more info regarding the
* See also pj_cli_sess and pj_cli_front_end for more info regarding the
* creation process.
* See also pj_cli_quit() to quit the whole application instead.
*
* @param sess The CLI session to be destroyed.
*/
PJ_DECL(void) pj_cli_sess_end_session(pj_cli_sess *sess);
PJ_DECL(void) pj_cli_sess_end_session(pj_cli_sess* sess);
/**
* Execute a command line. This function will parse the input string to find
@ -505,7 +494,7 @@ PJ_DECL(void) pj_cli_sess_end_session(pj_cli_sess *sess);
* See also pj_cli_sess_parse() for more info regarding the cmdline format.
*
* @param sess The CLI session.
* @param cmdline The command line string to be executed.
* @param cmdline The command line string to be executed.
* @param pool The pool to allocate memory from.
* @param info Optional pointer to receive additional information
* related to the execution of the command (such as
@ -517,10 +506,9 @@ PJ_DECL(void) pj_cli_sess_end_session(pj_cli_sess *sess);
* argument, if specified). Please see the return value
* of pj_cli_sess_parse() for possible return values.
*/
PJ_DECL(pj_status_t) pj_cli_sess_exec(pj_cli_sess *sess,
char *cmdline,
pj_pool_t *pool,
pj_cli_exec_info *info);
PJ_DECL(pj_status_t)
pj_cli_sess_exec(pj_cli_sess* sess, char* cmdline, pj_pool_t* pool,
pj_cli_exec_info* info);
/**
* @}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2010 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
@ -14,7 +13,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_CLI_CONSOLE_H__
#define __PJLIB_UTIL_CLI_CONSOLE_H__
@ -26,7 +25,6 @@
#include <pjlib-util/cli_imp.h>
PJ_BEGIN_DECL
/**
@ -35,7 +33,6 @@ PJ_BEGIN_DECL
*
*/
/**
* This structure contains various options for CLI console front-end.
* Application must call pj_cli_console_cfg_default() to initialize
@ -66,14 +63,12 @@ typedef struct pj_cli_console_cfg
} pj_cli_console_cfg;
/**
* Initialize pj_cli_console_cfg with its default values.
*
* @param param The structure to be initialized.
*/
PJ_DECL(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param);
PJ_DECL(void) pj_cli_console_cfg_default(pj_cli_console_cfg* param);
/**
* Create a console front-end for the specified CLI application, and return
@ -90,10 +85,9 @@ PJ_DECL(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param);
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_cli_console_create(pj_cli_t *cli,
const pj_cli_console_cfg *param,
pj_cli_sess **p_sess,
pj_cli_front_end **p_fe);
PJ_DECL(pj_status_t)
pj_cli_console_create(pj_cli_t* cli, const pj_cli_console_cfg* param,
pj_cli_sess** p_sess, pj_cli_front_end** p_fe);
/**
* Retrieve a cmdline from console stdin and process the input accordingly.
@ -104,9 +98,8 @@ PJ_DECL(pj_status_t) pj_cli_console_create(pj_cli_t *cli,
*
* @return PJ_SUCCESS if an input was read
*/
PJ_DECL(pj_status_t) pj_cli_console_process(pj_cli_sess *sess,
char *buf,
unsigned maxlen);
PJ_DECL(pj_status_t)
pj_cli_console_process(pj_cli_sess* sess, char* buf, unsigned maxlen);
/**
* @}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2010 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
@ -14,7 +13,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_CLI_IMP_H__
#define __PJLIB_UTIL_CLI_IMP_H__
@ -26,7 +25,6 @@
#include <pjlib-util/cli.h>
PJ_BEGIN_DECL
/**
@ -40,21 +38,21 @@ PJ_BEGIN_DECL
* Default log level for console sessions.
*/
#ifndef PJ_CLI_CONSOLE_LOG_LEVEL
# define PJ_CLI_CONSOLE_LOG_LEVEL PJ_LOG_MAX_LEVEL
# define PJ_CLI_CONSOLE_LOG_LEVEL PJ_LOG_MAX_LEVEL
#endif
/**
* Default log level for telnet sessions.
*/
#ifndef PJ_CLI_TELNET_LOG_LEVEL
# define PJ_CLI_TELNET_LOG_LEVEL 4
# define PJ_CLI_TELNET_LOG_LEVEL 4
#endif
/**
* Default port number for telnet daemon.
*/
#ifndef PJ_CLI_TELNET_PORT
# define PJ_CLI_TELNET_PORT 0
# define PJ_CLI_TELNET_PORT 0
#endif
/**
@ -62,13 +60,12 @@ PJ_BEGIN_DECL
*/
typedef enum pj_cli_front_end_type
{
PJ_CLI_CONSOLE_FRONT_END, /**< Console front end. */
PJ_CLI_TELNET_FRONT_END, /**< Telnet front end. */
PJ_CLI_HTTP_FRONT_END, /**< HTTP front end. */
PJ_CLI_GUI_FRONT_END /**< GUI front end. */
PJ_CLI_CONSOLE_FRONT_END, /**< Console front end. */
PJ_CLI_TELNET_FRONT_END, /**< Telnet front end. */
PJ_CLI_HTTP_FRONT_END, /**< HTTP front end. */
PJ_CLI_GUI_FRONT_END /**< GUI front end. */
} pj_cli_front_end_type;
/**
* Front end operations. Only the CLI should call these functions
* directly.
@ -86,8 +83,8 @@ typedef struct pj_cli_front_end_op
* @param data The message itself.
* @param len Length of this message.
*/
void (*on_write_log)(pj_cli_front_end *fe, int level,
const char *data, pj_size_t len);
void (*on_write_log)(pj_cli_front_end* fe, int level, const char* data,
pj_size_t len);
/**
* Callback to be called when the application is quitting, to signal the
@ -97,7 +94,7 @@ typedef struct pj_cli_front_end_op
* @param fe The front end.
* @param req The session which requested the application quit.
*/
void (*on_quit)(pj_cli_front_end *fe, pj_cli_sess *req);
void (*on_quit)(pj_cli_front_end* fe, pj_cli_sess* req);
/**
* Callback to be called to close and self destroy the front-end. This
@ -105,11 +102,10 @@ typedef struct pj_cli_front_end_op
*
* @param fe The front end.
*/
void (*on_destroy)(pj_cli_front_end *fe);
void (*on_destroy)(pj_cli_front_end* fe);
} pj_cli_front_end_op;
/**
* This structure describes common properties of CLI front-ends. A front-
* end is a mean to interact with end user, for example the CLI application
@ -135,15 +131,14 @@ struct pj_cli_front_end
/**
* The CLI application.
*/
pj_cli_t *cli;
pj_cli_t* cli;
/**
* Front end operations.
*/
pj_cli_front_end_op *op;
pj_cli_front_end_op* op;
};
/**
* Session operations.
*/
@ -154,11 +149,10 @@ typedef struct pj_cli_sess_op
*
* @param sess The session to destroy.
*/
void (*destroy)(pj_cli_sess *sess);
void (*destroy)(pj_cli_sess* sess);
} pj_cli_sess_op;
/**
* This structure describes common properties of a CLI session. A CLI session
* is the interaction of an end user to the CLI application via a specific
@ -178,12 +172,12 @@ struct pj_cli_sess
/**
* Pointer to the front-end instance which created this session.
*/
pj_cli_front_end *fe;
pj_cli_front_end* fe;
/**
* Session operations.
*/
pj_cli_sess_op *op;
pj_cli_sess_op* op;
/**
* Text containing session info, which is filled by the renderer when
@ -195,14 +189,12 @@ struct pj_cli_sess
* Log verbosity of this session.
*/
int log_level;
};
/**
* @}
*/
PJ_END_DECL
#endif /* __PJLIB_UTIL_CLI_IMP_H__ */
#endif /* __PJLIB_UTIL_CLI_IMP_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2010 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
@ -14,7 +13,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_CLI_TELNET_H__
#define __PJLIB_UTIL_CLI_TELNET_H__
@ -34,7 +33,7 @@ PJ_BEGIN_DECL
*
*/
/**
/**
* This structure contains the information about the telnet.
* Application will get updated information each time the telnet is started/
* restarted.
@ -44,7 +43,7 @@ typedef struct pj_cli_telnet_info
/**
* The telnet's ip address.
*/
pj_str_t ip_address;
pj_str_t ip_address;
/**
* The telnet's port number.
@ -83,7 +82,7 @@ typedef struct pj_cli_telnet_cfg
* Ioqueue instance to be used. If this field is NULL, an internal
* ioqueue and worker thread will be created.
*/
pj_ioqueue_t *ioqueue;
pj_ioqueue_t* ioqueue;
/**
* Default log verbosity level for the session.
@ -129,8 +128,7 @@ typedef struct pj_cli_telnet_cfg
*
* @param param The structure to be initialized.
*/
PJ_DECL(void) pj_cli_telnet_cfg_default(pj_cli_telnet_cfg *param);
PJ_DECL(void) pj_cli_telnet_cfg_default(pj_cli_telnet_cfg* param);
/**
* Create, initialize, and start a telnet daemon for the application.
@ -143,10 +141,9 @@ PJ_DECL(void) pj_cli_telnet_cfg_default(pj_cli_telnet_cfg *param);
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli,
pj_cli_telnet_cfg *param,
pj_cli_front_end **p_fe);
PJ_DECL(pj_status_t)
pj_cli_telnet_create(pj_cli_t* cli, pj_cli_telnet_cfg* param,
pj_cli_front_end** p_fe);
/**
* Retrieve cli telnet info.
@ -155,8 +152,8 @@ PJ_DECL(pj_status_t) pj_cli_telnet_create(pj_cli_t *cli,
*
* @return PJ_SUCCESS on success.
*/
PJ_DECL(pj_status_t) pj_cli_telnet_get_info(pj_cli_front_end *fe,
pj_cli_telnet_info *info);
PJ_DECL(pj_status_t)
pj_cli_telnet_get_info(pj_cli_front_end* fe, pj_cli_telnet_info* info);
/**
* @}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,12 +14,11 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_CONFIG_H__
#define __PJLIB_UTIL_CONFIG_H__
/**
* @file config.h
* @brief Compile time settings
@ -32,7 +30,6 @@
* @{
*/
/* **************************************************************************
* DNS CONFIGURATION
*/
@ -41,59 +38,53 @@
* Maximum number of IP addresses in DNS A response.
*/
#ifndef PJ_DNS_MAX_IP_IN_A_REC
# define PJ_DNS_MAX_IP_IN_A_REC 8
# define PJ_DNS_MAX_IP_IN_A_REC 8
#endif
/**
* Maximum server address entries per one SRV record
*/
#ifndef PJ_DNS_SRV_MAX_ADDR
# define PJ_DNS_SRV_MAX_ADDR 8
# define PJ_DNS_SRV_MAX_ADDR 8
#endif
/**
* This constant specifies the maximum names to keep in the temporary name
* table when performing name compression scheme when duplicating DNS packet
* (the #pj_dns_packet_dup() function).
*
* Generally name compression is desired, since it saves some memory (see
* PJ_DNS_RESOLVER_RES_BUF_SIZE setting). However it comes at the expense of
* PJ_DNS_RESOLVER_RES_BUF_SIZE setting). However it comes at the expense of
* a little processing overhead to perform name scanning and also a little
* bit more stack usage (8 bytes per entry on 32bit platform).
*
* Default: 16
*/
#ifndef PJ_DNS_MAX_NAMES_IN_NAMETABLE
# define PJ_DNS_MAX_NAMES_IN_NAMETABLE 16
# define PJ_DNS_MAX_NAMES_IN_NAMETABLE 16
#endif
/* **************************************************************************
* RESOLVER CONFIGURATION
*/
/**
* Maximum numbers of DNS nameservers that can be configured in resolver.
*/
#ifndef PJ_DNS_RESOLVER_MAX_NS
# define PJ_DNS_RESOLVER_MAX_NS 16
# define PJ_DNS_RESOLVER_MAX_NS 16
#endif
/**
* Default retransmission delay, in miliseconds. The combination of
* Default retransmission delay, in miliseconds. The combination of
* retransmission delay and count determines the query timeout.
*
* Default: 2000 (2 seconds, according to RFC 1035)
*/
#ifndef PJ_DNS_RESOLVER_QUERY_RETRANSMIT_DELAY
# define PJ_DNS_RESOLVER_QUERY_RETRANSMIT_DELAY 2000
# define PJ_DNS_RESOLVER_QUERY_RETRANSMIT_DELAY 2000
#endif
/**
* Maximum number of transmissions before timeout is declared for
* the query.
@ -101,13 +92,12 @@
* Default: 5
*/
#ifndef PJ_DNS_RESOLVER_QUERY_RETRANSMIT_COUNT
# define PJ_DNS_RESOLVER_QUERY_RETRANSMIT_COUNT 5
# define PJ_DNS_RESOLVER_QUERY_RETRANSMIT_COUNT 5
#endif
/**
* Maximum life-time of DNS response in the resolver response cache,
* in seconds. If the value is zero, then DNS response caching will be
* Maximum life-time of DNS response in the resolver response cache,
* in seconds. If the value is zero, then DNS response caching will be
* disabled.
*
* Default is 300 seconds (5 minutes).
@ -115,13 +105,13 @@
* @see PJ_DNS_RESOLVER_INVALID_TTL
*/
#ifndef PJ_DNS_RESOLVER_MAX_TTL
# define PJ_DNS_RESOLVER_MAX_TTL (5*60)
# define PJ_DNS_RESOLVER_MAX_TTL (5 * 60)
#endif
/**
* The life-time of invalid DNS response in the resolver response cache.
* An invalid DNS response is a response which RCODE is non-zero and
* response without any answer section. These responses can be put in
* An invalid DNS response is a response which RCODE is non-zero and
* response without any answer section. These responses can be put in
* the cache too to minimize message round-trip.
*
* Default: 60 (one minute).
@ -129,11 +119,11 @@
* @see PJ_DNS_RESOLVER_MAX_TTL
*/
#ifndef PJ_DNS_RESOLVER_INVALID_TTL
# define PJ_DNS_RESOLVER_INVALID_TTL 60
# define PJ_DNS_RESOLVER_INVALID_TTL 60
#endif
/**
* The interval on which nameservers which are known to be good to be
* The interval on which nameservers which are known to be good to be
* probed again to determine whether they are still good. Note that
* this applies to both active nameserver (the one currently being used)
* and idle nameservers (good nameservers that are not currently selected).
@ -146,7 +136,7 @@
* @see PJ_DNS_RESOLVER_BAD_NS_TTL
*/
#ifndef PJ_DNS_RESOLVER_GOOD_NS_TTL
# define PJ_DNS_RESOLVER_GOOD_NS_TTL (10*60)
# define PJ_DNS_RESOLVER_GOOD_NS_TTL (10 * 60)
#endif
/**
@ -158,10 +148,9 @@
* @see PJ_DNS_RESOLVER_GOOD_NS_TTL
*/
#ifndef PJ_DNS_RESOLVER_BAD_NS_TTL
# define PJ_DNS_RESOLVER_BAD_NS_TTL (1*60)
# define PJ_DNS_RESOLVER_BAD_NS_TTL (1 * 60)
#endif
/**
* Maximum size of UDP packet. RFC 1035 states that maximum size of
* DNS packet carried over UDP is 512 bytes.
@ -169,10 +158,9 @@
* Default: 512 byes
*/
#ifndef PJ_DNS_RESOLVER_MAX_UDP_SIZE
# define PJ_DNS_RESOLVER_MAX_UDP_SIZE 512
# define PJ_DNS_RESOLVER_MAX_UDP_SIZE 512
#endif
/**
* Size of memory pool allocated for each individual DNS response cache.
* This value here should be more or less the same as maximum UDP packet
@ -182,36 +170,31 @@
* Default: 512
*/
#ifndef PJ_DNS_RESOLVER_RES_BUF_SIZE
# define PJ_DNS_RESOLVER_RES_BUF_SIZE 512
# define PJ_DNS_RESOLVER_RES_BUF_SIZE 512
#endif
/**
* Size of temporary pool buffer for parsing DNS packets in resolver.
*
* default: 4000
*/
#ifndef PJ_DNS_RESOLVER_TMP_BUF_SIZE
# define PJ_DNS_RESOLVER_TMP_BUF_SIZE 4000
# define PJ_DNS_RESOLVER_TMP_BUF_SIZE 4000
#endif
/* **************************************************************************
* SCANNER CONFIGURATION
*/
/**
* Macro PJ_SCANNER_USE_BITWISE is defined and non-zero (by default yes)
* will enable the use of bitwise for character input specification (cis).
* This would save several kilobytes of .bss memory in the SIP parser.
*/
#ifndef PJ_SCANNER_USE_BITWISE
# define PJ_SCANNER_USE_BITWISE 1
# define PJ_SCANNER_USE_BITWISE 1
#endif
/* **************************************************************************
* STUN CLIENT CONFIGURATION
*/
@ -223,10 +206,9 @@
* Default: 16
*/
#ifndef PJSTUN_MAX_ATTR
# define PJSTUN_MAX_ATTR 16
# define PJSTUN_MAX_ATTR 16
#endif
/**
* Maximum number of attributes in the STUN packet (for the new STUN
* library).
@ -234,10 +216,9 @@
* Default: 16
*/
#ifndef PJ_STUN_MAX_ATTR
# define PJ_STUN_MAX_ATTR 16
# define PJ_STUN_MAX_ATTR 16
#endif
/* **************************************************************************
* UPnP
*/
@ -245,11 +226,10 @@
/* Default duration for searching UPnP Internet Gateway Devices (in seconds).
* Default: 5 seconds
*/
#ifndef PJ_UPNP_DEFAULT_SEARCH_TIME
# define PJ_UPNP_DEFAULT_SEARCH_TIME 5
#ifndef PJ_UPNP_DEFAULT_SEARCH_TIME
# define PJ_UPNP_DEFAULT_SEARCH_TIME 5
#endif
/* **************************************************************************
* ENCRYPTION
*/
@ -263,10 +243,9 @@
* Default: 1
*/
#ifndef PJ_CRC32_HAS_TABLES
# define PJ_CRC32_HAS_TABLES 1
# define PJ_CRC32_HAS_TABLES 1
#endif
/* **************************************************************************
* HTTP Client configuration
*/
@ -275,7 +254,7 @@
* Default: 60000ms
*/
#ifndef PJ_HTTP_DEFAULT_TIMEOUT
# define PJ_HTTP_DEFAULT_TIMEOUT (60000)
# define PJ_HTTP_DEFAULT_TIMEOUT (60000)
#endif
/* **************************************************************************
@ -287,7 +266,7 @@
* Default: 1024 bytes
*/
#ifndef PJ_CLI_POOL_SIZE
# define PJ_CLI_POOL_SIZE 1024
# define PJ_CLI_POOL_SIZE 1024
#endif
/**
@ -295,7 +274,7 @@
* Default: 512 bytes
*/
#ifndef PJ_CLI_POOL_INC
# define PJ_CLI_POOL_INC 512
# define PJ_CLI_POOL_INC 512
#endif
/**
@ -303,7 +282,7 @@
* Default: 512
*/
#ifndef PJ_CLI_MAX_CMDBUF
# define PJ_CLI_MAX_CMDBUF 512
# define PJ_CLI_MAX_CMDBUF 512
#endif
/**
@ -311,7 +290,7 @@
* Default: 8
*/
#ifndef PJ_CLI_MAX_ARGS
# define PJ_CLI_MAX_ARGS 8
# define PJ_CLI_MAX_ARGS 8
#endif
/**
@ -319,7 +298,7 @@
* Default: 32
*/
#ifndef PJ_CLI_MAX_HINTS
# define PJ_CLI_MAX_HINTS 32
# define PJ_CLI_MAX_HINTS 32
#endif
/**
@ -327,7 +306,7 @@
* Default: 4
*/
#ifndef PJ_CLI_MAX_SHORTCUTS
# define PJ_CLI_MAX_SHORTCUTS 4
# define PJ_CLI_MAX_SHORTCUTS 4
#endif
/**
@ -335,7 +314,7 @@
* Default: 256 bytes
*/
#ifndef PJ_CLI_CONSOLE_POOL_SIZE
# define PJ_CLI_CONSOLE_POOL_SIZE 256
# define PJ_CLI_CONSOLE_POOL_SIZE 256
#endif
/**
@ -343,7 +322,7 @@
* Default: 256 bytes
*/
#ifndef PJ_CLI_CONSOLE_POOL_INC
# define PJ_CLI_CONSOLE_POOL_INC 256
# define PJ_CLI_CONSOLE_POOL_INC 256
#endif
/**
@ -351,7 +330,7 @@
* Default: 1024 bytes
*/
#ifndef PJ_CLI_TELNET_POOL_SIZE
# define PJ_CLI_TELNET_POOL_SIZE 1024
# define PJ_CLI_TELNET_POOL_SIZE 1024
#endif
/**
@ -359,7 +338,7 @@
* Default: 512 bytes
*/
#ifndef PJ_CLI_TELNET_POOL_INC
# define PJ_CLI_TELNET_POOL_INC 512
# define PJ_CLI_TELNET_POOL_INC 512
#endif
/**
@ -367,7 +346,7 @@
* Default: 64
*/
#ifndef PJ_CLI_MAX_CHOICE_VAL
# define PJ_CLI_MAX_CHOICE_VAL 64
# define PJ_CLI_MAX_CHOICE_VAL 64
#endif
/**
@ -375,12 +354,11 @@
* Default: 16
*/
#ifndef PJ_CLI_MAX_CMD_HISTORY
# define PJ_CLI_MAX_CMD_HISTORY 16
# define PJ_CLI_MAX_CMD_HISTORY 16
#endif
/**
* @}
*/
#endif /* __PJLIB_UTIL_CONFIG_H__ */
#endif /* __PJLIB_UTIL_CONFIG_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_CRC32_H__
#define __PJLIB_UTIL_CRC32_H__
@ -33,23 +32,22 @@ PJ_BEGIN_DECL
* @defgroup PJLIB_UTIL_CRC32 CRC32 (Cyclic Redundancy Check)
* @ingroup PJLIB_UTIL_ENCRYPTION
* @{
* This implements CRC32 algorithm. See ITU-T V.42 for the formal
* This implements CRC32 algorithm. See ITU-T V.42 for the formal
* specification.
*/
/** CRC32 context. */
typedef struct pj_crc32_context
{
pj_uint32_t crc_state; /**< Current state. */
pj_uint32_t crc_state; /**< Current state. */
} pj_crc32_context;
/**
* Initialize CRC32 context.
*
* @param ctx CRC32 context.
*/
PJ_DECL(void) pj_crc32_init(pj_crc32_context *ctx);
PJ_DECL(void) pj_crc32_init(pj_crc32_context* ctx);
/**
* Feed data incrementally to the CRC32 algorithm.
@ -60,9 +58,9 @@ PJ_DECL(void) pj_crc32_init(pj_crc32_context *ctx);
*
* @return The current CRC32 value.
*/
PJ_DECL(pj_uint32_t) pj_crc32_update(pj_crc32_context *ctx,
const pj_uint8_t *data,
pj_size_t nbytes);
PJ_DECL(pj_uint32_t)
pj_crc32_update(pj_crc32_context* ctx, const pj_uint8_t* data,
pj_size_t nbytes);
/**
* Finalize CRC32 calculation and retrieve the CRC32 value.
@ -71,7 +69,7 @@ PJ_DECL(pj_uint32_t) pj_crc32_update(pj_crc32_context *ctx,
*
* @return The current CRC value.
*/
PJ_DECL(pj_uint32_t) pj_crc32_final(pj_crc32_context *ctx);
PJ_DECL(pj_uint32_t) pj_crc32_final(pj_crc32_context* ctx);
/**
* Perform one-off CRC32 calculation to the specified data.
@ -81,9 +79,7 @@ PJ_DECL(pj_uint32_t) pj_crc32_final(pj_crc32_context *ctx);
*
* @return CRC value of the data.
*/
PJ_DECL(pj_uint32_t) pj_crc32_calc(const pj_uint8_t *data,
pj_size_t nbytes);
PJ_DECL(pj_uint32_t) pj_crc32_calc(const pj_uint8_t* data, pj_size_t nbytes);
/**
* @}
@ -91,6 +87,4 @@ PJ_DECL(pj_uint32_t) pj_crc32_calc(const pj_uint8_t *data,
PJ_END_DECL
#endif /* __PJLIB_UTIL_CRC32_H__ */
#endif /* __PJLIB_UTIL_CRC32_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,12 +14,11 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_DNS_H__
#define __PJLIB_UTIL_DNS_H__
/**
* @file dns.h
* @brief Low level DNS message parsing and packetization.
@ -42,14 +40,14 @@ PJ_BEGIN_DECL
*
* This module provides low-level services to parse and packetize DNS queries
* and responses. The functions support building a DNS query packet and parse
* the data in the DNS response. This implementation conforms to the
* the data in the DNS response. This implementation conforms to the
* following specifications:
* - RFC 1035: DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION
* - RFC 1886: DNS Extensions to support IP version 6
*
* To create a DNS query packet, application should call #pj_dns_make_query()
* function, specifying the desired DNS query type, the name to be resolved,
* and the buffer where the DNS packet will be built into.
* and the buffer where the DNS packet will be built into.
*
* When incoming DNS query or response packet arrives, application can use
* #pj_dns_parse_packet() to parse the TCP/UDP payload into parsed DNS packet
@ -62,7 +60,7 @@ PJ_BEGIN_DECL
enum
{
PJ_DNS_CLASS_IN = 1 /**< DNS class IN. */
PJ_DNS_CLASS_IN = 1 /**< DNS class IN. */
};
/**
@ -71,61 +69,59 @@ enum
*/
typedef enum pj_dns_type
{
PJ_DNS_TYPE_A = 1, /**< Host address (A) record. */
PJ_DNS_TYPE_NS = 2, /**< Authoritative name server (NS) */
PJ_DNS_TYPE_MD = 3, /**< Mail destination (MD) record. */
PJ_DNS_TYPE_MF = 4, /**< Mail forwarder (MF) record. */
PJ_DNS_TYPE_CNAME = 5, /**< Canonical name (CNAME) record. */
PJ_DNS_TYPE_SOA = 6, /**< Marks start of zone authority. */
PJ_DNS_TYPE_MB = 7, /**< Mailbox domain name (MB). */
PJ_DNS_TYPE_MG = 8, /**< Mail group member (MG). */
PJ_DNS_TYPE_MR = 9, /**< Mail rename domain name. */
PJ_DNS_TYPE_NULL = 10, /**< NULL RR. */
PJ_DNS_TYPE_WKS = 11, /**< Well known service description */
PJ_DNS_TYPE_PTR = 12, /**< Domain name pointer. */
PJ_DNS_TYPE_HINFO = 13, /**< Host information. */
PJ_DNS_TYPE_MINFO = 14, /**< Mailbox or mail list information. */
PJ_DNS_TYPE_MX = 15, /**< Mail exchange record. */
PJ_DNS_TYPE_TXT = 16, /**< Text string. */
PJ_DNS_TYPE_RP = 17, /**< Responsible person. */
PJ_DNS_TYPE_AFSB = 18, /**< AFS cell database. */
PJ_DNS_TYPE_X25 = 19, /**< X.25 calling address. */
PJ_DNS_TYPE_ISDN = 20, /**< ISDN calling address. */
PJ_DNS_TYPE_RT = 21, /**< Router. */
PJ_DNS_TYPE_NSAP = 22, /**< NSAP address. */
PJ_DNS_TYPE_NSAP_PTR= 23, /**< NSAP reverse address. */
PJ_DNS_TYPE_SIG = 24, /**< Signature. */
PJ_DNS_TYPE_KEY = 25, /**< Key. */
PJ_DNS_TYPE_PX = 26, /**< X.400 mail mapping. */
PJ_DNS_TYPE_GPOS = 27, /**< Geographical position (withdrawn) */
PJ_DNS_TYPE_AAAA = 28, /**< IPv6 address. */
PJ_DNS_TYPE_LOC = 29, /**< Location. */
PJ_DNS_TYPE_NXT = 30, /**< Next valid name in the zone. */
PJ_DNS_TYPE_EID = 31, /**< Endpoint idenfitier. */
PJ_DNS_TYPE_NIMLOC = 32, /**< Nimrod locator. */
PJ_DNS_TYPE_SRV = 33, /**< Server selection (SRV) record. */
PJ_DNS_TYPE_ATMA = 34, /**< DNS ATM address record. */
PJ_DNS_TYPE_NAPTR = 35, /**< DNS Naming authority pointer record. */
PJ_DNS_TYPE_KX = 36, /**< DNS key exchange record. */
PJ_DNS_TYPE_CERT = 37, /**< DNS certificate record. */
PJ_DNS_TYPE_A6 = 38, /**< DNS IPv6 address (experimental) */
PJ_DNS_TYPE_DNAME = 39, /**< DNS non-terminal name redirection rec. */
PJ_DNS_TYPE_A = 1, /**< Host address (A) record. */
PJ_DNS_TYPE_NS = 2, /**< Authoritative name server (NS) */
PJ_DNS_TYPE_MD = 3, /**< Mail destination (MD) record. */
PJ_DNS_TYPE_MF = 4, /**< Mail forwarder (MF) record. */
PJ_DNS_TYPE_CNAME = 5, /**< Canonical name (CNAME) record. */
PJ_DNS_TYPE_SOA = 6, /**< Marks start of zone authority. */
PJ_DNS_TYPE_MB = 7, /**< Mailbox domain name (MB). */
PJ_DNS_TYPE_MG = 8, /**< Mail group member (MG). */
PJ_DNS_TYPE_MR = 9, /**< Mail rename domain name. */
PJ_DNS_TYPE_NULL = 10, /**< NULL RR. */
PJ_DNS_TYPE_WKS = 11, /**< Well known service description */
PJ_DNS_TYPE_PTR = 12, /**< Domain name pointer. */
PJ_DNS_TYPE_HINFO = 13, /**< Host information. */
PJ_DNS_TYPE_MINFO = 14, /**< Mailbox or mail list information. */
PJ_DNS_TYPE_MX = 15, /**< Mail exchange record. */
PJ_DNS_TYPE_TXT = 16, /**< Text string. */
PJ_DNS_TYPE_RP = 17, /**< Responsible person. */
PJ_DNS_TYPE_AFSB = 18, /**< AFS cell database. */
PJ_DNS_TYPE_X25 = 19, /**< X.25 calling address. */
PJ_DNS_TYPE_ISDN = 20, /**< ISDN calling address. */
PJ_DNS_TYPE_RT = 21, /**< Router. */
PJ_DNS_TYPE_NSAP = 22, /**< NSAP address. */
PJ_DNS_TYPE_NSAP_PTR = 23, /**< NSAP reverse address. */
PJ_DNS_TYPE_SIG = 24, /**< Signature. */
PJ_DNS_TYPE_KEY = 25, /**< Key. */
PJ_DNS_TYPE_PX = 26, /**< X.400 mail mapping. */
PJ_DNS_TYPE_GPOS = 27, /**< Geographical position (withdrawn) */
PJ_DNS_TYPE_AAAA = 28, /**< IPv6 address. */
PJ_DNS_TYPE_LOC = 29, /**< Location. */
PJ_DNS_TYPE_NXT = 30, /**< Next valid name in the zone. */
PJ_DNS_TYPE_EID = 31, /**< Endpoint idenfitier. */
PJ_DNS_TYPE_NIMLOC = 32, /**< Nimrod locator. */
PJ_DNS_TYPE_SRV = 33, /**< Server selection (SRV) record. */
PJ_DNS_TYPE_ATMA = 34, /**< DNS ATM address record. */
PJ_DNS_TYPE_NAPTR = 35, /**< DNS Naming authority pointer record. */
PJ_DNS_TYPE_KX = 36, /**< DNS key exchange record. */
PJ_DNS_TYPE_CERT = 37, /**< DNS certificate record. */
PJ_DNS_TYPE_A6 = 38, /**< DNS IPv6 address (experimental) */
PJ_DNS_TYPE_DNAME = 39, /**< DNS non-terminal name redirection rec. */
PJ_DNS_TYPE_OPT = 41, /**< DNS options - contains EDNS metadata. */
PJ_DNS_TYPE_APL = 42, /**< DNS Address Prefix List (APL) record. */
PJ_DNS_TYPE_DS = 43, /**< DNS Delegation Signer (DS) */
PJ_DNS_TYPE_SSHFP = 44, /**< DNS SSH Key Fingerprint */
PJ_DNS_TYPE_IPSECKEY= 45, /**< DNS IPSEC Key. */
PJ_DNS_TYPE_RRSIG = 46, /**< DNS Resource Record signature. */
PJ_DNS_TYPE_NSEC = 47, /**< DNS Next Secure Name. */
PJ_DNS_TYPE_DNSKEY = 48 /**< DNSSEC Key. */
PJ_DNS_TYPE_OPT = 41, /**< DNS options - contains EDNS metadata. */
PJ_DNS_TYPE_APL = 42, /**< DNS Address Prefix List (APL) record. */
PJ_DNS_TYPE_DS = 43, /**< DNS Delegation Signer (DS) */
PJ_DNS_TYPE_SSHFP = 44, /**< DNS SSH Key Fingerprint */
PJ_DNS_TYPE_IPSECKEY = 45, /**< DNS IPSEC Key. */
PJ_DNS_TYPE_RRSIG = 46, /**< DNS Resource Record signature. */
PJ_DNS_TYPE_NSEC = 47, /**< DNS Next Secure Name. */
PJ_DNS_TYPE_DNSKEY = 48 /**< DNSSEC Key. */
} pj_dns_type;
/**
* Standard DNS header, according to RFC 1035, which will be present in
* both DNS query and DNS response.
* both DNS query and DNS response.
*
* Note that all values seen by application would be in
* host by order. The library would convert them to network
@ -133,148 +129,149 @@ typedef enum pj_dns_type
*/
typedef struct pj_dns_hdr
{
pj_uint16_t id; /**< Transaction ID. */
pj_uint16_t flags; /**< Flags. */
pj_uint16_t qdcount; /**< Nb. of queries. */
pj_uint16_t anscount; /**< Nb. of res records */
pj_uint16_t nscount; /**< Nb. of NS records. */
pj_uint16_t arcount; /**< Nb. of additional records */
pj_uint16_t id; /**< Transaction ID. */
pj_uint16_t flags; /**< Flags. */
pj_uint16_t qdcount; /**< Nb. of queries. */
pj_uint16_t anscount; /**< Nb. of res records */
pj_uint16_t nscount; /**< Nb. of NS records. */
pj_uint16_t arcount; /**< Nb. of additional records */
} pj_dns_hdr;
/** Create RCODE flag */
#define PJ_DNS_SET_RCODE(c) ((pj_uint16_t)((c) & 0x0F))
#define PJ_DNS_SET_RCODE(c) ((pj_uint16_t)((c)&0x0F))
/** Create RA (Recursion Available) bit */
#define PJ_DNS_SET_RA(on) ((pj_uint16_t)((on) << 7))
#define PJ_DNS_SET_RA(on) ((pj_uint16_t)((on) << 7))
/** Create RD (Recursion Desired) bit */
#define PJ_DNS_SET_RD(on) ((pj_uint16_t)((on) << 8))
#define PJ_DNS_SET_RD(on) ((pj_uint16_t)((on) << 8))
/** Create TC (Truncated) bit */
#define PJ_DNS_SET_TC(on) ((pj_uint16_t)((on) << 9))
#define PJ_DNS_SET_TC(on) ((pj_uint16_t)((on) << 9))
/** Create AA (Authoritative Answer) bit */
#define PJ_DNS_SET_AA(on) ((pj_uint16_t)((on) << 10))
#define PJ_DNS_SET_AA(on) ((pj_uint16_t)((on) << 10))
/** Create four bits opcode */
#define PJ_DNS_SET_OPCODE(o) ((pj_uint16_t)((o) << 11))
#define PJ_DNS_SET_OPCODE(o) ((pj_uint16_t)((o) << 11))
/** Create query/response bit */
#define PJ_DNS_SET_QR(on) ((pj_uint16_t)((on) << 15))
#define PJ_DNS_SET_QR(on) ((pj_uint16_t)((on) << 15))
/** Get RCODE value */
#define PJ_DNS_GET_RCODE(val) (((val) & PJ_DNS_SET_RCODE(0x0F)) >> 0)
#define PJ_DNS_GET_RCODE(val) (((val)&PJ_DNS_SET_RCODE(0x0F)) >> 0)
/** Get RA bit */
#define PJ_DNS_GET_RA(val) (((val) & PJ_DNS_SET_RA(1)) >> 7)
#define PJ_DNS_GET_RA(val) (((val)&PJ_DNS_SET_RA(1)) >> 7)
/** Get RD bit */
#define PJ_DNS_GET_RD(val) (((val) & PJ_DNS_SET_RD(1)) >> 8)
#define PJ_DNS_GET_RD(val) (((val)&PJ_DNS_SET_RD(1)) >> 8)
/** Get TC bit */
#define PJ_DNS_GET_TC(val) (((val) & PJ_DNS_SET_TC(1)) >> 9)
#define PJ_DNS_GET_TC(val) (((val)&PJ_DNS_SET_TC(1)) >> 9)
/** Get AA bit */
#define PJ_DNS_GET_AA(val) (((val) & PJ_DNS_SET_AA(1)) >> 10)
#define PJ_DNS_GET_AA(val) (((val)&PJ_DNS_SET_AA(1)) >> 10)
/** Get OPCODE value */
#define PJ_DNS_GET_OPCODE(val) (((val) & PJ_DNS_SET_OPCODE(0x0F)) >> 11)
#define PJ_DNS_GET_OPCODE(val) (((val)&PJ_DNS_SET_OPCODE(0x0F)) >> 11)
/** Get QR bit */
#define PJ_DNS_GET_QR(val) (((val) & PJ_DNS_SET_QR(1)) >> 15)
#define PJ_DNS_GET_QR(val) (((val)&PJ_DNS_SET_QR(1)) >> 15)
/**
/**
* These constants describe DNS RCODEs. Application can fold these constants
* into PJLIB pj_status_t namespace by calling #PJ_STATUS_FROM_DNS_RCODE()
* macro.
*/
typedef enum pj_dns_rcode
{
PJ_DNS_RCODE_FORMERR = 1, /**< Format error. */
PJ_DNS_RCODE_SERVFAIL = 2, /**< Server failure. */
PJ_DNS_RCODE_NXDOMAIN = 3, /**< Name Error. */
PJ_DNS_RCODE_NOTIMPL = 4, /**< Not Implemented. */
PJ_DNS_RCODE_REFUSED = 5, /**< Refused. */
PJ_DNS_RCODE_YXDOMAIN = 6, /**< The name exists. */
PJ_DNS_RCODE_YXRRSET = 7, /**< The RRset (name, type) exists. */
PJ_DNS_RCODE_NXRRSET = 8, /**< The RRset (name, type) doesn't exist*/
PJ_DNS_RCODE_NOTAUTH = 9, /**< Not authorized. */
PJ_DNS_RCODE_NOTZONE = 10 /**< The zone specified is not a zone. */
PJ_DNS_RCODE_FORMERR = 1, /**< Format error. */
PJ_DNS_RCODE_SERVFAIL = 2, /**< Server failure. */
PJ_DNS_RCODE_NXDOMAIN = 3, /**< Name Error. */
PJ_DNS_RCODE_NOTIMPL = 4, /**< Not Implemented. */
PJ_DNS_RCODE_REFUSED = 5, /**< Refused. */
PJ_DNS_RCODE_YXDOMAIN = 6, /**< The name exists. */
PJ_DNS_RCODE_YXRRSET = 7, /**< The RRset (name, type) exists. */
PJ_DNS_RCODE_NXRRSET = 8, /**< The RRset (name, type) doesn't exist*/
PJ_DNS_RCODE_NOTAUTH = 9, /**< Not authorized. */
PJ_DNS_RCODE_NOTZONE = 10 /**< The zone specified is not a zone. */
} pj_dns_rcode;
/**
* This structure describes a DNS query record.
*/
typedef struct pj_dns_parsed_query
{
pj_str_t name; /**< The domain in the query. */
pj_uint16_t type; /**< Type of the query (pj_dns_type) */
pj_uint16_t dnsclass; /**< Network class (PJ_DNS_CLASS_IN=1) */
pj_str_t name; /**< The domain in the query. */
pj_uint16_t type; /**< Type of the query (pj_dns_type) */
pj_uint16_t dnsclass; /**< Network class (PJ_DNS_CLASS_IN=1) */
} pj_dns_parsed_query;
/**
* This structure describes a Resource Record parsed from the DNS packet.
* All integral values are in host byte order.
*/
typedef struct pj_dns_parsed_rr
{
pj_str_t name; /**< The domain name which this rec pertains. */
pj_uint16_t type; /**< RR type code. */
pj_uint16_t dnsclass; /**< Class of data (PJ_DNS_CLASS_IN=1). */
pj_uint32_t ttl; /**< Time to live. */
pj_uint16_t rdlength; /**< Resource data length. */
void *data; /**< Pointer to the raw resource data, only
when the type is not known. If it is known,
the data will be put in rdata below. */
pj_str_t name; /**< The domain name which this rec pertains. */
pj_uint16_t type; /**< RR type code. */
pj_uint16_t dnsclass; /**< Class of data (PJ_DNS_CLASS_IN=1). */
pj_uint32_t ttl; /**< Time to live. */
pj_uint16_t rdlength; /**< Resource data length. */
void* data; /**< Pointer to the raw resource data, only
when the type is not known. If it is known,
the data will be put in rdata below. */
/** For resource types that are recognized/supported by this library,
* the parsed resource data will be placed in this rdata union.
*/
union rdata
{
/** SRV Resource Data (PJ_DNS_TYPE_SRV, 33) */
struct srv {
pj_uint16_t prio; /**< Target priority (lower is higher). */
pj_uint16_t weight; /**< Weight/proportion */
pj_uint16_t port; /**< Port number of the service */
pj_str_t target; /**< Target name. */
} srv;
/** SRV Resource Data (PJ_DNS_TYPE_SRV, 33) */
struct srv
{
pj_uint16_t prio; /**< Target priority (lower is higher). */
pj_uint16_t weight; /**< Weight/proportion */
pj_uint16_t port; /**< Port number of the service */
pj_str_t target; /**< Target name. */
} srv;
/** CNAME Resource Data (PJ_DNS_TYPE_CNAME, 5) */
struct cname {
pj_str_t name; /**< Primary canonical name for an alias. */
} cname;
/** CNAME Resource Data (PJ_DNS_TYPE_CNAME, 5) */
struct cname
{
pj_str_t name; /**< Primary canonical name for an alias. */
} cname;
/** NS Resource Data (PJ_DNS_TYPE_NS, 2) */
struct ns {
pj_str_t name; /**< Primary name server. */
} ns;
/** NS Resource Data (PJ_DNS_TYPE_NS, 2) */
struct ns
{
pj_str_t name; /**< Primary name server. */
} ns;
/** PTR Resource Data (PJ_DNS_TYPE_PTR, 12) */
struct ptr {
pj_str_t name; /**< PTR name. */
} ptr;
/** PTR Resource Data (PJ_DNS_TYPE_PTR, 12) */
struct ptr
{
pj_str_t name; /**< PTR name. */
} ptr;
/** A Resource Data (PJ_DNS_TYPE_A, 1) */
struct a {
pj_in_addr ip_addr;/**< IPv4 address in network byte order. */
} a;
/** A Resource Data (PJ_DNS_TYPE_A, 1) */
struct a
{
pj_in_addr ip_addr; /**< IPv4 address in network byte order. */
} a;
/** AAAA Resource Data (PJ_DNS_TYPE_AAAA, 28) */
struct aaaa {
pj_in6_addr ip_addr;/**< IPv6 address in network byte order. */
} aaaa;
/** AAAA Resource Data (PJ_DNS_TYPE_AAAA, 28) */
struct aaaa
{
pj_in6_addr ip_addr; /**< IPv6 address in network byte order. */
} aaaa;
} rdata;
} pj_dns_parsed_rr;
/**
* This structure describes the parsed repersentation of the raw DNS packet.
* Note that all integral values in the parsed packet are represented in
@ -282,27 +279,25 @@ typedef struct pj_dns_parsed_rr
*/
typedef struct pj_dns_parsed_packet
{
pj_dns_hdr hdr; /**< Pointer to DNS hdr, in host byte order */
pj_dns_parsed_query *q; /**< Array of DNS queries. */
pj_dns_parsed_rr *ans; /**< Array of DNS RR answer. */
pj_dns_parsed_rr *ns; /**< Array of NS record in the answer. */
pj_dns_parsed_rr *arr; /**< Array of additional RR answer. */
pj_dns_hdr hdr; /**< Pointer to DNS hdr, in host byte order */
pj_dns_parsed_query* q; /**< Array of DNS queries. */
pj_dns_parsed_rr* ans; /**< Array of DNS RR answer. */
pj_dns_parsed_rr* ns; /**< Array of NS record in the answer. */
pj_dns_parsed_rr* arr; /**< Array of additional RR answer. */
} pj_dns_parsed_packet;
/**
* Option flags to be specified when calling #pj_dns_packet_dup() function.
* These flags can be combined with bitwise OR operation.
*/
enum pj_dns_dup_options
{
PJ_DNS_NO_QD = 1, /**< Do not duplicate the query section. */
PJ_DNS_NO_ANS = 2, /**< Do not duplicate the answer section. */
PJ_DNS_NO_NS = 4, /**< Do not duplicate the NS section. */
PJ_DNS_NO_AR = 8 /**< Do not duplicate the additional rec section */
PJ_DNS_NO_QD = 1, /**< Do not duplicate the query section. */
PJ_DNS_NO_ANS = 2, /**< Do not duplicate the answer section. */
PJ_DNS_NO_NS = 4, /**< Do not duplicate the NS section. */
PJ_DNS_NO_AR = 8 /**< Do not duplicate the additional rec section */
};
/**
* Create DNS query packet to resolve the specified names. This function
* can be used to build any types of DNS query, such as A record or DNS SRV
@ -324,11 +319,9 @@ enum pj_dns_dup_options
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_dns_make_query(void *packet,
unsigned *size,
pj_uint16_t id,
int qtype,
const pj_str_t *name);
PJ_DECL(pj_status_t)
pj_dns_make_query(void* packet, unsigned* size, pj_uint16_t id, int qtype,
const pj_str_t* name);
/**
* Parse raw DNS packet into parsed DNS packet structure. This function is
@ -336,17 +329,16 @@ PJ_DECL(pj_status_t) pj_dns_make_query(void *packet,
* CNAME record, NS record, and SRV record.
*
* @param pool Pool to allocate memory for the parsed packet.
* @param packet Pointer to the DNS packet (the TCP/UDP payload of
* @param packet Pointer to the DNS packet (the TCP/UDP payload of
* the raw packet).
* @param size The size of the DNS packet.
* @param p_res Pointer to store the resulting parsed packet.
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_dns_parse_packet(pj_pool_t *pool,
const void *packet,
unsigned size,
pj_dns_parsed_packet **p_res);
PJ_DECL(pj_status_t)
pj_dns_parse_packet(pj_pool_t* pool, const void* packet, unsigned size,
pj_dns_parsed_packet** p_res);
/**
* Duplicate DNS packet.
@ -356,11 +348,9 @@ PJ_DECL(pj_status_t) pj_dns_parse_packet(pj_pool_t *pool,
* @param options Option flags, from pj_dns_dup_options.
* @param p_dst Pointer to store the cloned DNS packet.
*/
PJ_DECL(void) pj_dns_packet_dup(pj_pool_t *pool,
const pj_dns_parsed_packet*p,
unsigned options,
pj_dns_parsed_packet **p_dst);
PJ_DECL(void)
pj_dns_packet_dup(pj_pool_t* pool, const pj_dns_parsed_packet* p,
unsigned options, pj_dns_parsed_packet** p_dst);
/**
* Utility function to get the type name string of the specified DNS type.
@ -369,8 +359,7 @@ PJ_DECL(void) pj_dns_packet_dup(pj_pool_t *pool,
*
* @return String name of the type (e.g. "A", "SRV", etc.).
*/
PJ_DECL(const char *) pj_dns_get_type_name(int type);
PJ_DECL(const char*) pj_dns_get_type_name(int type);
/**
* Initialize DNS record as DNS SRV record.
@ -385,14 +374,10 @@ PJ_DECL(const char *) pj_dns_get_type_name(int type);
* @param port Target port.
* @param target Target name.
*/
PJ_DECL(void) pj_dns_init_srv_rr(pj_dns_parsed_rr *rec,
const pj_str_t *res_name,
unsigned dnsclass,
unsigned ttl,
unsigned prio,
unsigned weight,
unsigned port,
const pj_str_t *target);
PJ_DECL(void)
pj_dns_init_srv_rr(pj_dns_parsed_rr* rec, const pj_str_t* res_name,
unsigned dnsclass, unsigned ttl, unsigned prio,
unsigned weight, unsigned port, const pj_str_t* target);
/**
* Initialize DNS record as DNS CNAME record.
@ -404,11 +389,9 @@ PJ_DECL(void) pj_dns_init_srv_rr(pj_dns_parsed_rr *rec,
* @param ttl Resource TTL value.
* @param name Host name.
*/
PJ_DECL(void) pj_dns_init_cname_rr(pj_dns_parsed_rr *rec,
const pj_str_t *res_name,
unsigned dnsclass,
unsigned ttl,
const pj_str_t *name);
PJ_DECL(void)
pj_dns_init_cname_rr(pj_dns_parsed_rr* rec, const pj_str_t* res_name,
unsigned dnsclass, unsigned ttl, const pj_str_t* name);
/**
* Initialize DNS record as DNS A record.
@ -420,11 +403,9 @@ PJ_DECL(void) pj_dns_init_cname_rr(pj_dns_parsed_rr *rec,
* @param ttl Resource TTL value.
* @param ip_addr Host address.
*/
PJ_DECL(void) pj_dns_init_a_rr(pj_dns_parsed_rr *rec,
const pj_str_t *res_name,
unsigned dnsclass,
unsigned ttl,
const pj_in_addr *ip_addr);
PJ_DECL(void)
pj_dns_init_a_rr(pj_dns_parsed_rr* rec, const pj_str_t* res_name,
unsigned dnsclass, unsigned ttl, const pj_in_addr* ip_addr);
/**
* Initialize DNS record as DNS AAAA record.
@ -436,19 +417,17 @@ PJ_DECL(void) pj_dns_init_a_rr(pj_dns_parsed_rr *rec,
* @param ttl Resource TTL value.
* @param ip_addr Host address.
*/
PJ_DECL(void) pj_dns_init_aaaa_rr(pj_dns_parsed_rr *rec,
const pj_str_t *res_name,
unsigned dnsclass,
unsigned ttl,
const pj_in6_addr *ip_addr);
PJ_DECL(void)
pj_dns_init_aaaa_rr(pj_dns_parsed_rr* rec, const pj_str_t* res_name,
unsigned dnsclass, unsigned ttl,
const pj_in6_addr* ip_addr);
/**
* Dump DNS packet to standard log.
*
* @param res The DNS packet.
*/
PJ_DECL(void) pj_dns_dump_packet(const pj_dns_parsed_packet *res);
PJ_DECL(void) pj_dns_dump_packet(const pj_dns_parsed_packet* res);
/**
* @}
@ -456,6 +435,4 @@ PJ_DECL(void) pj_dns_dump_packet(const pj_dns_parsed_packet *res);
PJ_END_DECL
#endif /* __PJLIB_UTIL_DNS_H__ */
#endif /* __PJLIB_UTIL_DNS_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_DNS_SERVER_H__
#define __PJLIB_UTIL_DNS_SERVER_H__
@ -33,8 +32,8 @@ PJ_BEGIN_DECL
* @defgroup PJ_DNS_SERVER Simple DNS Server
* @ingroup PJ_DNS
* @{
* This contains a simple but fully working DNS server implementation,
* mostly for testing purposes. It supports serving various DNS resource
* This contains a simple but fully working DNS server implementation,
* mostly for testing purposes. It supports serving various DNS resource
* records such as SRV, CNAME, A, and AAAA.
*/
@ -59,12 +58,9 @@ typedef struct pj_dns_server pj_dns_server;
* otherwise the function will return the appropriate
* error code.
*/
PJ_DECL(pj_status_t) pj_dns_server_create(pj_pool_factory *pf,
pj_ioqueue_t *ioqueue,
int af,
unsigned port,
unsigned flags,
pj_dns_server **p_srv);
PJ_DECL(pj_status_t)
pj_dns_server_create(pj_pool_factory* pf, pj_ioqueue_t* ioqueue, int af,
unsigned port, unsigned flags, pj_dns_server** p_srv);
/**
* Destroy DNS server instance.
@ -73,8 +69,7 @@ PJ_DECL(pj_status_t) pj_dns_server_create(pj_pool_factory *pf,
*
* @return PJ_SUCCESS on success or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_dns_server_destroy(pj_dns_server *srv);
PJ_DECL(pj_status_t) pj_dns_server_destroy(pj_dns_server* srv);
/**
* Add generic resource record entries to the server.
@ -85,9 +80,9 @@ PJ_DECL(pj_status_t) pj_dns_server_destroy(pj_dns_server *srv);
*
* @return PJ_SUCCESS on success or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_dns_server_add_rec(pj_dns_server *srv,
unsigned count,
const pj_dns_parsed_rr rr[]);
PJ_DECL(pj_status_t)
pj_dns_server_add_rec(pj_dns_server* srv, unsigned count,
const pj_dns_parsed_rr rr[]);
/**
* Remove the specified record from the server.
@ -99,12 +94,9 @@ PJ_DECL(pj_status_t) pj_dns_server_add_rec(pj_dns_server *srv,
*
* @return PJ_SUCCESS on success or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_dns_server_del_rec(pj_dns_server *srv,
int dns_class,
pj_dns_type type,
const pj_str_t *name);
PJ_DECL(pj_status_t)
pj_dns_server_del_rec(pj_dns_server* srv, int dns_class, pj_dns_type type,
const pj_str_t* name);
/**
* @}
@ -112,6 +104,4 @@ PJ_DECL(pj_status_t) pj_dns_server_del_rec(pj_dns_server *srv,
PJ_END_DECL
#endif /* __PJLIB_UTIL_DNS_SERVER_H__ */
#endif /* __PJLIB_UTIL_DNS_SERVER_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,12 +14,11 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_ERRNO_H__
#define __PJLIB_UTIL_ERRNO_H__
#include <pj/errno.h>
/**
@ -33,8 +31,7 @@
* Start of error code relative to PJ_ERRNO_START_USER.
* This value is 320000.
*/
#define PJLIB_UTIL_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*3)
#define PJLIB_UTIL_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE * 3)
/************************************************************
* STUN ERROR
@ -43,69 +40,67 @@
* @hideinitializer
* Unable to resolve STUN server
*/
#define PJLIB_UTIL_ESTUNRESOLVE (PJLIB_UTIL_ERRNO_START+1) /* 320001 */
#define PJLIB_UTIL_ESTUNRESOLVE (PJLIB_UTIL_ERRNO_START + 1) /* 320001 */
/**
* @hideinitializer
* Unknown STUN message type.
*/
#define PJLIB_UTIL_ESTUNINMSGTYPE (PJLIB_UTIL_ERRNO_START+2) /* 320002 */
#define PJLIB_UTIL_ESTUNINMSGTYPE (PJLIB_UTIL_ERRNO_START + 2) /* 320002 */
/**
* @hideinitializer
* Invalid STUN message length
*/
#define PJLIB_UTIL_ESTUNINMSGLEN (PJLIB_UTIL_ERRNO_START+3) /* 320003 */
#define PJLIB_UTIL_ESTUNINMSGLEN (PJLIB_UTIL_ERRNO_START + 3) /* 320003 */
/**
* @hideinitializer
* Invalid STUN attribute length
*/
#define PJLIB_UTIL_ESTUNINATTRLEN (PJLIB_UTIL_ERRNO_START+4) /* 320004 */
#define PJLIB_UTIL_ESTUNINATTRLEN (PJLIB_UTIL_ERRNO_START + 4) /* 320004 */
/**
* @hideinitializer
* Invalid STUN attribute type
*/
#define PJLIB_UTIL_ESTUNINATTRTYPE (PJLIB_UTIL_ERRNO_START+5) /* 320005 */
#define PJLIB_UTIL_ESTUNINATTRTYPE (PJLIB_UTIL_ERRNO_START + 5) /* 320005 */
/**
* @hideinitializer
* Invalid STUN server/socket index
*/
#define PJLIB_UTIL_ESTUNININDEX (PJLIB_UTIL_ERRNO_START+6) /* 320006 */
#define PJLIB_UTIL_ESTUNININDEX (PJLIB_UTIL_ERRNO_START + 6) /* 320006 */
/**
* @hideinitializer
* No STUN binding response in the message
*/
#define PJLIB_UTIL_ESTUNNOBINDRES (PJLIB_UTIL_ERRNO_START+7) /* 320007 */
#define PJLIB_UTIL_ESTUNNOBINDRES (PJLIB_UTIL_ERRNO_START + 7) /* 320007 */
/**
* @hideinitializer
* Received STUN error attribute
*/
#define PJLIB_UTIL_ESTUNRECVERRATTR (PJLIB_UTIL_ERRNO_START+8) /* 320008 */
#define PJLIB_UTIL_ESTUNRECVERRATTR (PJLIB_UTIL_ERRNO_START + 8) /* 320008 */
/**
* @hideinitializer
* No STUN mapped address attribute
*/
#define PJLIB_UTIL_ESTUNNOMAP (PJLIB_UTIL_ERRNO_START+9) /* 320009 */
#define PJLIB_UTIL_ESTUNNOMAP (PJLIB_UTIL_ERRNO_START + 9) /* 320009 */
/**
* @hideinitializer
* Received no response from STUN server
*/
#define PJLIB_UTIL_ESTUNNOTRESPOND (PJLIB_UTIL_ERRNO_START+10) /* 320010 */
#define PJLIB_UTIL_ESTUNNOTRESPOND (PJLIB_UTIL_ERRNO_START + 10) /* 320010 */
/**
* @hideinitializer
* Symetric NAT detected by STUN
*/
#define PJLIB_UTIL_ESTUNSYMMETRIC (PJLIB_UTIL_ERRNO_START+11) /* 320011 */
#define PJLIB_UTIL_ESTUNSYMMETRIC (PJLIB_UTIL_ERRNO_START + 11) /* 320011 */
/**
* @hideinitializer
* Invalid STUN magic value
*/
#define PJLIB_UTIL_ESTUNNOTMAGIC (PJLIB_UTIL_ERRNO_START+12) /* 320012 */
#define PJLIB_UTIL_ESTUNNOTMAGIC (PJLIB_UTIL_ERRNO_START + 12) /* 320012 */
/**
* @hideinitializer
* Invalid STUN fingerprint value
*/
#define PJLIB_UTIL_ESTUNFINGERPRINT (PJLIB_UTIL_ERRNO_START+13) /* 320013 */
#define PJLIB_UTIL_ESTUNFINGERPRINT (PJLIB_UTIL_ERRNO_START + 13) /* 320013 */
/************************************************************
* XML ERROR
@ -114,8 +109,7 @@
* @hideinitializer
* General invalid XML message.
*/
#define PJLIB_UTIL_EINXML (PJLIB_UTIL_ERRNO_START+20) /* 320020 */
#define PJLIB_UTIL_EINXML (PJLIB_UTIL_ERRNO_START + 20) /* 320020 */
/************************************************************
* JSON ERROR
@ -124,8 +118,7 @@
* @hideinitializer
* General invalid JSON message.
*/
#define PJLIB_UTIL_EINJSON (PJLIB_UTIL_ERRNO_START+30) /* 320030 */
#define PJLIB_UTIL_EINJSON (PJLIB_UTIL_ERRNO_START + 30) /* 320030 */
/************************************************************
* DNS ERROR
@ -136,21 +129,21 @@
* This error occurs when the user supplied buffer for creating DNS
* query (#pj_dns_make_query() function) is too small.
*/
#define PJLIB_UTIL_EDNSQRYTOOSMALL (PJLIB_UTIL_ERRNO_START+40) /* 320040 */
#define PJLIB_UTIL_EDNSQRYTOOSMALL (PJLIB_UTIL_ERRNO_START + 40) /* 320040 */
/**
* @hideinitializer
* Invalid DNS packet length.
* This error occurs when the received DNS response packet does not
* match all the fields length.
*/
#define PJLIB_UTIL_EDNSINSIZE (PJLIB_UTIL_ERRNO_START+41) /* 320041 */
#define PJLIB_UTIL_EDNSINSIZE (PJLIB_UTIL_ERRNO_START + 41) /* 320041 */
/**
* @hideinitializer
* Invalid DNS class.
* This error occurs when the received DNS response contains network
* class other than IN (Internet).
*/
#define PJLIB_UTIL_EDNSINCLASS (PJLIB_UTIL_ERRNO_START+42) /* 320042 */
#define PJLIB_UTIL_EDNSINCLASS (PJLIB_UTIL_ERRNO_START + 42) /* 320042 */
/**
* @hideinitializer
* Invalid DNS name pointer.
@ -158,119 +151,117 @@
* response packet, when the name pointer points to an invalid address
* or the parsing has triggerred too much recursion.
*/
#define PJLIB_UTIL_EDNSINNAMEPTR (PJLIB_UTIL_ERRNO_START+43) /* 320043 */
#define PJLIB_UTIL_EDNSINNAMEPTR (PJLIB_UTIL_ERRNO_START + 43) /* 320043 */
/**
* @hideinitializer
* Invalid DNS nameserver address. If hostname was specified for nameserver
* address, this error means that the function was unable to resolve
* the nameserver hostname.
*/
#define PJLIB_UTIL_EDNSINNSADDR (PJLIB_UTIL_ERRNO_START+44) /* 320044 */
#define PJLIB_UTIL_EDNSINNSADDR (PJLIB_UTIL_ERRNO_START + 44) /* 320044 */
/**
* @hideinitializer
* No nameserver is in DNS resolver. No nameserver is configured in the
* No nameserver is in DNS resolver. No nameserver is configured in the
* resolver.
*/
#define PJLIB_UTIL_EDNSNONS (PJLIB_UTIL_ERRNO_START+45) /* 320045 */
#define PJLIB_UTIL_EDNSNONS (PJLIB_UTIL_ERRNO_START + 45) /* 320045 */
/**
* @hideinitializer
* No working DNS nameserver. All nameservers have been queried,
* but none was able to serve any DNS requests. These "bad" nameservers
* will be re-tested again for "goodness" after some period.
*/
#define PJLIB_UTIL_EDNSNOWORKINGNS (PJLIB_UTIL_ERRNO_START+46) /* 320046 */
#define PJLIB_UTIL_EDNSNOWORKINGNS (PJLIB_UTIL_ERRNO_START + 46) /* 320046 */
/**
* @hideinitializer
* No answer record in the DNS response.
*/
#define PJLIB_UTIL_EDNSNOANSWERREC (PJLIB_UTIL_ERRNO_START+47) /* 320047 */
#define PJLIB_UTIL_EDNSNOANSWERREC (PJLIB_UTIL_ERRNO_START + 47) /* 320047 */
/**
* @hideinitializer
* Invalid DNS answer. This error is raised for example when the DNS
* answer does not have a query section, or the type of RR in the answer
* doesn't match the query.
*/
#define PJLIB_UTIL_EDNSINANSWER (PJLIB_UTIL_ERRNO_START+48) /* 320048 */
#define PJLIB_UTIL_EDNSINANSWER (PJLIB_UTIL_ERRNO_START + 48) /* 320048 */
/* DNS ERRORS MAPPED FROM RCODE: */
/**
* Start of error code mapped from DNS RCODE
*/
#define PJLIB_UTIL_DNS_RCODE_START (PJLIB_UTIL_ERRNO_START+50) /* 320050 */
#define PJLIB_UTIL_DNS_RCODE_START (PJLIB_UTIL_ERRNO_START + 50) /* 320050 */
/**
* Map DNS RCODE status into pj_status_t.
*/
#define PJ_STATUS_FROM_DNS_RCODE(rcode) (rcode==0 ? PJ_SUCCESS : \
PJLIB_UTIL_DNS_RCODE_START+rcode)
#define PJ_STATUS_FROM_DNS_RCODE(rcode) \
(rcode == 0 ? PJ_SUCCESS : PJLIB_UTIL_DNS_RCODE_START + rcode)
/**
* @hideinitializer
* Format error - The name server was unable to interpret the query.
* This corresponds to DNS RCODE 1.
*/
#define PJLIB_UTIL_EDNS_FORMERR PJ_STATUS_FROM_DNS_RCODE(1) /* 320051 */
#define PJLIB_UTIL_EDNS_FORMERR PJ_STATUS_FROM_DNS_RCODE(1) /* 320051 */
/**
* @hideinitializer
* Server failure - The name server was unable to process this query due to a
* problem with the name server.
* This corresponds to DNS RCODE 2.
*/
#define PJLIB_UTIL_EDNS_SERVFAIL PJ_STATUS_FROM_DNS_RCODE(2) /* 320052 */
#define PJLIB_UTIL_EDNS_SERVFAIL PJ_STATUS_FROM_DNS_RCODE(2) /* 320052 */
/**
* @hideinitializer
* Name Error - Meaningful only for responses from an authoritative name
* server, this code signifies that the domain name referenced in the query
* server, this code signifies that the domain name referenced in the query
* does not exist.
* This corresponds to DNS RCODE 3.
*/
#define PJLIB_UTIL_EDNS_NXDOMAIN PJ_STATUS_FROM_DNS_RCODE(3) /* 320053 */
#define PJLIB_UTIL_EDNS_NXDOMAIN PJ_STATUS_FROM_DNS_RCODE(3) /* 320053 */
/**
* @hideinitializer
* Not Implemented - The name server does not support the requested kind of
* Not Implemented - The name server does not support the requested kind of
* query.
* This corresponds to DNS RCODE 4.
*/
#define PJLIB_UTIL_EDNS_NOTIMPL PJ_STATUS_FROM_DNS_RCODE(4) /* 320054 */
#define PJLIB_UTIL_EDNS_NOTIMPL PJ_STATUS_FROM_DNS_RCODE(4) /* 320054 */
/**
* @hideinitializer
* Refused - The name server refuses to perform the specified operation for
* policy reasons.
* This corresponds to DNS RCODE 5.
*/
#define PJLIB_UTIL_EDNS_REFUSED PJ_STATUS_FROM_DNS_RCODE(5) /* 320055 */
#define PJLIB_UTIL_EDNS_REFUSED PJ_STATUS_FROM_DNS_RCODE(5) /* 320055 */
/**
* @hideinitializer
* The name exists.
* This corresponds to DNS RCODE 6.
*/
#define PJLIB_UTIL_EDNS_YXDOMAIN PJ_STATUS_FROM_DNS_RCODE(6) /* 320056 */
#define PJLIB_UTIL_EDNS_YXDOMAIN PJ_STATUS_FROM_DNS_RCODE(6) /* 320056 */
/**
* @hideinitializer
* The RRset (name, type) exists.
* This corresponds to DNS RCODE 7.
*/
#define PJLIB_UTIL_EDNS_YXRRSET PJ_STATUS_FROM_DNS_RCODE(7) /* 320057 */
#define PJLIB_UTIL_EDNS_YXRRSET PJ_STATUS_FROM_DNS_RCODE(7) /* 320057 */
/**
* @hideinitializer
* The RRset (name, type) does not exist.
* This corresponds to DNS RCODE 8.
*/
#define PJLIB_UTIL_EDNS_NXRRSET PJ_STATUS_FROM_DNS_RCODE(8) /* 320058 */
#define PJLIB_UTIL_EDNS_NXRRSET PJ_STATUS_FROM_DNS_RCODE(8) /* 320058 */
/**
* @hideinitializer
* The requestor is not authorized to perform this operation.
* This corresponds to DNS RCODE 9.
*/
#define PJLIB_UTIL_EDNS_NOTAUTH PJ_STATUS_FROM_DNS_RCODE(9) /* 320059 */
#define PJLIB_UTIL_EDNS_NOTAUTH PJ_STATUS_FROM_DNS_RCODE(9) /* 320059 */
/**
* @hideinitializer
* The zone specified is not a zone.
* This corresponds to DNS RCODE 10.
*/
#define PJLIB_UTIL_EDNS_NOTZONE PJ_STATUS_FROM_DNS_RCODE(10)/* 320060 */
#define PJLIB_UTIL_EDNS_NOTZONE PJ_STATUS_FROM_DNS_RCODE(10) /* 320060 */
/************************************************************
* NEW STUN ERROR
@ -280,89 +271,92 @@
* @hideinitializer
* Too many STUN attributes.
*/
#define PJLIB_UTIL_ESTUNTOOMANYATTR (PJLIB_UTIL_ERRNO_START+110)/* 320110 */
#define PJLIB_UTIL_ESTUNTOOMANYATTR (PJLIB_UTIL_ERRNO_START + 110) /* 320110 \
*/
/**
* @hideinitializer
* Unknown STUN attribute. This error happens when the decoder encounters
* mandatory attribute type which it doesn't understand.
*/
#define PJLIB_UTIL_ESTUNUNKNOWNATTR (PJLIB_UTIL_ERRNO_START+111)/* 320111 */
#define PJLIB_UTIL_ESTUNUNKNOWNATTR (PJLIB_UTIL_ERRNO_START + 111) /* 320111 \
*/
/**
* @hideinitializer
* Invalid STUN socket address length.
*/
#define PJLIB_UTIL_ESTUNINADDRLEN (PJLIB_UTIL_ERRNO_START+112)/* 320112 */
#define PJLIB_UTIL_ESTUNINADDRLEN (PJLIB_UTIL_ERRNO_START + 112) /* 320112 */
/**
* @hideinitializer
* STUN IPv6 attribute not supported
*/
#define PJLIB_UTIL_ESTUNIPV6NOTSUPP (PJLIB_UTIL_ERRNO_START+113)/* 320113 */
#define PJLIB_UTIL_ESTUNIPV6NOTSUPP (PJLIB_UTIL_ERRNO_START + 113) /* 320113 \
*/
/**
* @hideinitializer
* Expecting STUN response message.
*/
#define PJLIB_UTIL_ESTUNNOTRESPONSE (PJLIB_UTIL_ERRNO_START+114)/* 320114 */
#define PJLIB_UTIL_ESTUNNOTRESPONSE (PJLIB_UTIL_ERRNO_START + 114) /* 320114 \
*/
/**
* @hideinitializer
* STUN transaction ID mismatch.
*/
#define PJLIB_UTIL_ESTUNINVALIDID (PJLIB_UTIL_ERRNO_START+115)/* 320115 */
#define PJLIB_UTIL_ESTUNINVALIDID (PJLIB_UTIL_ERRNO_START + 115) /* 320115 */
/**
* @hideinitializer
* Unable to find handler for the request.
*/
#define PJLIB_UTIL_ESTUNNOHANDLER (PJLIB_UTIL_ERRNO_START+116)/* 320116 */
#define PJLIB_UTIL_ESTUNNOHANDLER (PJLIB_UTIL_ERRNO_START + 116) /* 320116 */
/**
* @hideinitializer
* Found non-FINGERPRINT attribute after MESSAGE-INTEGRITY. This is not
* valid since MESSAGE-INTEGRITY MUST be the last attribute or the
* attribute right before FINGERPRINT before the message.
*/
#define PJLIB_UTIL_ESTUNMSGINTPOS (PJLIB_UTIL_ERRNO_START+118)/* 320118 */
#define PJLIB_UTIL_ESTUNMSGINTPOS (PJLIB_UTIL_ERRNO_START + 118) /* 320118 */
/**
* @hideinitializer
* Found attribute after FINGERPRINT. This is not valid since FINGERPRINT
* MUST be the last attribute in the message.
*/
#define PJLIB_UTIL_ESTUNFINGERPOS (PJLIB_UTIL_ERRNO_START+119)/* 320119 */
#define PJLIB_UTIL_ESTUNFINGERPOS (PJLIB_UTIL_ERRNO_START + 119) /* 320119 */
/**
* @hideinitializer
* Missing STUN USERNAME attribute.
* When credential is included in the STUN message (MESSAGE-INTEGRITY is
* present), the USERNAME attribute must be present in the message.
*/
#define PJLIB_UTIL_ESTUNNOUSERNAME (PJLIB_UTIL_ERRNO_START+120)/* 320120 */
#define PJLIB_UTIL_ESTUNNOUSERNAME (PJLIB_UTIL_ERRNO_START + 120) /* 320120 */
/**
* @hideinitializer
* Unknown STUN username/credential.
*/
#define PJLIB_UTIL_ESTUNUSERNAME (PJLIB_UTIL_ERRNO_START+121)/* 320121 */
#define PJLIB_UTIL_ESTUNUSERNAME (PJLIB_UTIL_ERRNO_START + 121) /* 320121 */
/**
* @hideinitializer
* Missing/invalidSTUN MESSAGE-INTEGRITY attribute.
*/
#define PJLIB_UTIL_ESTUNMSGINT (PJLIB_UTIL_ERRNO_START+122)/* 320122 */
#define PJLIB_UTIL_ESTUNMSGINT (PJLIB_UTIL_ERRNO_START + 122) /* 320122 */
/**
* @hideinitializer
* Found duplicate STUN attribute.
*/
#define PJLIB_UTIL_ESTUNDUPATTR (PJLIB_UTIL_ERRNO_START+123)/* 320123 */
#define PJLIB_UTIL_ESTUNDUPATTR (PJLIB_UTIL_ERRNO_START + 123) /* 320123 */
/**
* @hideinitializer
* Missing STUN REALM attribute.
*/
#define PJLIB_UTIL_ESTUNNOREALM (PJLIB_UTIL_ERRNO_START+124)/* 320124 */
#define PJLIB_UTIL_ESTUNNOREALM (PJLIB_UTIL_ERRNO_START + 124) /* 320124 */
/**
* @hideinitializer
* Missing/stale STUN NONCE attribute value.
*/
#define PJLIB_UTIL_ESTUNNONCE (PJLIB_UTIL_ERRNO_START+125)/* 320125 */
#define PJLIB_UTIL_ESTUNNONCE (PJLIB_UTIL_ERRNO_START + 125) /* 320125 */
/**
* @hideinitializer
* STUN transaction terminates with failure.
*/
#define PJLIB_UTIL_ESTUNTSXFAILED (PJLIB_UTIL_ERRNO_START+126)/* 320126 */
#define PJLIB_UTIL_ESTUNTSXFAILED (PJLIB_UTIL_ERRNO_START + 126) /* 320126 */
//#define PJ_STATUS_FROM_STUN_CODE(code) (PJLIB_UTIL_ERRNO_START+code)
@ -373,27 +367,27 @@
* @hideinitializer
* Invalid URL format
*/
#define PJLIB_UTIL_EHTTPINURL (PJLIB_UTIL_ERRNO_START+151)/* 320151 */
#define PJLIB_UTIL_EHTTPINURL (PJLIB_UTIL_ERRNO_START + 151) /* 320151 */
/**
* @hideinitializer
* Invalid port number
*/
#define PJLIB_UTIL_EHTTPINPORT (PJLIB_UTIL_ERRNO_START+152)/* 320152 */
#define PJLIB_UTIL_EHTTPINPORT (PJLIB_UTIL_ERRNO_START + 152) /* 320152 */
/**
* @hideinitializer
* Incomplete headers received
*/
#define PJLIB_UTIL_EHTTPINCHDR (PJLIB_UTIL_ERRNO_START+153)/* 320153 */
#define PJLIB_UTIL_EHTTPINCHDR (PJLIB_UTIL_ERRNO_START + 153) /* 320153 */
/**
* @hideinitializer
* Insufficient buffer
*/
#define PJLIB_UTIL_EHTTPINSBUF (PJLIB_UTIL_ERRNO_START+154)/* 320154 */
#define PJLIB_UTIL_EHTTPINSBUF (PJLIB_UTIL_ERRNO_START + 154) /* 320154 */
/**
* @hideinitializer
* Connection lost
*/
#define PJLIB_UTIL_EHTTPLOST (PJLIB_UTIL_ERRNO_START+155)/* 320155 */
#define PJLIB_UTIL_EHTTPLOST (PJLIB_UTIL_ERRNO_START + 155) /* 320155 */
/************************************************************
* CLI ERROR
@ -405,52 +399,52 @@
* pj_cli_sess_exec() to indicate that "exit" or equivalent command has been
* called to end the current session.
*/
#define PJ_CLI_EEXIT (PJLIB_UTIL_ERRNO_START+201)/* 320201 */
#define PJ_CLI_EEXIT (PJLIB_UTIL_ERRNO_START + 201) /* 320201 */
/**
* @hideinitializer
* A required CLI argument is not specified.
*/
#define PJ_CLI_EMISSINGARG (PJLIB_UTIL_ERRNO_START+202)/* 320202 */
/**
* @hideinitializer
* Too many CLI arguments.
*/
#define PJ_CLI_ETOOMANYARGS (PJLIB_UTIL_ERRNO_START+203)/* 320203 */
#define PJ_CLI_EMISSINGARG (PJLIB_UTIL_ERRNO_START + 202) /* 320202 */
/**
* @hideinitializer
* Too many CLI arguments.
*/
#define PJ_CLI_ETOOMANYARGS (PJLIB_UTIL_ERRNO_START + 203) /* 320203 */
/**
* @hideinitializer
* Invalid CLI argument. Typically this is caused by extra characters
* specified in the command line which does not match any arguments.
*/
#define PJ_CLI_EINVARG (PJLIB_UTIL_ERRNO_START+204)/* 320204 */
#define PJ_CLI_EINVARG (PJLIB_UTIL_ERRNO_START + 204) /* 320204 */
/**
* @hideinitializer
* CLI command with the specified name already exist.
*/
#define PJ_CLI_EBADNAME (PJLIB_UTIL_ERRNO_START+205)/* 320205 */
#define PJ_CLI_EBADNAME (PJLIB_UTIL_ERRNO_START + 205) /* 320205 */
/**
* @hideinitializer
* CLI command with the specified id already exist.
*/
#define PJ_CLI_EBADID (PJLIB_UTIL_ERRNO_START+206)/* 320206 */
#define PJ_CLI_EBADID (PJLIB_UTIL_ERRNO_START + 206) /* 320206 */
/**
* @hideinitializer
* Invalid XML format for CLI command specification.
*/
#define PJ_CLI_EBADXML (PJLIB_UTIL_ERRNO_START+207)/* 320207 */
#define PJ_CLI_EBADXML (PJLIB_UTIL_ERRNO_START + 207) /* 320207 */
/**
* @hideinitializer
* CLI command entered by user match with more than one command/argument
* CLI command entered by user match with more than one command/argument
* specification.
*/
#define PJ_CLI_EAMBIGUOUS (PJLIB_UTIL_ERRNO_START+208)/* 320208 */
#define PJ_CLI_EAMBIGUOUS (PJLIB_UTIL_ERRNO_START + 208) /* 320208 */
/**
* @hideinitializer
* Telnet connection lost.
*/
#define PJ_CLI_ETELNETLOST (PJLIB_UTIL_ERRNO_START+211)/* 320211 */
#define PJ_CLI_ETELNETLOST (PJLIB_UTIL_ERRNO_START + 211) /* 320211 */
/**
* @}
*/
#endif /* __PJLIB_UTIL_ERRNO_H__ */
#endif /* __PJLIB_UTIL_ERRNO_H__ */

View File

@ -1,4 +1,3 @@
/* $Id$ */
/* Declarations for pj_getopt.
Copyright (C) 1989,90,91,92,93,94,96,97,98 Free Software Foundation, Inc.
This file is part of the GNU C Library.
@ -32,108 +31,108 @@
* @{
*/
#ifdef __cplusplus
extern "C" {
#ifdef __cplusplus
extern "C"
{
#endif
/* For communication from `pj_getopt' to the caller.
When `pj_getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
/* For communication from `pj_getopt' to the caller.
When `pj_getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
extern char *pj_optarg;
extern char* pj_optarg;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `pj_getopt'.
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `pj_getopt'.
On entry to `pj_getopt', zero means this is the first call; initialize.
On entry to `pj_getopt', zero means this is the first call; initialize.
When `pj_getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
When `pj_getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, `pj_optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
Otherwise, `pj_optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
extern int pj_optind;
extern int pj_optind;
/* Set to an option character which was unrecognized. */
/* Set to an option character which was unrecognized. */
extern int pj_optopt;
extern int pj_optopt;
/* Describe the long-named options requested by the application.
The LONG_OPTIONS argument to pj_getopt_long or pj_getopt_long_only is a vector
of `struct pj_getopt_option' terminated by an element containing a name which is
zero.
/* Describe the long-named options requested by the application.
The LONG_OPTIONS argument to pj_getopt_long or pj_getopt_long_only is a
vector of `struct pj_getopt_option' terminated by an element containing a
name which is zero.
The field `has_arg' is:
no_argument (or 0) if the option does not take an argument,
required_argument (or 1) if the option requires an argument,
optional_argument (or 2) if the option takes an optional argument.
The field `has_arg' is:
no_argument (or 0) if the option does not take an argument,
required_argument (or 1) if the option requires an argument,
optional_argument (or 2) if the option takes an optional argument.
If the field `flag' is not NULL, it points to a variable that is set
to the value given in the field `val' when the option is found, but
left unchanged if the option is not found.
If the field `flag' is not NULL, it points to a variable that is set
to the value given in the field `val' when the option is found, but
left unchanged if the option is not found.
To have a long-named option do something other than set an `int' to
a compiled-in constant, such as set a value from `pj_optarg', set the
option's `flag' field to zero and its `val' field to a nonzero
value (the equivalent single-letter option character, if there is
one). For long options that have a zero `flag' field, `pj_getopt'
returns the contents of the `val' field. */
To have a long-named option do something other than set an `int' to
a compiled-in constant, such as set a value from `pj_optarg', set the
option's `flag' field to zero and its `val' field to a nonzero
value (the equivalent single-letter option character, if there is
one). For long options that have a zero `flag' field, `pj_getopt'
returns the contents of the `val' field. */
struct pj_getopt_option
{
const char *name;
/* has_arg can't be an enum because some compilers complain about
type mismatches in all the code that assumes it is an int. */
int has_arg;
int *flag;
int val;
};
struct pj_getopt_option
{
const char* name;
/* has_arg can't be an enum because some compilers complain about
type mismatches in all the code that assumes it is an int. */
int has_arg;
int* flag;
int val;
};
/* Names for the values of the `has_arg' field of `struct pj_getopt_option'. */
/* Names for the values of the `has_arg' field of `struct pj_getopt_option'.
*/
# define no_argument 0
# define required_argument 1
# define optional_argument 2
#define no_argument 0
#define required_argument 1
#define optional_argument 2
/* Get definitions and prototypes for functions to process the
arguments in ARGV (ARGC of them, minus the program name) for
options given in OPTS.
/* Get definitions and prototypes for functions to process the
arguments in ARGV (ARGC of them, minus the program name) for
options given in OPTS.
Return the option character from OPTS just read. Return -1 when
there are no more options. For unrecognized options, or options
missing arguments, `pj_optopt' is set to the option letter, and '?' is
returned.
Return the option character from OPTS just read. Return -1 when
there are no more options. For unrecognized options, or options
missing arguments, `pj_optopt' is set to the option letter, and '?' is
returned.
The OPTS string is a list of characters which are recognized option
letters, optionally followed by colons, specifying that that letter
takes an argument, to be placed in `pj_optarg'.
The OPTS string is a list of characters which are recognized option
letters, optionally followed by colons, specifying that that letter
takes an argument, to be placed in `pj_optarg'.
If a letter in OPTS is followed by two colons, its argument is
optional. This behavior is specific to the GNU `pj_getopt'.
If a letter in OPTS is followed by two colons, its argument is
optional. This behavior is specific to the GNU `pj_getopt'.
The argument `--' causes premature termination of argument
scanning, explicitly telling `pj_getopt' that there are no more
options.
The argument `--' causes premature termination of argument
scanning, explicitly telling `pj_getopt' that there are no more
options.
If OPTS begins with `--', then non-option arguments are treated as
arguments to the option '\0'. This behavior is specific to the GNU
`pj_getopt'. */
If OPTS begins with `--', then non-option arguments are treated as
arguments to the option '\0'. This behavior is specific to the GNU
`pj_getopt'. */
int pj_getopt(int argc, char* const* argv, const char* shortopts);
int pj_getopt (int argc, char *const *argv, const char *shortopts);
int pj_getopt_long(int argc, char* const* argv, const char* options,
const struct pj_getopt_option* longopts, int* longind);
int pj_getopt_long_only(int argc, char* const* argv, const char* shortopts,
const struct pj_getopt_option* longopts,
int* longind);
int pj_getopt_long (int argc, char *const *argv, const char *options,
const struct pj_getopt_option *longopts, int *longind);
int pj_getopt_long_only (int argc, char *const *argv,
const char *shortopts,
const struct pj_getopt_option *longopts, int *longind);
#ifdef __cplusplus
#ifdef __cplusplus
}
#endif
@ -142,4 +141,3 @@ int pj_getopt_long_only (int argc, char *const *argv,
*/
#endif /* pj_getopt.h */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_HMAC_MD5_H__
#define __PJLIB_UTIL_HMAC_MD5_H__
@ -39,7 +38,7 @@ PJ_BEGIN_DECL
* @ingroup PJLIB_UTIL_ENCRYPTION
* @{
*
* This module contains the implementation of HMAC: Keyed-Hashing
* This module contains the implementation of HMAC: Keyed-Hashing
* for Message Authentication, as described in RFC 2104
*/
@ -48,11 +47,10 @@ PJ_BEGIN_DECL
*/
typedef struct pj_hmac_md5_context
{
pj_md5_context context; /**< MD5 context */
pj_uint8_t k_opad[64]; /**< opad xor-ed with key */
pj_md5_context context; /**< MD5 context */
pj_uint8_t k_opad[64]; /**< opad xor-ed with key */
} pj_hmac_md5_context;
/**
* Calculate HMAC MD5 digest for the specified input and key.
*
@ -62,10 +60,9 @@ typedef struct pj_hmac_md5_context
* @param key_len Length of the authentication key.
* @param digest Buffer to be filled with HMAC MD5 digest.
*/
PJ_DECL(void) pj_hmac_md5(const pj_uint8_t *input, unsigned input_len,
const pj_uint8_t *key, unsigned key_len,
pj_uint8_t digest[16]);
PJ_DECL(void)
pj_hmac_md5(const pj_uint8_t* input, unsigned input_len, const pj_uint8_t* key,
unsigned key_len, pj_uint8_t digest[16]);
/**
* Initiate HMAC-MD5 context for incremental hashing.
@ -74,8 +71,9 @@ PJ_DECL(void) pj_hmac_md5(const pj_uint8_t *input, unsigned input_len,
* @param key Pointer to the authentication key.
* @param key_len Length of the authentication key.
*/
PJ_DECL(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx,
const pj_uint8_t *key, unsigned key_len);
PJ_DECL(void)
pj_hmac_md5_init(pj_hmac_md5_context* hctx, const pj_uint8_t* key,
unsigned key_len);
/**
* Append string to the message.
@ -84,18 +82,18 @@ PJ_DECL(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx,
* @param input Pointer to the input stream.
* @param input_len Length of input stream in bytes.
*/
PJ_DECL(void) pj_hmac_md5_update(pj_hmac_md5_context *hctx,
const pj_uint8_t *input,
unsigned input_len);
PJ_DECL(void)
pj_hmac_md5_update(pj_hmac_md5_context* hctx, const pj_uint8_t* input,
unsigned input_len);
/**
* Finish the message and return the digest.
* Finish the message and return the digest.
*
* @param hctx HMAC-MD5 context.
* @param digest Buffer to be filled with HMAC MD5 digest.
*/
PJ_DECL(void) pj_hmac_md5_final(pj_hmac_md5_context *hctx,
pj_uint8_t digest[16]);
PJ_DECL(void)
pj_hmac_md5_final(pj_hmac_md5_context* hctx, pj_uint8_t digest[16]);
/**
* @}
@ -103,7 +101,4 @@ PJ_DECL(void) pj_hmac_md5_final(pj_hmac_md5_context *hctx,
PJ_END_DECL
#endif /* __PJLIB_UTIL_HMAC_MD5_H__ */
#endif /* __PJLIB_UTIL_HMAC_MD5_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_HMAC_SHA1_H__
#define __PJLIB_UTIL_HMAC_SHA1_H__
@ -35,7 +34,7 @@ PJ_BEGIN_DECL
* @ingroup PJLIB_UTIL_ENCRYPTION
* @{
*
* This module contains the implementation of HMAC: Keyed-Hashing
* This module contains the implementation of HMAC: Keyed-Hashing
* for Message Authentication, as described in RFC 2104.
*/
@ -44,11 +43,10 @@ PJ_BEGIN_DECL
*/
typedef struct pj_hmac_sha1_context
{
pj_sha1_context context; /**< SHA1 context */
pj_uint8_t k_opad[64]; /**< opad xor-ed with key */
pj_sha1_context context; /**< SHA1 context */
pj_uint8_t k_opad[64]; /**< opad xor-ed with key */
} pj_hmac_sha1_context;
/**
* Calculate HMAC-SHA1 digest for the specified input and key with this
* single function call.
@ -59,10 +57,9 @@ typedef struct pj_hmac_sha1_context
* @param key_len Length of the authentication key.
* @param digest Buffer to be filled with HMAC SHA1 digest.
*/
PJ_DECL(void) pj_hmac_sha1(const pj_uint8_t *input, unsigned input_len,
const pj_uint8_t *key, unsigned key_len,
pj_uint8_t digest[20]);
PJ_DECL(void)
pj_hmac_sha1(const pj_uint8_t* input, unsigned input_len, const pj_uint8_t* key,
unsigned key_len, pj_uint8_t digest[20]);
/**
* Initiate HMAC-SHA1 context for incremental hashing.
@ -71,8 +68,9 @@ PJ_DECL(void) pj_hmac_sha1(const pj_uint8_t *input, unsigned input_len,
* @param key Pointer to the authentication key.
* @param key_len Length of the authentication key.
*/
PJ_DECL(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx,
const pj_uint8_t *key, unsigned key_len);
PJ_DECL(void)
pj_hmac_sha1_init(pj_hmac_sha1_context* hctx, const pj_uint8_t* key,
unsigned key_len);
/**
* Append string to the message.
@ -81,19 +79,18 @@ PJ_DECL(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx,
* @param input Pointer to the input stream.
* @param input_len Length of input stream in bytes.
*/
PJ_DECL(void) pj_hmac_sha1_update(pj_hmac_sha1_context *hctx,
const pj_uint8_t *input,
unsigned input_len);
PJ_DECL(void)
pj_hmac_sha1_update(pj_hmac_sha1_context* hctx, const pj_uint8_t* input,
unsigned input_len);
/**
* Finish the message and return the digest.
* Finish the message and return the digest.
*
* @param hctx HMAC-SHA1 context.
* @param digest Buffer to be filled with HMAC SHA1 digest.
*/
PJ_DECL(void) pj_hmac_sha1_final(pj_hmac_sha1_context *hctx,
pj_uint8_t digest[20]);
PJ_DECL(void)
pj_hmac_sha1_final(pj_hmac_sha1_context* hctx, pj_uint8_t digest[20]);
/**
* @}
@ -101,7 +98,4 @@ PJ_DECL(void) pj_hmac_sha1_final(pj_hmac_sha1_context *hctx,
PJ_END_DECL
#endif /* __PJLIB_UTIL_HMAC_SHA1_H__ */
#endif /* __PJLIB_UTIL_HMAC_SHA1_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
@ -14,7 +13,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_HTTP_CLIENT_H__
#define __PJLIB_UTIL_HTTP_CLIENT_H__
@ -33,7 +32,7 @@ PJ_BEGIN_DECL
* @ingroup PJ_PROTOCOLS
* @{
* This contains a simple HTTP client implementation.
* Some known limitations:
* Some known limitations:
* - Does not support chunked Transfer-Encoding.
*/
@ -53,8 +52,8 @@ typedef struct pj_http_req pj_http_req;
*/
typedef struct pj_http_header_elmt
{
pj_str_t name; /**< Header name */
pj_str_t value; /**< Header value */
pj_str_t name; /**< Header name */
pj_str_t value; /**< Header value */
} pj_http_header_elmt;
/**
@ -65,7 +64,7 @@ typedef struct pj_http_header_elmt
typedef struct pj_http_headers
{
/**< Number of header fields */
unsigned count;
unsigned count;
/** Header elements/fields */
pj_http_header_elmt header[PJ_HTTP_HEADER_SIZE];
@ -83,7 +82,7 @@ typedef struct pj_http_auth_cred
*
* Default is empty.
*/
pj_str_t scheme;
pj_str_t scheme;
/**
* Specify specific authentication realm to be responded. If this field
@ -92,14 +91,14 @@ typedef struct pj_http_auth_cred
*
* Default is empty.
*/
pj_str_t realm;
pj_str_t realm;
/**
* Specify authentication username.
*
* Default is empty.
*/
pj_str_t username;
pj_str_t username;
/**
* The type of password in \a data field. Currently only 0 is
@ -107,7 +106,7 @@ typedef struct pj_http_auth_cred
*
* Default is 0.
*/
unsigned data_type;
unsigned data_type;
/**
* Specify authentication password. The encoding of the password depends
@ -115,78 +114,77 @@ typedef struct pj_http_auth_cred
*
* Default is empty.
*/
pj_str_t data;
pj_str_t data;
} pj_http_auth_cred;
/**
* Parameters that can be given during http request creation. Application
* must initialize this structure with #pj_http_req_param_default().
*/
typedef struct pj_http_req_param
typedef struct pj_http_req_param
{
/**
/**
* The address family of the URL.
* Default is pj_AF_INET().
*/
int addr_family;
int addr_family;
/**
/**
* The HTTP request method.
* Default is GET.
*/
pj_str_t method;
pj_str_t method;
/**
/**
* The HTTP protocol version ("1.0" or "1.1").
* Default is "1.0".
*/
pj_str_t version;
pj_str_t version;
/**
/**
* HTTP request operation timeout.
* Default is PJ_HTTP_DEFAULT_TIMEOUT.
*/
pj_time_val timeout;
pj_time_val timeout;
/**
/**
* User-defined data.
* Default is NULL.
*/
void *user_data;
void* user_data;
/**
/**
* HTTP request headers.
* Default is empty.
*/
pj_http_headers headers;
/**
* This structure describes the http request body. If application
* specifies the data to send, the data must remain valid until
* the HTTP request is sent. Alternatively, application can choose
* to specify total_size as the total data size to send instead
* while leaving the data NULL (and its size 0). In this case,
* HTTP request will then call on_send_data() callback once it is
* ready to send the request body. This will be useful if
* application does not wish to load the data into the buffer at
* once.
*
* Default is empty.
*/
* This structure describes the http request body. If application
* specifies the data to send, the data must remain valid until
* the HTTP request is sent. Alternatively, application can choose
* to specify total_size as the total data size to send instead
* while leaving the data NULL (and its size 0). In this case,
* HTTP request will then call on_send_data() callback once it is
* ready to send the request body. This will be useful if
* application does not wish to load the data into the buffer at
* once.
*
* Default is empty.
*/
struct pj_http_reqdata
{
void *data; /**< Request body data */
pj_size_t size; /**< Request body size */
pj_size_t total_size; /**< If total_size > 0, data */
/**< will be provided later */
void* data; /**< Request body data */
pj_size_t size; /**< Request body size */
pj_size_t total_size; /**< If total_size > 0, data */
/**< will be provided later */
} reqdata;
/**
* Authentication credential needed to respond to 401/407 response.
*/
pj_http_auth_cred auth_cred;
pj_http_auth_cred auth_cred;
/**
* Optional source port range to use when binding the socket.
@ -199,7 +197,7 @@ typedef struct pj_http_req_param
*
* Default is 0 (The OS will select the source port automatically)
*/
pj_uint16_t source_port_range_start;
pj_uint16_t source_port_range_start;
/**
* Optional source port range to use when binding.
@ -207,7 +205,7 @@ typedef struct pj_http_req_param
*
* Default is 0 (The OS will select the source port automatically))
*/
pj_uint16_t source_port_range_size;
pj_uint16_t source_port_range_size;
/**
* Max number of retries if binding to a port fails.
@ -216,7 +214,7 @@ typedef struct pj_http_req_param
*
* Default is 3
*/
pj_uint16_t max_retries;
pj_uint16_t max_retries;
} pj_http_req_param;
@ -225,14 +223,14 @@ typedef struct pj_http_req_param
*/
typedef struct pj_http_auth_chal
{
pj_str_t scheme; /**< Auth scheme. */
pj_str_t realm; /**< Realm for the challenge. */
pj_str_t domain; /**< Domain. */
pj_str_t nonce; /**< Nonce challenge. */
pj_str_t opaque; /**< Opaque value. */
int stale; /**< Stale parameter. */
pj_str_t algorithm; /**< Algorithm parameter. */
pj_str_t qop; /**< Quality of protection. */
pj_str_t scheme; /**< Auth scheme. */
pj_str_t realm; /**< Realm for the challenge. */
pj_str_t domain; /**< Domain. */
pj_str_t nonce; /**< Nonce challenge. */
pj_str_t opaque; /**< Opaque value. */
int stale; /**< Stale parameter. */
pj_str_t algorithm; /**< Algorithm parameter. */
pj_str_t qop; /**< Quality of protection. */
} pj_http_auth_chal;
/**
@ -240,16 +238,16 @@ typedef struct pj_http_auth_chal
*/
typedef struct pj_http_resp
{
pj_str_t version; /**< HTTP version of the server */
pj_uint16_t status_code; /**< Status code of the request */
pj_str_t reason; /**< Reason phrase */
pj_http_headers headers; /**< Response headers */
pj_http_auth_chal auth_chal; /**< Parsed WWW-Authenticate header, if
any. */
pj_int32_t content_length; /**< The value of content-length header
field. -1 if not specified. */
void *data; /**< Data received */
pj_size_t size; /**< Data size */
pj_str_t version; /**< HTTP version of the server */
pj_uint16_t status_code; /**< Status code of the request */
pj_str_t reason; /**< Reason phrase */
pj_http_headers headers; /**< Response headers */
pj_http_auth_chal auth_chal; /**< Parsed WWW-Authenticate header, if
any. */
pj_int32_t content_length; /**< The value of content-length header
field. -1 if not specified. */
void* data; /**< Data received */
pj_size_t size; /**< Data size */
} pj_http_resp;
/**
@ -257,12 +255,12 @@ typedef struct pj_http_resp
*/
typedef struct pj_http_url
{
pj_str_t username; /**< Username part */
pj_str_t passwd; /**< Password part */
pj_str_t protocol; /**< Protocol used */
pj_str_t host; /**< Host name */
pj_uint16_t port; /**< Port number */
pj_str_t path; /**< Path */
pj_str_t username; /**< Username part */
pj_str_t passwd; /**< Password part */
pj_str_t protocol; /**< Protocol used */
pj_str_t host; /**< Host name */
pj_uint16_t port; /**< Port number */
pj_str_t path; /**< Path */
} pj_http_url;
/**
@ -271,18 +269,18 @@ typedef struct pj_http_url
typedef struct pj_http_req_callback
{
/**
* This callback is called when a complete HTTP response header
* This callback is called when a complete HTTP response header
* is received.
*
* @param http_req The http request.
* @param resp The response of the request.
*/
void (*on_response)(pj_http_req *http_req, const pj_http_resp *resp);
void (*on_response)(pj_http_req* http_req, const pj_http_resp* resp);
/**
* This callback is called when the HTTP request is ready to send
* its request body. Application may wish to use this callback if
* it wishes to load the data at a later time or if it does not
* it wishes to load the data at a later time or if it does not
* wish to load the whole data into memory. In order for this
* callback to be called, application MUST set http_req_param.total_size
* to a value greater than 0.
@ -290,29 +288,27 @@ typedef struct pj_http_req_callback
* @param http_req The http request.
* @param data Pointer to the data that will be sent. Application
* must set the pointer to the current data chunk/segment
* to be sent. Data must remain valid until the next
* to be sent. Data must remain valid until the next
* on_send_data() callback or for the last segment,
* until it is sent.
* @param size Pointer to the data size that will be sent.
*/
void (*on_send_data)(pj_http_req *http_req,
void **data, pj_size_t *size);
void (*on_send_data)(pj_http_req* http_req, void** data, pj_size_t* size);
/**
* This callback is called when a segment of response body data
* arrives. If this callback is specified (i.e. not NULL), the
* on_complete() callback will be called with zero-length data
* (within the response parameter), hence the application must
* store and manage its own data buffer, otherwise the
* on_complete() callback will be called with the response
* parameter containing the complete data.
*
* (within the response parameter), hence the application must
* store and manage its own data buffer, otherwise the
* on_complete() callback will be called with the response
* parameter containing the complete data.
*
* @param http_req The http request.
* @param data The buffer containing the data.
* @param size The length of data in the buffer.
*/
void (*on_data_read)(pj_http_req *http_req,
void *data, pj_size_t size);
void (*on_data_read)(pj_http_req* http_req, void* data, pj_size_t size);
/**
* This callback is called when the HTTP request is completed.
@ -323,36 +319,34 @@ typedef struct pj_http_req_callback
* as long as pj_http_req is not destroyed and application does
* not start a new request.
*
* If no longer required, application may choose to destroy
* pj_http_req immediately by calling #pj_http_req_destroy() inside
* If no longer required, application may choose to destroy
* pj_http_req immediately by calling #pj_http_req_destroy() inside
* the callback.
*
* @param http_req The http request.
* @param status The status of the request operation. PJ_SUCCESS
* if the operation completed successfully
* (connection-wise). To check the server's
* status-code response to the HTTP request,
* (connection-wise). To check the server's
* status-code response to the HTTP request,
* application should check resp->status_code instead.
* @param resp The response of the corresponding request. If
* the status argument is non-PJ_SUCCESS, this
* @param resp The response of the corresponding request. If
* the status argument is non-PJ_SUCCESS, this
* argument will be set to NULL.
*/
void (*on_complete)(pj_http_req *http_req,
pj_status_t status,
const pj_http_resp *resp);
void (*on_complete)(pj_http_req* http_req, pj_status_t status,
const pj_http_resp* resp);
} pj_http_req_callback;
/**
* Initialize the http request parameters with the default values.
*
* @param param The parameter to be initialized.
*/
PJ_DECL(void) pj_http_req_param_default(pj_http_req_param *param);
PJ_DECL(void) pj_http_req_param_default(pj_http_req_param* param);
/**
* Add a header element/field. Application MUST make sure that
* Add a header element/field. Application MUST make sure that
* name and val pointer remains valid until the HTTP request is sent.
*
* @param headers The headers.
@ -362,13 +356,13 @@ PJ_DECL(void) pj_http_req_param_default(pj_http_req_param *param);
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_http_headers_add_elmt(pj_http_headers *headers,
pj_str_t *name,
pj_str_t *val);
PJ_DECL(pj_status_t)
pj_http_headers_add_elmt(pj_http_headers* headers, pj_str_t* name,
pj_str_t* val);
/**
/**
* The same as #pj_http_headers_add_elmt() with char * as
* its parameters. Application MUST make sure that name and val pointer
* its parameters. Application MUST make sure that name and val pointer
* remains valid until the HTTP request is sent.
*
* @param headers The headers.
@ -378,8 +372,8 @@ PJ_DECL(pj_status_t) pj_http_headers_add_elmt(pj_http_headers *headers,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_http_headers_add_elmt2(pj_http_headers *headers,
char *name, char *val);
PJ_DECL(pj_status_t)
pj_http_headers_add_elmt2(pj_http_headers* headers, char* name, char* val);
/**
* Parse a http URL into its components.
@ -390,8 +384,8 @@ PJ_DECL(pj_status_t) pj_http_headers_add_elmt2(pj_http_headers *headers,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_http_req_parse_url(const pj_str_t *url,
pj_http_url *hurl);
PJ_DECL(pj_status_t)
pj_http_req_parse_url(const pj_str_t* url, pj_http_url* hurl);
/**
* Create the HTTP request.
@ -401,7 +395,7 @@ PJ_DECL(pj_status_t) pj_http_req_parse_url(const pj_str_t *url,
* @param url HTTP URL request.
* @param timer The timer to use.
* @param ioqueue The ioqueue to use.
* @param param Optional parameters. When this parameter is not
* @param param Optional parameters. When this parameter is not
* specifed (NULL), the default values will be used.
* @param hcb Pointer to structure containing application
* callbacks.
@ -410,24 +404,21 @@ PJ_DECL(pj_status_t) pj_http_req_parse_url(const pj_str_t *url,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_http_req_create(pj_pool_t *pool,
const pj_str_t *url,
pj_timer_heap_t *timer,
pj_ioqueue_t *ioqueue,
const pj_http_req_param *param,
const pj_http_req_callback *hcb,
pj_http_req **http_req);
PJ_DECL(pj_status_t)
pj_http_req_create(pj_pool_t* pool, const pj_str_t* url, pj_timer_heap_t* timer,
pj_ioqueue_t* ioqueue, const pj_http_req_param* param,
const pj_http_req_callback* hcb, pj_http_req** http_req);
/**
* Set the timeout of the HTTP request operation. Note that if the
* HTTP request is currently running, the timeout will only affect
* Set the timeout of the HTTP request operation. Note that if the
* HTTP request is currently running, the timeout will only affect
* subsequent request operations.
*
* @param http_req The http request.
* @param timeout Timeout value for HTTP request operation.
*/
PJ_DECL(void) pj_http_req_set_timeout(pj_http_req *http_req,
const pj_time_val* timeout);
PJ_DECL(void)
pj_http_req_set_timeout(pj_http_req* http_req, const pj_time_val* timeout);
/**
* Starts an asynchronous HTTP request to the URL specified.
@ -438,22 +429,22 @@ PJ_DECL(void) pj_http_req_set_timeout(pj_http_req *http_req,
* - PJ_SUCCESS if success
* - non-zero which indicates the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_http_req_start(pj_http_req *http_req);
PJ_DECL(pj_status_t) pj_http_req_start(pj_http_req* http_req);
/**
* Cancel the asynchronous HTTP request.
* Cancel the asynchronous HTTP request.
*
* @param http_req The http request.
* @param notify If non-zero, the on_complete() callback will be
* called with status PJ_ECANCELLED to notify that
* @param notify If non-zero, the on_complete() callback will be
* called with status PJ_ECANCELLED to notify that
* the query has been cancelled.
*
* @return
* - PJ_SUCCESS if success
* - non-zero which indicates the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_http_req_cancel(pj_http_req *http_req,
pj_bool_t notify);
PJ_DECL(pj_status_t)
pj_http_req_cancel(pj_http_req* http_req, pj_bool_t notify);
/**
* Destroy the http request.
@ -462,7 +453,7 @@ PJ_DECL(pj_status_t) pj_http_req_cancel(pj_http_req *http_req,
*
* @return PJ_SUCCESS if success.
*/
PJ_DECL(pj_status_t) pj_http_req_destroy(pj_http_req *http_req);
PJ_DECL(pj_status_t) pj_http_req_destroy(pj_http_req* http_req);
/**
* Find out whether the http request is running.
@ -472,7 +463,7 @@ PJ_DECL(pj_status_t) pj_http_req_destroy(pj_http_req *http_req);
* @return PJ_TRUE if a request is pending, or
* PJ_FALSE if idle
*/
PJ_DECL(pj_bool_t) pj_http_req_is_running(const pj_http_req *http_req);
PJ_DECL(pj_bool_t) pj_http_req_is_running(const pj_http_req* http_req);
/**
* Retrieve the user data previously associated with this http
@ -482,7 +473,7 @@ PJ_DECL(pj_bool_t) pj_http_req_is_running(const pj_http_req *http_req);
*
* @return The user data.
*/
PJ_DECL(void *) pj_http_req_get_user_data(pj_http_req *http_req);
PJ_DECL(void*) pj_http_req_get_user_data(pj_http_req* http_req);
/**
* @}
@ -490,5 +481,4 @@ PJ_DECL(void *) pj_http_req_get_user_data(pj_http_req *http_req);
PJ_END_DECL
#endif /* __PJLIB_UTIL_HTTP_CLIENT_H__ */
#endif /* __PJLIB_UTIL_HTTP_CLIENT_H__ */

View File

@ -1,4 +1,3 @@
/* $Id$ */
/*
* Copyright (C) 2013 Teluu Inc. (http://www.teluu.com)
*
@ -19,7 +18,6 @@
#ifndef __PJLIB_UTIL_JSON_H__
#define __PJLIB_UTIL_JSON_H__
/**
* @file json.h
* @brief PJLIB JSON Implementation
@ -44,12 +42,12 @@ PJ_BEGIN_DECL
*/
typedef enum pj_json_val_type
{
PJ_JSON_VAL_NULL, /**< Null value (null) */
PJ_JSON_VAL_BOOL, /**< Boolean value (true, false) */
PJ_JSON_VAL_NUMBER, /**< Numeric (float or fixed point) */
PJ_JSON_VAL_STRING, /**< Literal string value. */
PJ_JSON_VAL_ARRAY, /**< Array */
PJ_JSON_VAL_OBJ /**< Object. */
PJ_JSON_VAL_NULL, /**< Null value (null) */
PJ_JSON_VAL_BOOL, /**< Boolean value (true, false) */
PJ_JSON_VAL_NUMBER, /**< Numeric (float or fixed point) */
PJ_JSON_VAL_STRING, /**< Literal string value. */
PJ_JSON_VAL_ARRAY, /**< Array */
PJ_JSON_VAL_OBJ /**< Object. */
} pj_json_val_type;
/* Forward declaration for JSON element */
@ -73,15 +71,15 @@ typedef struct pj_json_list
struct pj_json_elem
{
PJ_DECL_LIST_MEMBER(pj_json_elem);
pj_str_t name; /**< ELement name. */
pj_json_val_type type; /**< Element type. */
pj_str_t name; /**< ELement name. */
pj_json_val_type type; /**< Element type. */
union
{
pj_bool_t is_true; /**< Boolean value. */
float num; /**< Number value. */
pj_str_t str; /**< String value. */
pj_json_list children; /**< Object and array children */
} value; /**< Element value. */
pj_bool_t is_true; /**< Boolean value. */
float num; /**< Number value. */
pj_str_t str; /**< String value. */
pj_json_list children; /**< Object and array children */
} value; /**< Element value. */
};
/**
@ -90,9 +88,9 @@ struct pj_json_elem
*/
typedef struct pj_json_err_info
{
unsigned line; /**< Line location of the error */
unsigned col; /**< Column location of the error */
int err_char; /**< The offending character. */
unsigned line; /**< Line location of the error */
unsigned col; /**< Column location of the error */
int err_char; /**< The offending character. */
} pj_json_err_info;
/**
@ -106,9 +104,8 @@ typedef struct pj_json_err_info
* stop the pj_json_writef() function and this error
* will be returned to caller.
*/
typedef pj_status_t (*pj_json_writer)(const char *s,
unsigned size,
void *user_data);
typedef pj_status_t (*pj_json_writer)(const char* s, unsigned size,
void* user_data);
/**
* Initialize null element.
@ -116,7 +113,7 @@ typedef pj_status_t (*pj_json_writer)(const char *s,
* @param el The element.
* @param name Name to be given to the element, or NULL.
*/
PJ_DECL(void) pj_json_elem_null(pj_json_elem *el, pj_str_t *name);
PJ_DECL(void) pj_json_elem_null(pj_json_elem* el, pj_str_t* name);
/**
* Initialize boolean element with the specified value.
@ -125,8 +122,8 @@ PJ_DECL(void) pj_json_elem_null(pj_json_elem *el, pj_str_t *name);
* @param name Name to be given to the element, or NULL.
* @param val The value.
*/
PJ_DECL(void) pj_json_elem_bool(pj_json_elem *el, pj_str_t *name,
pj_bool_t val);
PJ_DECL(void)
pj_json_elem_bool(pj_json_elem* el, pj_str_t* name, pj_bool_t val);
/**
* Initialize number element with the specified value.
@ -135,8 +132,7 @@ PJ_DECL(void) pj_json_elem_bool(pj_json_elem *el, pj_str_t *name,
* @param name Name to be given to the element, or NULL.
* @param val The value.
*/
PJ_DECL(void) pj_json_elem_number(pj_json_elem *el, pj_str_t *name,
float val);
PJ_DECL(void) pj_json_elem_number(pj_json_elem* el, pj_str_t* name, float val);
/**
* Initialize string element with the specified value.
@ -145,8 +141,8 @@ PJ_DECL(void) pj_json_elem_number(pj_json_elem *el, pj_str_t *name,
* @param name Name to be given to the element, or NULL.
* @param val The value.
*/
PJ_DECL(void) pj_json_elem_string(pj_json_elem *el, pj_str_t *name,
pj_str_t *val);
PJ_DECL(void)
pj_json_elem_string(pj_json_elem* el, pj_str_t* name, pj_str_t* val);
/**
* Initialize element as an empty array
@ -154,7 +150,7 @@ PJ_DECL(void) pj_json_elem_string(pj_json_elem *el, pj_str_t *name,
* @param el The element.
* @param name Name to be given to the element, or NULL.
*/
PJ_DECL(void) pj_json_elem_array(pj_json_elem *el, pj_str_t *name);
PJ_DECL(void) pj_json_elem_array(pj_json_elem* el, pj_str_t* name);
/**
* Initialize element as an empty object
@ -162,7 +158,7 @@ PJ_DECL(void) pj_json_elem_array(pj_json_elem *el, pj_str_t *name);
* @param el The element.
* @param name Name to be given to the element, or NULL.
*/
PJ_DECL(void) pj_json_elem_obj(pj_json_elem *el, pj_str_t *name);
PJ_DECL(void) pj_json_elem_obj(pj_json_elem* el, pj_str_t* name);
/**
* Add an element to an object or array.
@ -170,7 +166,7 @@ PJ_DECL(void) pj_json_elem_obj(pj_json_elem *el, pj_str_t *name);
* @param el The object or array element.
* @param child Element to be added to the object or array.
*/
PJ_DECL(void) pj_json_elem_add(pj_json_elem *el, pj_json_elem *child);
PJ_DECL(void) pj_json_elem_add(pj_json_elem* el, pj_json_elem* child);
/**
* Parse a JSON document in the buffer. The buffer MUST be NULL terminated,
@ -184,10 +180,9 @@ PJ_DECL(void) pj_json_elem_add(pj_json_elem *el, pj_json_elem *child);
*
* @return The root element from the document.
*/
PJ_DECL(pj_json_elem*) pj_json_parse(pj_pool_t *pool,
char *buffer,
unsigned *size,
pj_json_err_info *err_info);
PJ_DECL(pj_json_elem*)
pj_json_parse(pj_pool_t* pool, char* buffer, unsigned* size,
pj_json_err_info* err_info);
/**
* Write the specified element to the string buffer.
@ -200,8 +195,8 @@ PJ_DECL(pj_json_elem*) pj_json_parse(pj_pool_t *pool,
*
* @return PJ_SUCCESS on success or the appropriate error.
*/
PJ_DECL(pj_status_t) pj_json_write(const pj_json_elem *elem,
char *buffer, unsigned *size);
PJ_DECL(pj_status_t)
pj_json_write(const pj_json_elem* elem, char* buffer, unsigned* size);
/**
* Incrementally write the element to arbitrary medium using the specified
@ -215,9 +210,9 @@ PJ_DECL(pj_status_t) pj_json_write(const pj_json_elem *elem,
*
* @return PJ_SUCCESS on success or the appropriate error.
*/
PJ_DECL(pj_status_t) pj_json_writef(const pj_json_elem *elem,
pj_json_writer writer,
void *user_data);
PJ_DECL(pj_status_t)
pj_json_writef(const pj_json_elem* elem, pj_json_writer writer,
void* user_data);
/**
* @}
@ -225,4 +220,4 @@ PJ_DECL(pj_status_t) pj_json_writef(const pj_json_elem *elem,
PJ_END_DECL
#endif /* __PJLIB_UTIL_JSON_H__ */
#endif /* __PJLIB_UTIL_JSON_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_MD5_H__
#define __PJLIB_UTIL_MD5_H__
@ -35,34 +34,32 @@ PJ_BEGIN_DECL
* @{
*/
/** MD5 context. */
typedef struct pj_md5_context
{
pj_uint32_t buf[4]; /**< buf */
pj_uint32_t bits[2]; /**< bits */
pj_uint8_t in[64]; /**< in */
pj_uint32_t buf[4]; /**< buf */
pj_uint32_t bits[2]; /**< bits */
pj_uint8_t in[64]; /**< in */
} pj_md5_context;
/** Initialize the algorithm.
/** Initialize the algorithm.
* @param pms MD5 context.
*/
PJ_DECL(void) pj_md5_init(pj_md5_context *pms);
PJ_DECL(void) pj_md5_init(pj_md5_context* pms);
/** Append a string to the message.
/** Append a string to the message.
* @param pms MD5 context.
* @param data Data.
* @param nbytes Length of data.
*/
PJ_DECL(void) pj_md5_update( pj_md5_context *pms,
const pj_uint8_t *data, unsigned nbytes);
PJ_DECL(void)
pj_md5_update(pj_md5_context* pms, const pj_uint8_t* data, unsigned nbytes);
/** Finish the message and return the digest.
/** Finish the message and return the digest.
* @param pms MD5 context.
* @param digest 16 byte digest.
*/
PJ_DECL(void) pj_md5_final(pj_md5_context *pms, pj_uint8_t digest[16]);
PJ_DECL(void) pj_md5_final(pj_md5_context* pms, pj_uint8_t digest[16]);
/**
* @}
@ -70,5 +67,4 @@ PJ_DECL(void) pj_md5_final(pj_md5_context *pms, pj_uint8_t digest[16]);
PJ_END_DECL
#endif /* __PJLIB_UTIL_MD5_H__ */
#endif /* __PJLIB_UTIL_MD5_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_PCAP_H__
#define __PJLIB_UTIL_PCAP_H__
@ -44,35 +43,32 @@ PJ_BEGIN_DECL
typedef enum pj_pcap_link_type
{
/** Ethernet data link */
PJ_PCAP_LINK_TYPE_ETH = 1
PJ_PCAP_LINK_TYPE_ETH = 1
} pj_pcap_link_type;
/**
* Enumeration to describe supported protocol types.
*/
typedef enum pj_pcap_proto_type
{
/** UDP protocol */
PJ_PCAP_PROTO_TYPE_UDP = 17
PJ_PCAP_PROTO_TYPE_UDP = 17
} pj_pcap_proto_type;
/**
* This describes UDP header, which may optionally be returned in
* #pj_pcap_read_udp() function. All fields are in network byte order.
*/
typedef struct pj_pcap_udp_hdr
{
pj_uint16_t src_port; /**< Source port. */
pj_uint16_t dst_port; /**< Destination port */
pj_uint16_t len; /**< Length. */
pj_uint16_t csum; /**< Checksum. */
pj_uint16_t src_port; /**< Source port. */
pj_uint16_t dst_port; /**< Destination port */
pj_uint16_t len; /**< Length. */
pj_uint16_t csum; /**< Checksum. */
} pj_pcap_udp_hdr;
/**
* This structure describes the filter to be used when reading packets from
* a PCAP file. When a filter is configured, only packets matching all the
@ -83,55 +79,53 @@ typedef struct pj_pcap_filter
/**
* Select data link type, or zero to include any supported data links.
*/
pj_pcap_link_type link;
pj_pcap_link_type link;
/**
* Select protocol, or zero to include all supported protocols.
*/
pj_pcap_proto_type proto;
pj_pcap_proto_type proto;
/**
* Specify source IP address of the packets, or zero to include packets
* from any IP addresses. Note that IP address here must be in
* network byte order.
*/
pj_uint32_t ip_src;
pj_uint32_t ip_src;
/**
* Specify destination IP address of the packets, or zero to include packets
* destined to any IP addresses. Note that IP address here must be in
* network byte order.
*/
pj_uint32_t ip_dst;
pj_uint32_t ip_dst;
/**
* Specify source port of the packets, or zero to include packets with
* any source port number. Note that the port number must be in network
* byte order.
*/
pj_uint16_t src_port;
pj_uint16_t src_port;
/**
* Specify destination port of the packets, or zero to include packets with
* any destination port number. Note that the port number must be in network
* byte order.
*/
pj_uint16_t dst_port;
pj_uint16_t dst_port;
} pj_pcap_filter;
/** Opaque declaration for PCAP file */
typedef struct pj_pcap_file pj_pcap_file;
/**
* Initialize filter with default values. The default value is to allow
* any packets.
*
* @param filter Filter to be initialized.
*/
PJ_DECL(void) pj_pcap_filter_default(pj_pcap_filter *filter);
PJ_DECL(void) pj_pcap_filter_default(pj_pcap_filter* filter);
/**
* Open PCAP file.
@ -142,9 +136,8 @@ PJ_DECL(void) pj_pcap_filter_default(pj_pcap_filter *filter);
*
* @return PJ_SUCCESS if file can be opened successfully.
*/
PJ_DECL(pj_status_t) pj_pcap_open(pj_pool_t *pool,
const char *path,
pj_pcap_file **p_file);
PJ_DECL(pj_status_t)
pj_pcap_open(pj_pool_t* pool, const char* path, pj_pcap_file** p_file);
/**
* Close PCAP file.
@ -153,7 +146,7 @@ PJ_DECL(pj_status_t) pj_pcap_open(pj_pool_t *pool,
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_pcap_close(pj_pcap_file *file);
PJ_DECL(pj_status_t) pj_pcap_close(pj_pcap_file* file);
/**
* Configure filter for reading the file. When filter is configured,
@ -164,8 +157,8 @@ PJ_DECL(pj_status_t) pj_pcap_close(pj_pcap_file *file);
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_pcap_set_filter(pj_pcap_file *file,
const pj_pcap_filter *filter);
PJ_DECL(pj_status_t)
pj_pcap_set_filter(pj_pcap_file* file, const pj_pcap_filter* filter);
/**
* Read UDP payload from the next packet in the PCAP file. Optionally it
@ -180,11 +173,9 @@ PJ_DECL(pj_status_t) pj_pcap_set_filter(pj_pcap_file *file,
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_pcap_read_udp(pj_pcap_file *file,
pj_pcap_udp_hdr *udp_hdr,
pj_uint8_t *udp_payload,
pj_size_t *udp_payload_size);
PJ_DECL(pj_status_t)
pj_pcap_read_udp(pj_pcap_file* file, pj_pcap_udp_hdr* udp_hdr,
pj_uint8_t* udp_payload, pj_size_t* udp_payload_size);
/**
* @}
@ -192,5 +183,4 @@ PJ_DECL(pj_status_t) pj_pcap_read_udp(pj_pcap_file *file,
PJ_END_DECL
#endif /* __PJLIB_UTIL_PCAP_H__ */
#endif /* __PJLIB_UTIL_PCAP_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_RESOLVER_H__
#define __PJLIB_UTIL_RESOLVER_H__
@ -26,31 +25,30 @@
*/
#include <pjlib-util/dns.h>
PJ_BEGIN_DECL
/**
* @defgroup PJ_DNS_RESOLVER DNS Asynchronous/Caching Resolution Engine
* @ingroup PJ_DNS
* @{
*
* This module manages the host/server resolution by performing asynchronous
* DNS queries and caching the results in the cache. It uses PJLIB-UTIL
* DNS queries and caching the results in the cache. It uses PJLIB-UTIL
* low-level DNS parsing functions (see @ref PJ_DNS) and currently supports
* several types of DNS resource records such as A record (typical query with
* gethostbyname()) and SRV record.
*
* \section PJ_DNS_RESOLVER_FEATURES Features
*
* \subsection PJ_DNS_RESOLVER_FEATURES_ASYNC Asynchronous Query and Query Aggregation
*
* The DNS queries are performed asychronously, with timeout setting
* \subsection PJ_DNS_RESOLVER_FEATURES_ASYNC Asynchronous Query and Query
* Aggregation
*
* The DNS queries are performed asychronously, with timeout setting
* configured on per resolver instance basis. Application can issue multiple
* asynchronous queries simultaneously. Subsequent queries to the same resource
* (name and DNS resource type) while existing query is still pending will be
* merged into one query, so that only one DNS request packet is issued.
*
*
* \subsection PJ_DNS_RESOLVER_FEATURES_RETRANSMISSION Query Retransmission
*
* Asynchronous query will be retransmitted if no response is received
@ -62,18 +60,19 @@ PJ_BEGIN_DECL
*
* The resolver instance caches the results returned by nameservers, to
* enhance the performance by minimizing the message round-trip to the server.
* The TTL of the cached resposne is calculated from minimum TTL value found
* The TTL of the cached resposne is calculated from minimum TTL value found
* across all resource record (RR) TTL in the response and further more it can
* be limited to some preconfigured maximum TTL in the resolver.
* be limited to some preconfigured maximum TTL in the resolver.
*
* Response caching can be disabled by setting the maximum TTL value of the
* Response caching can be disabled by setting the maximum TTL value of the
* resolver to zero.
*
* \subsection PJ_DNS_RESOLVER_FEATURES_PARALLEL Parallel and Backup Name Servers
* \subsection PJ_DNS_RESOLVER_FEATURES_PARALLEL Parallel and Backup Name
* Servers
*
* When the resolver is configured with multiple nameservers, initially the
* queries will be issued to multiple name servers simultaneously to probe
* which servers are not active. Once the probing stage is done, subsequent
* which servers are not active. Once the probing stage is done, subsequent
* queries will be directed to only one ACTIVE server which provides the best
* response time.
*
@ -93,7 +92,7 @@ PJ_BEGIN_DECL
* - DNS NS record
* - DNS CNAME record
*
* For other types of record, application can parse the raw resource
* For other types of record, application can parse the raw resource
* record data (rdata) from the parsed DNS packet (#pj_dns_parsed_packet).
*
*
@ -102,22 +101,23 @@ PJ_BEGIN_DECL
* To use the resolver, application first creates the resolver instance by
* calling #pj_dns_resolver_create(). If application already has its own
* timer and ioqueue instances, it can instruct the resolver to use these
* instances so that application does not need to poll the resolver
* instances so that application does not need to poll the resolver
* periodically to process events. If application does not specify the
* timer and ioqueue instance for the resolver, an internal timer and
* ioqueue will be created by the resolver. And since the resolver does not
* create it's own thread, application MUST poll the resolver periodically
* by calling #pj_dns_resolver_handle_events() to allow events (network and
* by calling #pj_dns_resolver_handle_events() to allow events (network and
* timer) to be processed.
*
* Next, application MUST configure the nameservers to be used by the
* resolver, by calling #pj_dns_resolver_set_ns().
*
* Application performs asynchronous query by submitting the query with
* #pj_dns_resolver_start_query(). Once the query completes (either
* #pj_dns_resolver_start_query(). Once the query completes (either
* successfully or times out), the callback will be called.
*
* Application can cancel a pending query by calling #pj_dns_resolver_cancel_query().
* Application can cancel a pending query by calling
* #pj_dns_resolver_cancel_query().
*
* Resolver must be destroyed by calling #pj_dns_resolver_destroy() to
* release all resources back to the system.
@ -132,17 +132,17 @@ PJ_BEGIN_DECL
* entries. So the more unique names being queried by application, there more
* enties will be created in the response cache.
*
* Note that a single response entry will occupy about 600-700 bytes of
* Note that a single response entry will occupy about 600-700 bytes of
* pool memory (the PJ_DNS_RESOLVER_RES_BUF_SIZE value plus internal
* structure).
* structure).
*
* Application can work around this problem by doing one of these:
* - disable caching by setting PJ_DNS_RESOLVER_MAX_TTL and
* - disable caching by setting PJ_DNS_RESOLVER_MAX_TTL and
* PJ_DNS_RESOLVER_INVALID_TTL to zero.
* - periodically query #pj_dns_resolver_get_cached_count() and destroy-
* recreate the resolver to recycle the memory used by the resolver.
*
* Note that future improvement may solve this problem by introducing
* Note that future improvement may solve this problem by introducing
* expiration timer to the cached entries.
*
*
@ -157,8 +157,6 @@ PJ_BEGIN_DECL
* </A>
*/
/**
* Opaque data type for DNS resolver object.
*/
@ -179,26 +177,23 @@ typedef struct pj_dns_async_query pj_dns_async_query;
* @param response The response packet received from the server. This
* argument may be NULL when status is not PJ_SUCCESS.
*/
typedef void pj_dns_callback(void *user_data,
pj_status_t status,
pj_dns_parsed_packet *response);
typedef void pj_dns_callback(void* user_data, pj_status_t status,
pj_dns_parsed_packet* response);
/**
* This structure describes resolver settings.
*/
typedef struct pj_dns_settings
{
unsigned options; /**< Options flags. */
unsigned qretr_delay; /**< Query retransmit delay in msec. */
unsigned qretr_count; /**< Query maximum retransmission count. */
unsigned cache_max_ttl; /**< Maximum TTL for cached responses. If the
value is zero, caching is disabled. */
unsigned good_ns_ttl; /**< See #PJ_DNS_RESOLVER_GOOD_NS_TTL */
unsigned bad_ns_ttl; /**< See #PJ_DNS_RESOLVER_BAD_NS_TTL */
unsigned options; /**< Options flags. */
unsigned qretr_delay; /**< Query retransmit delay in msec. */
unsigned qretr_count; /**< Query maximum retransmission count. */
unsigned cache_max_ttl; /**< Maximum TTL for cached responses. If the
value is zero, caching is disabled. */
unsigned good_ns_ttl; /**< See #PJ_DNS_RESOLVER_GOOD_NS_TTL */
unsigned bad_ns_ttl; /**< See #PJ_DNS_RESOLVER_BAD_NS_TTL */
} pj_dns_settings;
/**
* This structure represents DNS A record, as the result of parsing
* DNS response packet using #pj_dns_parse_a_response().
@ -206,25 +201,24 @@ typedef struct pj_dns_settings
typedef struct pj_dns_a_record
{
/** The target name being queried. */
pj_str_t name;
pj_str_t name;
/** If target name corresponds to a CNAME entry, the alias contains
* the value of the CNAME entry, otherwise it will be empty.
*/
pj_str_t alias;
pj_str_t alias;
/** Number of IP addresses. */
unsigned addr_count;
unsigned addr_count;
/** IP addresses of the host found in the response */
pj_in_addr addr[PJ_DNS_MAX_IP_IN_A_REC];
pj_in_addr addr[PJ_DNS_MAX_IP_IN_A_REC];
/** Internal buffer for hostname and alias. */
char buf_[128];
char buf_[128];
} pj_dns_a_record;
/**
* This structure represents DNS address record, i.e: DNS A and DNS AAAA
* records, as the result of parsing DNS response packet using
@ -233,46 +227,45 @@ typedef struct pj_dns_a_record
typedef struct pj_dns_addr_record
{
/** The target name being queried. */
pj_str_t name;
pj_str_t name;
/** If target name corresponds to a CNAME entry, the alias contains
* the value of the CNAME entry, otherwise it will be empty.
*/
pj_str_t alias;
pj_str_t alias;
/** Number of IP addresses. */
unsigned addr_count;
unsigned addr_count;
/** IP addresses of the host found in the response */
struct {
struct
{
/** IP address family */
int af;
/** IP address family */
int af;
/** IP address */
union {
/** IPv4 address */
pj_in_addr v4;
/** IP address */
union
{
/** IPv4 address */
pj_in_addr v4;
/** IPv6 address */
pj_in6_addr v6;
} ip;
/** IPv6 address */
pj_in6_addr v6;
} ip;
} addr[PJ_DNS_MAX_IP_IN_A_REC];
/** Internal buffer for hostname and alias. */
char buf_[128];
char buf_[128];
} pj_dns_addr_record;
/**
* Set default values to the DNS settings.
*
* @param s The DNS settings to be initialized.
*/
PJ_DECL(void) pj_dns_settings_default(pj_dns_settings *s);
PJ_DECL(void) pj_dns_settings_default(pj_dns_settings* s);
/**
* Create DNS resolver instance. After the resolver is created, application
@ -283,7 +276,7 @@ PJ_DECL(void) pj_dns_settings_default(pj_dns_settings *s);
* periodically.
*
* @param pf Pool factory where the memory pool will be created from.
* @param name Optional resolver name to identify the instance in
* @param name Optional resolver name to identify the instance in
* the log.
* @param options Optional options, must be zero for now.
* @param timer Optional timer heap instance to be used by the resolver.
@ -298,13 +291,10 @@ PJ_DECL(void) pj_dns_settings_default(pj_dns_settings *s);
*
* @return PJ_SUCCESS on success, or the appropriate error code,
*/
PJ_DECL(pj_status_t) pj_dns_resolver_create(pj_pool_factory *pf,
const char *name,
unsigned options,
pj_timer_heap_t *timer,
pj_ioqueue_t *ioqueue,
pj_dns_resolver **p_resolver);
PJ_DECL(pj_status_t)
pj_dns_resolver_create(pj_pool_factory* pf, const char* name, unsigned options,
pj_timer_heap_t* timer, pj_ioqueue_t* ioqueue,
pj_dns_resolver** p_resolver);
/**
* Update the name servers for the DNS resolver. The name servers MUST be
@ -322,11 +312,9 @@ PJ_DECL(pj_status_t) pj_dns_resolver_create(pj_pool_factory *pf,
*
* @return PJ_SUCCESS on success, or the appropriate error code,
*/
PJ_DECL(pj_status_t) pj_dns_resolver_set_ns(pj_dns_resolver *resolver,
unsigned count,
const pj_str_t servers[],
const pj_uint16_t ports[]);
PJ_DECL(pj_status_t)
pj_dns_resolver_set_ns(pj_dns_resolver* resolver, unsigned count,
const pj_str_t servers[], const pj_uint16_t ports[]);
/**
* Get the resolver current settings.
@ -336,9 +324,8 @@ PJ_DECL(pj_status_t) pj_dns_resolver_set_ns(pj_dns_resolver *resolver,
*
* @return The query timeout setting, in seconds.
*/
PJ_DECL(pj_status_t) pj_dns_resolver_get_settings(pj_dns_resolver *resolver,
pj_dns_settings *st);
PJ_DECL(pj_status_t)
pj_dns_resolver_get_settings(pj_dns_resolver* resolver, pj_dns_settings* st);
/**
* Modify the resolver settings. Application should initialize the settings
@ -350,12 +337,12 @@ PJ_DECL(pj_status_t) pj_dns_resolver_get_settings(pj_dns_resolver *resolver,
*
* @return PJ_SUCCESS on success, or the appropriate error code,
*/
PJ_DECL(pj_status_t) pj_dns_resolver_set_settings(pj_dns_resolver *resolver,
const pj_dns_settings *st);
PJ_DECL(pj_status_t)
pj_dns_resolver_set_settings(pj_dns_resolver* resolver,
const pj_dns_settings* st);
/**
* Poll for events from the resolver. This function MUST be called
* Poll for events from the resolver. This function MUST be called
* periodically when the resolver is using it's own timer or ioqueue
* (in other words, when NULL is specified as either \a timer or
* \a ioqueue argument in #pj_dns_resolver_create()).
@ -365,9 +352,9 @@ PJ_DECL(pj_status_t) pj_dns_resolver_set_settings(pj_dns_resolver *resolver,
* argument is NULL, this function will wait forever
* until events occur.
*/
PJ_DECL(void) pj_dns_resolver_handle_events(pj_dns_resolver *resolver,
const pj_time_val *timeout);
PJ_DECL(void)
pj_dns_resolver_handle_events(pj_dns_resolver* resolver,
const pj_time_val* timeout);
/**
* Destroy DNS resolver instance.
@ -379,9 +366,8 @@ PJ_DECL(void) pj_dns_resolver_handle_events(pj_dns_resolver *resolver,
*
* @return PJ_SUCCESS on success, or the appropriate error code,
*/
PJ_DECL(pj_status_t) pj_dns_resolver_destroy(pj_dns_resolver *resolver,
pj_bool_t notify);
PJ_DECL(pj_status_t)
pj_dns_resolver_destroy(pj_dns_resolver* resolver, pj_bool_t notify);
/**
* Create and start asynchronous DNS query for a single resource. Depending
@ -393,7 +379,7 @@ PJ_DECL(pj_status_t) pj_dns_resolver_destroy(pj_dns_resolver *resolver,
* completes. If \a p_query argument is not NULL, it will be filled with
* the asynchronous query object.
*
* If response is available in the cache, the callback will be called
* If response is available in the cache, the callback will be called
* immediately before this function returns. In this case, if \a p_query
* argument is not NULL, the value will be set to NULL since no new query
* is started.
@ -410,17 +396,14 @@ PJ_DECL(pj_status_t) pj_dns_resolver_destroy(pj_dns_resolver *resolver,
* was started. If this pointer is specified, a NULL may
* be returned if response cache is available immediately.
*
* @return PJ_SUCCESS if either an asynchronous query has been
* @return PJ_SUCCESS if either an asynchronous query has been
* started successfully or response cache is available and
* the user callback has been called.
*/
PJ_DECL(pj_status_t) pj_dns_resolver_start_query(pj_dns_resolver *resolver,
const pj_str_t *name,
int type,
unsigned options,
pj_dns_callback *cb,
void *user_data,
pj_dns_async_query **p_query);
PJ_DECL(pj_status_t)
pj_dns_resolver_start_query(pj_dns_resolver* resolver, const pj_str_t* name,
int type, unsigned options, pj_dns_callback* cb,
void* user_data, pj_dns_async_query** p_query);
/**
* Cancel a pending query.
@ -431,11 +414,11 @@ PJ_DECL(pj_status_t) pj_dns_resolver_start_query(pj_dns_resolver *resolver,
*
* @return PJ_SUCCESS on success, or the appropriate error code,
*/
PJ_DECL(pj_status_t) pj_dns_resolver_cancel_query(pj_dns_async_query *query,
pj_bool_t notify);
PJ_DECL(pj_status_t)
pj_dns_resolver_cancel_query(pj_dns_async_query* query, pj_bool_t notify);
/**
* A utility function to parse a DNS response containing A records into
* A utility function to parse a DNS response containing A records into
* DNS A record.
*
* @param pkt The DNS response packet.
@ -444,12 +427,11 @@ PJ_DECL(pj_status_t) pj_dns_resolver_cancel_query(pj_dns_async_query *query,
*
* @return PJ_SUCCESS if response can be parsed successfully.
*/
PJ_DECL(pj_status_t) pj_dns_parse_a_response(const pj_dns_parsed_packet *pkt,
pj_dns_a_record *rec);
PJ_DECL(pj_status_t)
pj_dns_parse_a_response(const pj_dns_parsed_packet* pkt, pj_dns_a_record* rec);
/**
* A utility function to parse a DNS response containing AAAA records into
* A utility function to parse a DNS response containing AAAA records into
* DNS AAAA record.
*
* @param pkt The DNS response packet.
@ -458,10 +440,9 @@ PJ_DECL(pj_status_t) pj_dns_parse_a_response(const pj_dns_parsed_packet *pkt,
*
* @return PJ_SUCCESS if response can be parsed successfully.
*/
PJ_DECL(pj_status_t) pj_dns_parse_addr_response(
const pj_dns_parsed_packet *pkt,
pj_dns_addr_record *rec);
PJ_DECL(pj_status_t)
pj_dns_parse_addr_response(const pj_dns_parsed_packet* pkt,
pj_dns_addr_record* rec);
/**
* Put the specified DNS packet into DNS cache. This function is mainly used
@ -474,15 +455,15 @@ PJ_DECL(pj_status_t) pj_dns_parse_addr_response(
* @param resolver The resolver instance.
* @param pkt DNS packet to be added to the DNS cache. If the packet
* matches existing entry, it will update the entry.
* @param set_ttl If the value is PJ_FALSE, the entry will not expire
* @param set_ttl If the value is PJ_FALSE, the entry will not expire
* (so use with care). Otherwise cache expiration will be
* calculated based on the TTL of the answeres.
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_dns_resolver_add_entry(pj_dns_resolver *resolver,
const pj_dns_parsed_packet *pkt,
pj_bool_t set_ttl);
PJ_DECL(pj_status_t)
pj_dns_resolver_add_entry(pj_dns_resolver* resolver,
const pj_dns_parsed_packet* pkt, pj_bool_t set_ttl);
/**
* Get the total number of response in the response cache.
@ -492,8 +473,7 @@ PJ_DECL(pj_status_t) pj_dns_resolver_add_entry(pj_dns_resolver *resolver,
* @return Current number of entries being stored in the response
* cache.
*/
PJ_DECL(unsigned) pj_dns_resolver_get_cached_count(pj_dns_resolver *resolver);
PJ_DECL(unsigned) pj_dns_resolver_get_cached_count(pj_dns_resolver* resolver);
/**
* Dump resolver state to the log.
@ -501,9 +481,7 @@ PJ_DECL(unsigned) pj_dns_resolver_get_cached_count(pj_dns_resolver *resolver);
* @param resolver The resolver instance.
* @param detail Will print detailed entries.
*/
PJ_DECL(void) pj_dns_resolver_dump(pj_dns_resolver *resolver,
pj_bool_t detail);
PJ_DECL(void) pj_dns_resolver_dump(pj_dns_resolver* resolver, pj_bool_t detail);
/**
* @}
@ -511,6 +489,4 @@ PJ_DECL(void) pj_dns_resolver_dump(pj_dns_resolver *resolver,
PJ_END_DECL
#endif /* __PJLIB_UTIL_RESOLVER_H__ */
#endif /* __PJLIB_UTIL_RESOLVER_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_SCANNER_H__
#define __PJ_SCANNER_H__
@ -39,9 +38,9 @@ PJ_BEGIN_DECL
* @{
*/
#if defined(PJ_SCANNER_USE_BITWISE) && PJ_SCANNER_USE_BITWISE != 0
# include <pjlib-util/scanner_cis_bitwise.h>
# include <pjlib-util/scanner_cis_bitwise.h>
#else
# include <pjlib-util/scanner_cis_uint.h>
# include <pjlib-util/scanner_cis_uint.h>
#endif
/**
@ -49,7 +48,7 @@ PJ_BEGIN_DECL
*
* @param cs_buf The scanner character specification.
*/
PJ_DECL(void) pj_cis_buf_init(pj_cis_buf_t *cs_buf);
PJ_DECL(void) pj_cis_buf_init(pj_cis_buf_t* cs_buf);
/**
* Create a new input specification.
@ -61,7 +60,7 @@ PJ_DECL(void) pj_cis_buf_init(pj_cis_buf_t *cs_buf);
* created, or PJ_ETOOMANY if there are already too many
* specifications in the buffer.
*/
PJ_DECL(pj_status_t) pj_cis_init(pj_cis_buf_t *cs_buf, pj_cis_t *cis);
PJ_DECL(pj_status_t) pj_cis_init(pj_cis_buf_t* cs_buf, pj_cis_t* cis);
/**
* Create a new input specification based on an existing specification.
@ -74,31 +73,31 @@ PJ_DECL(pj_status_t) pj_cis_init(pj_cis_buf_t *cs_buf, pj_cis_t *cis);
* created, or PJ_ETOOMANY if there are already too many
* specifications in the buffer.
*/
PJ_DECL(pj_status_t) pj_cis_dup(pj_cis_t *new_cis, pj_cis_t *existing);
PJ_DECL(pj_status_t) pj_cis_dup(pj_cis_t* new_cis, pj_cis_t* existing);
/**
* Add the characters in the specified range '[cstart, cend)' to the
* Add the characters in the specified range '[cstart, cend)' to the
* specification (the last character itself ('cend') is not added).
*
* @param cis The scanner character specification.
* @param cstart The first character in the range.
* @param cend The next character after the last character in the range.
*/
PJ_DECL(void) pj_cis_add_range( pj_cis_t *cis, int cstart, int cend);
PJ_DECL(void) pj_cis_add_range(pj_cis_t* cis, int cstart, int cend);
/**
* Add alphabetic characters to the specification.
*
* @param cis The scanner character specification.
*/
PJ_DECL(void) pj_cis_add_alpha( pj_cis_t *cis);
PJ_DECL(void) pj_cis_add_alpha(pj_cis_t* cis);
/**
* Add numeric characters to the specification.
*
* @param cis The scanner character specification.
*/
PJ_DECL(void) pj_cis_add_num( pj_cis_t *cis);
PJ_DECL(void) pj_cis_add_num(pj_cis_t* cis);
/**
* Add the characters in the string to the specification.
@ -106,7 +105,7 @@ PJ_DECL(void) pj_cis_add_num( pj_cis_t *cis);
* @param cis The scanner character specification.
* @param str The string.
*/
PJ_DECL(void) pj_cis_add_str( pj_cis_t *cis, const char *str);
PJ_DECL(void) pj_cis_add_str(pj_cis_t* cis, const char* str);
/**
* Add specification from another specification.
@ -114,7 +113,7 @@ PJ_DECL(void) pj_cis_add_str( pj_cis_t *cis, const char *str);
* @param cis The specification is to be set.
* @param rhs The specification to be copied.
*/
PJ_DECL(void) pj_cis_add_cis( pj_cis_t *cis, const pj_cis_t *rhs);
PJ_DECL(void) pj_cis_add_cis(pj_cis_t* cis, const pj_cis_t* rhs);
/**
* Delete characters in the specified range from the specification.
@ -123,7 +122,7 @@ PJ_DECL(void) pj_cis_add_cis( pj_cis_t *cis, const pj_cis_t *rhs);
* @param cstart The first character in the range.
* @param cend The next character after the last character in the range.
*/
PJ_DECL(void) pj_cis_del_range( pj_cis_t *cis, int cstart, int cend);
PJ_DECL(void) pj_cis_del_range(pj_cis_t* cis, int cstart, int cend);
/**
* Delete characters in the specified string from the specification.
@ -131,14 +130,14 @@ PJ_DECL(void) pj_cis_del_range( pj_cis_t *cis, int cstart, int cend);
* @param cis The scanner character specification.
* @param str The string.
*/
PJ_DECL(void) pj_cis_del_str( pj_cis_t *cis, const char *str);
PJ_DECL(void) pj_cis_del_str(pj_cis_t* cis, const char* str);
/**
* Invert specification.
*
* @param cis The scanner character specification.
*/
PJ_DECL(void) pj_cis_invert( pj_cis_t *cis );
PJ_DECL(void) pj_cis_invert(pj_cis_t* cis);
/**
* Check whether the specified character belongs to the specification.
@ -148,19 +147,18 @@ PJ_DECL(void) pj_cis_invert( pj_cis_t *cis );
*
* @return Non-zero if match (not necessarily one).
*/
PJ_INLINE(int) pj_cis_match( const pj_cis_t *cis, pj_uint8_t c )
PJ_INLINE(int) pj_cis_match(const pj_cis_t* cis, pj_uint8_t c)
{
return PJ_CIS_ISSET(cis, c);
}
/**
* Flags for scanner.
*/
enum
{
/** This flags specifies that the scanner should automatically skip
whitespaces
whitespaces
*/
PJ_SCAN_AUTOSKIP_WS = 1,
@ -174,47 +172,42 @@ enum
PJ_SCAN_AUTOSKIP_NEWLINE = 4
};
/* Forward decl. */
struct pj_scanner;
/**
* The callback function type to be called by the scanner when it encounters
* syntax error.
*
* @param scanner The scanner instance that calls the callback .
*/
typedef void (*pj_syn_err_func_ptr)(struct pj_scanner *scanner);
typedef void (*pj_syn_err_func_ptr)(struct pj_scanner* scanner);
/**
* The text scanner structure.
*/
typedef struct pj_scanner
{
char *begin; /**< Start of input buffer. */
char *end; /**< End of input buffer. */
char *curptr; /**< Current pointer. */
int line; /**< Current line. */
char *start_line; /**< Where current line starts. */
int skip_ws; /**< Skip whitespace flag. */
pj_syn_err_func_ptr callback; /**< Syntax error callback. */
char* begin; /**< Start of input buffer. */
char* end; /**< End of input buffer. */
char* curptr; /**< Current pointer. */
int line; /**< Current line. */
char* start_line; /**< Where current line starts. */
int skip_ws; /**< Skip whitespace flag. */
pj_syn_err_func_ptr callback; /**< Syntax error callback. */
} pj_scanner;
/**
* This structure can be used by application to store the state of the parser,
* so that the scanner state can be rollback to this state when necessary.
*/
typedef struct pj_scan_state
{
char *curptr; /**< Current scanner's pointer. */
int line; /**< Current line. */
char *start_line; /**< Start of current line. */
char* curptr; /**< Current scanner's pointer. */
int line; /**< Current line. */
char* start_line; /**< Start of current line. */
} pj_scan_state;
/**
* Initialize the scanner.
* Note that the input string buffer MUST be NULL terminated and have
@ -229,34 +222,30 @@ typedef struct pj_scan_state
* @param callback Callback to be called when the scanner encounters syntax
* error condition.
*/
PJ_DECL(void) pj_scan_init( pj_scanner *scanner, char *bufstart,
pj_size_t buflen,
unsigned options,
pj_syn_err_func_ptr callback );
PJ_DECL(void)
pj_scan_init(pj_scanner* scanner, char* bufstart, pj_size_t buflen,
unsigned options, pj_syn_err_func_ptr callback);
/**
/**
* Call this function when application has finished using the scanner.
*
* @param scanner The scanner.
*/
PJ_DECL(void) pj_scan_fini( pj_scanner *scanner );
PJ_DECL(void) pj_scan_fini(pj_scanner* scanner);
/**
/**
* Determine whether the EOF condition for the scanner has been met.
*
* @param scanner The scanner.
*
* @return Non-zero if scanner is EOF.
*/
PJ_INLINE(int) pj_scan_is_eof( const pj_scanner *scanner)
PJ_INLINE(int) pj_scan_is_eof(const pj_scanner* scanner)
{
return scanner->curptr >= scanner->end;
}
/**
/**
* Peek strings in current position according to parameter spec, and return
* the strings in parameter out. The current scanner position will not be
* moved. If the scanner is already in EOF state, syntax error callback will
@ -269,14 +258,13 @@ PJ_INLINE(int) pj_scan_is_eof( const pj_scanner *scanner)
* @return the character right after the peek-ed position or zero if there's
* no more characters.
*/
PJ_DECL(int) pj_scan_peek( pj_scanner *scanner,
const pj_cis_t *spec, pj_str_t *out);
PJ_DECL(int)
pj_scan_peek(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out);
/**
/**
* Peek len characters in current position, and return them in out parameter.
* Note that whitespaces or newlines will be returned as it is, regardless
* of PJ_SCAN_AUTOSKIP_WS settings. If the character left is less than len,
* of PJ_SCAN_AUTOSKIP_WS settings. If the character left is less than len,
* syntax error callback will be called.
*
* @param scanner The scanner.
@ -286,11 +274,9 @@ PJ_DECL(int) pj_scan_peek( pj_scanner *scanner,
* @return the character right after the peek-ed position or zero if there's
* no more characters.
*/
PJ_DECL(int) pj_scan_peek_n( pj_scanner *scanner,
pj_size_t len, pj_str_t *out);
PJ_DECL(int) pj_scan_peek_n(pj_scanner* scanner, pj_size_t len, pj_str_t* out);
/**
/**
* Peek strings in current position until spec is matched, and return
* the strings in parameter out. The current scanner position will not be
* moved. If the scanner is already in EOF state, syntax error callback will
@ -302,12 +288,10 @@ PJ_DECL(int) pj_scan_peek_n( pj_scanner *scanner,
*
* @return the character right after the peek-ed position.
*/
PJ_DECL(int) pj_scan_peek_until( pj_scanner *scanner,
const pj_cis_t *spec,
pj_str_t *out);
PJ_DECL(int)
pj_scan_peek_until(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out);
/**
/**
* Get characters from the buffer according to the spec, and return them
* in out parameter. The scanner will attempt to get as many characters as
* possible as long as the spec matches. If the first character doesn't
@ -318,11 +302,10 @@ PJ_DECL(int) pj_scan_peek_until( pj_scanner *scanner,
* @param spec The spec to match input string.
* @param out String to store the result.
*/
PJ_DECL(void) pj_scan_get( pj_scanner *scanner,
const pj_cis_t *spec, pj_str_t *out);
PJ_DECL(void)
pj_scan_get(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out);
/**
/**
* Just like #pj_scan_get(), but additionally performs unescaping when
* escaped ('%') character is found. The input spec MUST NOT contain the
* specification for '%' characted.
@ -331,11 +314,10 @@ PJ_DECL(void) pj_scan_get( pj_scanner *scanner,
* @param spec The spec to match input string.
* @param out String to store the result.
*/
PJ_DECL(void) pj_scan_get_unescape( pj_scanner *scanner,
const pj_cis_t *spec, pj_str_t *out);
PJ_DECL(void)
pj_scan_get_unescape(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out);
/**
/**
* Get characters between quotes. If current input doesn't match begin_quote,
* syntax error will be thrown. Note that the resulting string will contain
* the enclosing quote.
@ -345,11 +327,11 @@ PJ_DECL(void) pj_scan_get_unescape( pj_scanner *scanner,
* @param end_quote The character to end the quote.
* @param out String to store the result.
*/
PJ_DECL(void) pj_scan_get_quote( pj_scanner *scanner,
int begin_quote, int end_quote,
pj_str_t *out);
PJ_DECL(void)
pj_scan_get_quote(pj_scanner* scanner, int begin_quote, int end_quote,
pj_str_t* out);
/**
/**
* Get characters between quotes. If current input doesn't match begin_quote,
* syntax error will be thrown. Note that the resulting string will contain
* the enclosing quote.
@ -366,11 +348,9 @@ PJ_DECL(void) pj_scan_get_quote( pj_scanner *scanner,
* @param qsize The size of the begin_quotes and end_quotes arrays.
* @param out String to store the result.
*/
PJ_DECL(void) pj_scan_get_quotes(pj_scanner *scanner,
const char *begin_quotes,
const char *end_quotes, int qsize,
pj_str_t *out);
PJ_DECL(void)
pj_scan_get_quotes(pj_scanner* scanner, const char* begin_quotes,
const char* end_quotes, int qsize, pj_str_t* out);
/**
* Get N characters from the scanner.
@ -379,21 +359,18 @@ PJ_DECL(void) pj_scan_get_quotes(pj_scanner *scanner,
* @param N Number of characters to get.
* @param out String to store the result.
*/
PJ_DECL(void) pj_scan_get_n( pj_scanner *scanner,
unsigned N, pj_str_t *out);
PJ_DECL(void) pj_scan_get_n(pj_scanner* scanner, unsigned N, pj_str_t* out);
/**
/**
* Get one character from the scanner.
*
* @param scanner The scanner.
*
* @return The character.
*/
PJ_DECL(int) pj_scan_get_char( pj_scanner *scanner );
PJ_DECL(int) pj_scan_get_char(pj_scanner* scanner);
/**
/**
* Get characters from the scanner and move the scanner position until the
* current character matches the spec.
*
@ -401,11 +378,10 @@ PJ_DECL(int) pj_scan_get_char( pj_scanner *scanner );
* @param spec Get until the input match this spec.
* @param out String to store the result.
*/
PJ_DECL(void) pj_scan_get_until( pj_scanner *scanner,
const pj_cis_t *spec, pj_str_t *out);
PJ_DECL(void)
pj_scan_get_until(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out);
/**
/**
* Get characters from the scanner and move the scanner position until the
* current character matches until_char.
*
@ -413,11 +389,10 @@ PJ_DECL(void) pj_scan_get_until( pj_scanner *scanner,
* @param until_char Get until the input match this character.
* @param out String to store the result.
*/
PJ_DECL(void) pj_scan_get_until_ch( pj_scanner *scanner,
int until_char, pj_str_t *out);
PJ_DECL(void)
pj_scan_get_until_ch(pj_scanner* scanner, int until_char, pj_str_t* out);
/**
/**
* Get characters from the scanner and move the scanner position until the
* current character matches until_char.
*
@ -425,10 +400,11 @@ PJ_DECL(void) pj_scan_get_until_ch( pj_scanner *scanner,
* @param until_spec Get until the input match any of these characters.
* @param out String to store the result.
*/
PJ_DECL(void) pj_scan_get_until_chr( pj_scanner *scanner,
const char *until_spec, pj_str_t *out);
PJ_DECL(void)
pj_scan_get_until_chr(pj_scanner* scanner, const char* until_spec,
pj_str_t* out);
/**
/**
* Advance the scanner N characters, and skip whitespace
* if necessary.
*
@ -437,23 +413,21 @@ PJ_DECL(void) pj_scan_get_until_chr( pj_scanner *scanner,
* @param skip Flag to specify whether whitespace should be skipped
* after skipping the characters.
*/
PJ_DECL(void) pj_scan_advance_n( pj_scanner *scanner,
unsigned N, pj_bool_t skip);
PJ_DECL(void)
pj_scan_advance_n(pj_scanner* scanner, unsigned N, pj_bool_t skip);
/**
/**
* Compare string in current position with the specified string.
*
*
* @param scanner The scanner.
* @param s The string to compare with.
* @param len Length of the string to compare.
*
* @return zero, <0, or >0 (just like strcmp()).
*/
PJ_DECL(int) pj_scan_strcmp( pj_scanner *scanner, const char *s, int len);
PJ_DECL(int) pj_scan_strcmp(pj_scanner* scanner, const char* s, int len);
/**
/**
* Case-less string comparison of current position with the specified
* string.
*
@ -463,7 +437,7 @@ PJ_DECL(int) pj_scan_strcmp( pj_scanner *scanner, const char *s, int len);
*
* @return zero, <0, or >0 (just like strcmp()).
*/
PJ_DECL(int) pj_scan_stricmp( pj_scanner *scanner, const char *s, int len);
PJ_DECL(int) pj_scan_stricmp(pj_scanner* scanner, const char* s, int len);
/**
* Perform case insensitive string comparison of string in current position,
@ -481,46 +455,41 @@ PJ_DECL(int) pj_scan_stricmp( pj_scanner *scanner, const char *s, int len);
*
* @see strnicmp_alnum, pj_stricmp_alnum
*/
PJ_DECL(int) pj_scan_stricmp_alnum( pj_scanner *scanner, const char *s,
int len);
PJ_DECL(int) pj_scan_stricmp_alnum(pj_scanner* scanner, const char* s, int len);
/**
/**
* Get a newline from the scanner. A newline is defined as '\\n', or '\\r', or
* "\\r\\n". If current input is not newline, syntax error will be thrown.
*
* @param scanner The scanner.
*/
PJ_DECL(void) pj_scan_get_newline( pj_scanner *scanner );
PJ_DECL(void) pj_scan_get_newline(pj_scanner* scanner);
/**
/**
* Manually skip whitespaces according to flag that was specified when
* the scanner was initialized.
*
* @param scanner The scanner.
*/
PJ_DECL(void) pj_scan_skip_whitespace( pj_scanner *scanner );
PJ_DECL(void) pj_scan_skip_whitespace(pj_scanner* scanner);
/**
* Skip current line.
*
* @param scanner The scanner.
*/
PJ_DECL(void) pj_scan_skip_line( pj_scanner *scanner );
PJ_DECL(void) pj_scan_skip_line(pj_scanner* scanner);
/**
/**
* Save the full scanner state.
*
* @param scanner The scanner.
* @param state Variable to store scanner's state.
*/
PJ_DECL(void) pj_scan_save_state( const pj_scanner *scanner,
pj_scan_state *state);
PJ_DECL(void)
pj_scan_save_state(const pj_scanner* scanner, pj_scan_state* state);
/**
/**
* Restore the full scanner state.
* Note that this would not restore the string if application has modified
* it. This will only restore the scanner scanning position.
@ -528,8 +497,7 @@ PJ_DECL(void) pj_scan_save_state( const pj_scanner *scanner,
* @param scanner The scanner.
* @param state State of the scanner.
*/
PJ_DECL(void) pj_scan_restore_state( pj_scanner *scanner,
pj_scan_state *state);
PJ_DECL(void) pj_scan_restore_state(pj_scanner* scanner, pj_scan_state* state);
/**
* Get current column position.
@ -538,7 +506,7 @@ PJ_DECL(void) pj_scan_restore_state( pj_scanner *scanner,
*
* @return The column position.
*/
PJ_INLINE(int) pj_scan_get_col( const pj_scanner *scanner )
PJ_INLINE(int) pj_scan_get_col(const pj_scanner* scanner)
{
return (int)(scanner->curptr - scanner->start_line);
}
@ -547,8 +515,6 @@ PJ_INLINE(int) pj_scan_get_col( const pj_scanner *scanner )
* @}
*/
PJ_END_DECL
#endif

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_SCANNER_CIS_BIT_H__
#define __PJLIB_UTIL_SCANNER_CIS_BIT_H__
@ -29,7 +28,7 @@ PJ_BEGIN_DECL
* #pj_cis_buf_t. Basicly the number of bits here
*/
#ifndef PJ_CIS_ELEM_TYPE
# define PJ_CIS_ELEM_TYPE pj_uint32_t
# define PJ_CIS_ELEM_TYPE pj_uint32_t
#endif
/**
@ -42,15 +41,15 @@ typedef PJ_CIS_ELEM_TYPE pj_cis_elem_t;
* Maximum number of input specification in a buffer.
* Effectively this means the number of bits in pj_cis_elem_t.
*/
#define PJ_CIS_MAX_INDEX (sizeof(pj_cis_elem_t) << 3)
#define PJ_CIS_MAX_INDEX (sizeof(pj_cis_elem_t) << 3)
/**
* The scanner input specification buffer.
*/
typedef struct pj_cis_buf_t
{
pj_cis_elem_t cis_buf[256]; /**< Must be 256 (not 128)! */
pj_cis_elem_t use_mask; /**< To keep used indexes. */
pj_cis_elem_t cis_buf[256]; /**< Must be 256 (not 128)! */
pj_cis_elem_t use_mask; /**< To keep used indexes. */
} pj_cis_buf_t;
/**
@ -58,11 +57,10 @@ typedef struct pj_cis_buf_t
*/
typedef struct pj_cis_t
{
pj_cis_elem_t *cis_buf; /**< Pointer to buffer. */
int cis_id; /**< Id. */
pj_cis_elem_t* cis_buf; /**< Pointer to buffer. */
int cis_id; /**< Id. */
} pj_cis_t;
/**
* Set the membership of the specified character.
* Note that this is a macro, and arguments may be evaluated more than once.
@ -70,7 +68,7 @@ typedef struct pj_cis_t
* @param cis Pointer to character input specification.
* @param c The character.
*/
#define PJ_CIS_SET(cis,c) ((cis)->cis_buf[(int)(c)] |= (1 << (cis)->cis_id))
#define PJ_CIS_SET(cis, c) ((cis)->cis_buf[(int)(c)] |= (1 << (cis)->cis_id))
/**
* Remove the membership of the specified character.
@ -79,7 +77,7 @@ typedef struct pj_cis_t
* @param cis Pointer to character input specification.
* @param c The character to be removed from the membership.
*/
#define PJ_CIS_CLR(cis,c) ((cis)->cis_buf[(int)c] &= ~(1 << (cis)->cis_id))
#define PJ_CIS_CLR(cis, c) ((cis)->cis_buf[(int)c] &= ~(1 << (cis)->cis_id))
/**
* Check the membership of the specified character.
@ -88,10 +86,8 @@ typedef struct pj_cis_t
* @param cis Pointer to character input specification.
* @param c The character.
*/
#define PJ_CIS_ISSET(cis,c) ((cis)->cis_buf[(int)c] & (1 << (cis)->cis_id))
#define PJ_CIS_ISSET(cis, c) ((cis)->cis_buf[(int)c] & (1 << (cis)->cis_id))
PJ_END_DECL
#endif /* __PJLIB_UTIL_SCANNER_CIS_BIT_H__ */
#endif /* __PJLIB_UTIL_SCANNER_CIS_BIT_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_SCANNER_CIS_BIT_H__
#define __PJLIB_UTIL_SCANNER_CIS_BIT_H__
@ -29,7 +28,7 @@ PJ_BEGIN_DECL
* #pj_cis_buf_t. Basicly the number of bits here
*/
#ifndef PJ_CIS_ELEM_TYPE
# define PJ_CIS_ELEM_TYPE int
# define PJ_CIS_ELEM_TYPE int
#endif
/**
@ -46,10 +45,9 @@ typedef int pj_cis_buf_t;
*/
typedef struct pj_cis_t
{
PJ_CIS_ELEM_TYPE cis_buf[256]; /**< Internal buffer. */
PJ_CIS_ELEM_TYPE cis_buf[256]; /**< Internal buffer. */
} pj_cis_t;
/**
* Set the membership of the specified character.
* Note that this is a macro, and arguments may be evaluated more than once.
@ -57,7 +55,7 @@ typedef struct pj_cis_t
* @param cis Pointer to character input specification.
* @param c The character.
*/
#define PJ_CIS_SET(cis,c) ((cis)->cis_buf[(int)(c)] = 1)
#define PJ_CIS_SET(cis, c) ((cis)->cis_buf[(int)(c)] = 1)
/**
* Remove the membership of the specified character.
@ -66,7 +64,7 @@ typedef struct pj_cis_t
* @param cis Pointer to character input specification.
* @param c The character to be removed from the membership.
*/
#define PJ_CIS_CLR(cis,c) ((cis)->cis_buf[(int)c] = 0)
#define PJ_CIS_CLR(cis, c) ((cis)->cis_buf[(int)c] = 0)
/**
* Check the membership of the specified character.
@ -75,10 +73,8 @@ typedef struct pj_cis_t
* @param cis Pointer to character input specification.
* @param c The character.
*/
#define PJ_CIS_ISSET(cis,c) ((cis)->cis_buf[(int)c])
#define PJ_CIS_ISSET(cis, c) ((cis)->cis_buf[(int)c])
PJ_END_DECL
#endif /* __PJLIB_UTIL_SCANNER_CIS_BIT_H__ */
#endif /* __PJLIB_UTIL_SCANNER_CIS_BIT_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_SHA1_H__
#define __PJLIB_UTIL_SHA1_H__
@ -38,36 +37,34 @@ PJ_BEGIN_DECL
/** SHA1 context */
typedef struct pj_sha1_context
{
pj_uint32_t state[5]; /**< State */
pj_uint32_t count[2]; /**< Count */
pj_uint8_t buffer[64]; /**< Buffer */
pj_uint32_t state[5]; /**< State */
pj_uint32_t count[2]; /**< Count */
pj_uint8_t buffer[64]; /**< Buffer */
} pj_sha1_context;
/** SHA1 digest size is 20 bytes */
#define PJ_SHA1_DIGEST_SIZE 20
#define PJ_SHA1_DIGEST_SIZE 20
/** Initialize the algorithm.
/** Initialize the algorithm.
* @param ctx SHA1 context.
*/
PJ_DECL(void) pj_sha1_init(pj_sha1_context *ctx);
PJ_DECL(void) pj_sha1_init(pj_sha1_context* ctx);
/** Append a stream to the message.
/** Append a stream to the message.
* @param ctx SHA1 context.
* @param data Data.
* @param nbytes Length of data.
*/
PJ_DECL(void) pj_sha1_update(pj_sha1_context *ctx,
const pj_uint8_t *data,
const pj_size_t nbytes);
PJ_DECL(void)
pj_sha1_update(pj_sha1_context* ctx, const pj_uint8_t* data,
const pj_size_t nbytes);
/** Finish the message and return the digest.
/** Finish the message and return the digest.
* @param ctx SHA1 context.
* @param digest 16 byte digest.
*/
PJ_DECL(void) pj_sha1_final(pj_sha1_context *ctx,
pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE]);
PJ_DECL(void)
pj_sha1_final(pj_sha1_context* ctx, pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE]);
/**
* @}
@ -75,6 +72,4 @@ PJ_DECL(void) pj_sha1_final(pj_sha1_context *ctx,
PJ_END_DECL
#endif /* __PJLIB_UTIL_SHA1_H__ */
#endif /* __PJLIB_UTIL_SHA1_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_SRV_RESOLVER_H__
#define __PJLIB_UTIL_SRV_RESOLVER_H__
@ -41,7 +40,7 @@ PJ_BEGIN_DECL
* The #pj_dns_srv_resolve() function will asynchronously resolve the server
* name into IP address(es) with a single function call. If the SRV name
* contains multiple names, then each will be resolved with individual
* DNS A resolution to get the IP addresses. Upon successful completion,
* DNS A resolution to get the IP addresses. Upon successful completion,
* application callback will be called with each IP address of the
* target selected based on the load-balancing and fail-over criteria
* below.
@ -51,27 +50,28 @@ PJ_BEGIN_DECL
* the resolver will fallback to using DNS A record resolution to resolve
* the name.
*
* \subsection PJ_DNS_SRV_RESOLVER_FAILOVER_LOADBALANCE Load-Balancing and Fail-Over
* \subsection PJ_DNS_SRV_RESOLVER_FAILOVER_LOADBALANCE Load-Balancing and
*Fail-Over
*
* When multiple targets are returned in the DNS SRV response, server entries
* are selected based on the following rule (which is described in RFC 2782):
* - targets will be sorted based on the priority first.
* - for targets with the same priority, #pj_dns_srv_resolve() will select
* only one target according to its weight. To select this one target,
* the function associates running-sum for all targets, and generates
* the function associates running-sum for all targets, and generates
* a random number between zero and the total running-sum (inclusive).
* The target selected is the first target with running-sum greater than
* or equal to this random number.
*
* The above procedure will select one target for each priority, allowing
* application to fail-over to the next target when the previous target fails.
* These targets are returned in the #pj_dns_srv_record structure
* argument of the callback.
* These targets are returned in the #pj_dns_srv_record structure
* argument of the callback.
*
* \section PJ_DNS_SRV_RESOLVER_REFERENCE Reference
*
* Reference:
* - <A HREF="http://www.ietf.org/rfc/rfc2782.txt">RFC 2782</A>:
* - <A HREF="http://www.ietf.org/rfc/rfc2782.txt">RFC 2782</A>:
* A DNS RR for specifying the location of services (DNS SRV)
*/
@ -87,7 +87,7 @@ typedef enum pj_dns_srv_option
* make the resolver fallback to both DNS A and DNS AAAA
* resolutions if SRV resolution fails.
*/
PJ_DNS_SRV_FALLBACK_A = 1,
PJ_DNS_SRV_FALLBACK_A = 1,
/**
* Specify if the resolver should fallback with DNS AAAA
@ -96,7 +96,7 @@ typedef enum pj_dns_srv_option
* make the resolver fallback to both DNS A and DNS AAAA
* resolutions if SRV resolution fails.
*/
PJ_DNS_SRV_FALLBACK_AAAA = 2,
PJ_DNS_SRV_FALLBACK_AAAA = 2,
/**
* Specify if the resolver should try to resolve with DNS AAAA
@ -104,7 +104,7 @@ typedef enum pj_dns_srv_option
* option is not specified, the SRV resolver will query the
* DNS A record for the target instead.
*/
PJ_DNS_SRV_RESOLVE_AAAA = 4,
PJ_DNS_SRV_RESOLVE_AAAA = 4,
/**
* Specify if the resolver should try to resolve with DNS AAAA
@ -115,7 +115,6 @@ typedef enum pj_dns_srv_option
} pj_dns_srv_option;
/**
* This structure represents DNS SRV records as the result of DNS SRV
* resolution using #pj_dns_srv_resolve().
@ -123,28 +122,27 @@ typedef enum pj_dns_srv_option
typedef struct pj_dns_srv_record
{
/** Number of address records. */
unsigned count;
unsigned count;
/** Address records. */
struct
{
/** Server priority (the lower the higher the priority). */
unsigned priority;
/** Server priority (the lower the higher the priority). */
unsigned priority;
/** Server weight (the higher the more load it can handle). */
unsigned weight;
/** Server weight (the higher the more load it can handle). */
unsigned weight;
/** Port number. */
pj_uint16_t port;
/** Port number. */
pj_uint16_t port;
/** The host address. */
pj_dns_addr_record server;
/** The host address. */
pj_dns_addr_record server;
} entry[PJ_DNS_SRV_MAX_ADDR];
} pj_dns_srv_record;
/** Opaque declaration for DNS SRV query */
typedef struct pj_dns_srv_async_query pj_dns_srv_async_query;
@ -152,10 +150,8 @@ typedef struct pj_dns_srv_async_query pj_dns_srv_async_query;
* Type of callback function to receive notification from the resolver
* when the resolution process completes.
*/
typedef void pj_dns_srv_resolver_cb(void *user_data,
pj_status_t status,
const pj_dns_srv_record *rec);
typedef void pj_dns_srv_resolver_cb(void* user_data, pj_status_t status,
const pj_dns_srv_record* rec);
/**
* Start DNS SRV resolution for the specified name. The full name of the
@ -166,14 +162,14 @@ typedef void pj_dns_srv_resolver_cb(void *user_data,
* and with all the leading underscore characters and
* ending dot (e.g. "_sip._udp.", "_stun._udp.").
* @param def_port The port number to be assigned to the resolved address
* when the DNS SRV resolution fails and the name is
* when the DNS SRV resolution fails and the name is
* resolved with DNS A resolution.
* @param pool Memory pool used to allocate memory for the query.
* @param resolver The resolver instance.
* @param option Option flags, which can be constructed from
* #pj_dns_srv_option bitmask. Note that this argument
* was called "fallback_a" in pjsip version 0.8.0 and
* older, but the new option should be backward
* older, but the new option should be backward
* compatible with existing applications. If application
* specifies PJ_TRUE as "fallback_a" value, it will
* correspond to PJ_DNS_SRV_FALLBACK_A option.
@ -187,16 +183,12 @@ typedef void pj_dns_srv_resolver_cb(void *user_data,
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_dns_srv_resolve(const pj_str_t *domain_name,
const pj_str_t *res_name,
unsigned def_port,
pj_pool_t *pool,
pj_dns_resolver *resolver,
unsigned option,
void *token,
pj_dns_srv_resolver_cb *cb,
pj_dns_srv_async_query **p_query);
PJ_DECL(pj_status_t)
pj_dns_srv_resolve(const pj_str_t* domain_name, const pj_str_t* res_name,
unsigned def_port, pj_pool_t* pool,
pj_dns_resolver* resolver, unsigned option, void* token,
pj_dns_srv_resolver_cb* cb,
pj_dns_srv_async_query** p_query);
/**
* Cancel an outstanding DNS SRV query.
@ -207,9 +199,8 @@ PJ_DECL(pj_status_t) pj_dns_srv_resolve(const pj_str_t *domain_name,
*
* @return PJ_SUCCESS on success, or the appropriate error code,
*/
PJ_DECL(pj_status_t) pj_dns_srv_cancel_query(pj_dns_srv_async_query *query,
pj_bool_t notify);
PJ_DECL(pj_status_t)
pj_dns_srv_cancel_query(pj_dns_srv_async_query* query, pj_bool_t notify);
/**
* @}
@ -217,6 +208,4 @@ PJ_DECL(pj_status_t) pj_dns_srv_cancel_query(pj_dns_srv_async_query *query,
PJ_END_DECL
#endif /* __PJLIB_UTIL_SRV_RESOLVER_H__ */
#endif /* __PJLIB_UTIL_SRV_RESOLVER_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_STRING_H__
#define __PJLIB_UTIL_STRING_H__
@ -46,7 +45,7 @@ PJ_BEGIN_DECL
*
* @return String with no escaped characters.
*/
PJ_DECL(pj_str_t) pj_str_unescape( pj_pool_t *pool, const pj_str_t *src);
PJ_DECL(pj_str_t) pj_str_unescape(pj_pool_t* pool, const pj_str_t* src);
/**
* Unescape string to destination.
@ -56,7 +55,7 @@ PJ_DECL(pj_str_t) pj_str_unescape( pj_pool_t *pool, const pj_str_t *src);
*
* @return Target string.
*/
PJ_DECL(pj_str_t*) pj_strcpy_unescape(pj_str_t *dst, const pj_str_t *src);
PJ_DECL(pj_str_t*) pj_strcpy_unescape(pj_str_t* dst, const pj_str_t* src);
/**
* Copy string to destination while escaping reserved characters, up to
@ -65,16 +64,16 @@ PJ_DECL(pj_str_t*) pj_strcpy_unescape(pj_str_t *dst, const pj_str_t *src);
* @param dst Target string.
* @param src Source string.
* @param max Maximum length to copy to target string.
* @param unres Unreserved characters, which are allowed to appear
* @param unres Unreserved characters, which are allowed to appear
* unescaped.
*
* @return The target string if all characters have been copied
* @return The target string if all characters have been copied
* successfully, or NULL if there's not enough buffer to
* escape the strings.
*/
PJ_DECL(pj_str_t*) pj_strncpy_escape(pj_str_t *dst, const pj_str_t *src,
pj_ssize_t max, const pj_cis_t *unres);
PJ_DECL(pj_str_t*)
pj_strncpy_escape(pj_str_t* dst, const pj_str_t* src, pj_ssize_t max,
const pj_cis_t* unres);
/**
* Copy string to destination while escaping reserved characters, up to
@ -83,20 +82,20 @@ PJ_DECL(pj_str_t*) pj_strncpy_escape(pj_str_t *dst, const pj_str_t *src,
* @param dst Target string.
* @param src Source string.
* @param max Maximum length to copy to target string.
* @param unres Unreserved characters, which are allowed to appear
* @param unres Unreserved characters, which are allowed to appear
* unescaped.
*
* @return The length of the destination, or -1 if there's not
* enough buffer.
*/
PJ_DECL(pj_ssize_t) pj_strncpy2_escape(char *dst, const pj_str_t *src,
pj_ssize_t max, const pj_cis_t *unres);
PJ_DECL(pj_ssize_t)
pj_strncpy2_escape(char* dst, const pj_str_t* src, pj_ssize_t max,
const pj_cis_t* unres);
PJ_END_DECL
/**
* @}
*/
#endif /* __PJLIB_UTIL_STRING_H__ */
#endif /* __PJLIB_UTIL_STRING_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJSTUN_H__
#define __PJSTUN_H__
@ -28,7 +27,6 @@
#include <pjlib-util/types.h>
#include <pj/sock.h>
PJ_BEGIN_DECL
/*
@ -36,15 +34,14 @@ PJ_BEGIN_DECL
*/
typedef enum pjstun_msg_type
{
PJSTUN_BINDING_REQUEST = 0x0001,
PJSTUN_BINDING_RESPONSE = 0x0101,
PJSTUN_BINDING_ERROR_RESPONSE = 0x0111,
PJSTUN_SHARED_SECRET_REQUEST = 0x0002,
PJSTUN_SHARED_SECRET_RESPONSE = 0x0102,
PJSTUN_SHARED_SECRET_ERROR_RESPONSE = 0x0112
PJSTUN_BINDING_REQUEST = 0x0001,
PJSTUN_BINDING_RESPONSE = 0x0101,
PJSTUN_BINDING_ERROR_RESPONSE = 0x0111,
PJSTUN_SHARED_SECRET_REQUEST = 0x0002,
PJSTUN_SHARED_SECRET_RESPONSE = 0x0102,
PJSTUN_SHARED_SECRET_ERROR_RESPONSE = 0x0112
} pjstun_msg_type;
/*
* This enumeration describes STUN attribute types.
*/
@ -64,38 +61,35 @@ typedef enum pjstun_attr_type
PJSTUN_ATTR_XOR_MAPPED_ADDR = 0x0020
} pjstun_attr_type;
/*
* This structre describes STUN message header.
*/
typedef struct pjstun_msg_hdr
{
pj_uint16_t type;
pj_uint16_t length;
pj_uint32_t tsx[4];
pj_uint16_t type;
pj_uint16_t length;
pj_uint32_t tsx[4];
} pjstun_msg_hdr;
/*
* This structre describes STUN attribute header.
*/
typedef struct pjstun_attr_hdr
{
pj_uint16_t type;
pj_uint16_t length;
pj_uint16_t type;
pj_uint16_t length;
} pjstun_attr_hdr;
/*
* This structre describes STUN MAPPED-ADDR attribute.
*/
typedef struct pjstun_mapped_addr_attr
{
pjstun_attr_hdr hdr;
pj_uint8_t ignored;
pj_uint8_t family;
pj_uint16_t port;
pj_uint32_t addr;
pjstun_attr_hdr hdr;
pj_uint8_t ignored;
pj_uint8_t family;
pj_uint16_t port;
pj_uint32_t addr;
} pjstun_mapped_addr_attr;
typedef pjstun_mapped_addr_attr pjstun_response_addr_attr;
@ -105,44 +99,42 @@ typedef pjstun_mapped_addr_attr pjstun_reflected_form_attr;
typedef struct pjstun_change_request_attr
{
pjstun_attr_hdr hdr;
pj_uint32_t value;
pjstun_attr_hdr hdr;
pj_uint32_t value;
} pjstun_change_request_attr;
typedef struct pjstun_username_attr
{
pjstun_attr_hdr hdr;
pj_uint32_t value[1];
pjstun_attr_hdr hdr;
pj_uint32_t value[1];
} pjstun_username_attr;
typedef pjstun_username_attr pjstun_password_attr;
typedef struct pjstun_error_code_attr
{
pjstun_attr_hdr hdr;
pj_uint16_t ignored;
pj_uint8_t err_class;
pj_uint8_t number;
char reason[4];
pjstun_attr_hdr hdr;
pj_uint16_t ignored;
pj_uint8_t err_class;
pj_uint8_t number;
char reason[4];
} pjstun_error_code_attr;
typedef struct pjstun_msg
{
pjstun_msg_hdr *hdr;
int attr_count;
pjstun_attr_hdr *attr[PJSTUN_MAX_ATTR];
pjstun_msg_hdr* hdr;
int attr_count;
pjstun_attr_hdr* attr[PJSTUN_MAX_ATTR];
} pjstun_msg;
/* STUN message API (stun.c). */
PJ_DECL(pj_status_t) pjstun_create_bind_req( pj_pool_t *pool,
void **msg, pj_size_t *len,
pj_uint32_t id_hi,
pj_uint32_t id_lo);
PJ_DECL(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t len,
pjstun_msg *msg);
PJ_DECL(void*) pjstun_msg_find_attr( pjstun_msg *msg, pjstun_attr_type t);
PJ_DECL(pj_status_t)
pjstun_create_bind_req(pj_pool_t* pool, void** msg, pj_size_t* len,
pj_uint32_t id_hi, pj_uint32_t id_lo);
PJ_DECL(pj_status_t)
pjstun_parse_msg(void* buf, pj_size_t len, pjstun_msg* msg);
PJ_DECL(void*) pjstun_msg_find_attr(pjstun_msg* msg, pjstun_attr_type t);
/**
* @defgroup PJLIB_UTIL_STUN_CLIENT Simple STUN Helper
@ -157,7 +149,7 @@ PJ_DECL(void*) pjstun_msg_find_attr( pjstun_msg *msg, pjstun_attr_type t);
/**
* This is the main function to request the mapped address of local sockets
* to multiple STUN servers. This function is able to find the mapped
* to multiple STUN servers. This function is able to find the mapped
* addresses of multiple sockets simultaneously, and for each socket, two
* requests will be sent to two different STUN servers to see if both servers
* get the same public address for the same socket. (Note that application can
@ -176,10 +168,10 @@ PJ_DECL(void*) pjstun_msg_find_attr( pjstun_msg *msg, pjstun_attr_type t);
* to be queried from the STUN servers.
* @param srv1 Host name or IP address string of the first STUN
* server.
* @param port1 The port number of the first STUN server.
* @param port1 The port number of the first STUN server.
* @param srv2 Host name or IP address string of the second STUN
* server.
* @param port2 The port number of the second STUN server.
* @param port2 The port number of the second STUN server.
* @param mapped_addr Array to receive the mapped public address of the local
* UDP sockets, when the function returns PJ_SUCCESS.
*
@ -193,12 +185,10 @@ PJ_DECL(void*) pjstun_msg_find_attr( pjstun_msg *msg, pjstun_attr_type t);
* - etc.
*
*/
PJ_DECL(pj_status_t) pjstun_get_mapped_addr( pj_pool_factory *pf,
int sock_cnt, pj_sock_t sock[],
const pj_str_t *srv1, int port1,
const pj_str_t *srv2, int port2,
pj_sockaddr_in mapped_addr[]);
PJ_DECL(pj_status_t)
pjstun_get_mapped_addr(pj_pool_factory* pf, int sock_cnt, pj_sock_t sock[],
const pj_str_t* srv1, int port1, const pj_str_t* srv2,
int port2, pj_sockaddr_in mapped_addr[]);
/*
* This structre describes configurable setting for requesting mapped address.
@ -209,8 +199,8 @@ typedef struct pjstun_setting
* Specifies whether STUN request generated by old STUN library should
* insert magic cookie (specified in RFC 5389) in the transaction ID.
*/
pj_bool_t use_stun2;
pj_bool_t use_stun2;
/**
* Address family of the STUN servers.
*/
@ -238,7 +228,6 @@ typedef struct pjstun_setting
} pjstun_setting;
/**
* Another version of mapped address resolution of local sockets to multiple
* STUN servers configured in #pjstun_setting. This function is able to find
@ -272,12 +261,10 @@ typedef struct pjstun_setting
* - etc.
*
*/
PJ_DECL(pj_status_t) pjstun_get_mapped_addr2( pj_pool_factory *pf,
const pjstun_setting *opt,
int sock_cnt,
pj_sock_t sock[],
pj_sockaddr_in mapped_addr[]);
PJ_DECL(pj_status_t)
pjstun_get_mapped_addr2(pj_pool_factory* pf, const pjstun_setting* opt,
int sock_cnt, pj_sock_t sock[],
pj_sockaddr_in mapped_addr[]);
PJ_END_DECL
@ -285,5 +272,4 @@ PJ_END_DECL
* @}
*/
#endif /* __PJSTUN_H__ */
#endif /* __PJSTUN_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJLIB_UTIL_TYPES_H__
#define __PJLIB_UTIL_TYPES_H__
@ -42,11 +41,8 @@ PJ_BEGIN_DECL
*/
PJ_DECL(pj_status_t) pjlib_util_init(void);
PJ_END_DECL
/**
* @}
*/
@ -71,7 +67,7 @@ PJ_END_DECL
* \n
* This is the documentation of PJLIB-UTIL, an auxiliary library providing
* adjunct functions to PJLIB.
*
*
* Please go to the <A HREF="modules.htm"><B>Table of Contents</B></A> page
* for list of modules.
*
@ -91,5 +87,4 @@ PJ_END_DECL
* \n
*/
#endif /* __PJLIB_UTIL_TYPES_H__ */
#endif /* __PJLIB_UTIL_TYPES_H__ */

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (C) 2022 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
@ -13,7 +13,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_UPNP_H__
#define __PJ_UPNP_H__
@ -25,7 +25,6 @@
#include <pj/sock.h>
PJ_BEGIN_DECL
/**
@ -48,28 +47,28 @@ typedef struct pj_upnp_init_param
/**
* The pool factory where memory will be allocated from.
*/
pj_pool_factory *factory;
pj_pool_factory* factory;
/**
* The interface name to use for all UPnP operations.
*
* If NULL, the library will use the first suitable interface found.
*/
const char *if_name;
const char* if_name;
/**
* The port number to use for all UPnP operations.
*
* If 0, the library will pick an arbitrary free port.
*/
unsigned port;
unsigned port;
/**
* The time duration to search for IGD devices (in seconds).
*
* If 0, the library will use PJ_UPNP_DEFAULT_SEARCH_TIME.
*/
int search_time;
int search_time;
/**
* The callback to notify application when the initialization
@ -77,12 +76,10 @@ typedef struct pj_upnp_init_param
*
* @param status The initialization status.
*/
void (*upnp_cb)(pj_status_t status);
void (*upnp_cb)(pj_status_t status);
} pj_upnp_init_param;
/**
* Initialize UPnP library and initiate the search for valid Internet
* Gateway Devices (IGD) in the network.
@ -92,8 +89,7 @@ typedef struct pj_upnp_init_param
* @return PJ_SUCCESS on success, or the appropriate error
* status.
*/
PJ_DECL(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param);
PJ_DECL(pj_status_t) pj_upnp_init(const pj_upnp_init_param* param);
/**
* Deinitialize UPnP library.
@ -103,7 +99,6 @@ PJ_DECL(pj_status_t) pj_upnp_init(const pj_upnp_init_param *param);
*/
PJ_DECL(pj_status_t) pj_upnp_deinit();
/**
* This is the main function to request a port mapping. If successful,
* the Internet Gateway Device will redirect communication received on
@ -121,11 +116,9 @@ PJ_DECL(pj_status_t) pj_upnp_deinit();
* @return PJ_SUCCESS on success, or the appropriate error
* status.
*/
PJ_DECL(pj_status_t)pj_upnp_add_port_mapping(unsigned sock_cnt,
const pj_sock_t sock[],
unsigned ext_port[],
pj_sockaddr mapped_addr[]);
PJ_DECL(pj_status_t)
pj_upnp_add_port_mapping(unsigned sock_cnt, const pj_sock_t sock[],
unsigned ext_port[], pj_sockaddr mapped_addr[]);
/**
* Send request to delete a port mapping.
@ -136,8 +129,7 @@ PJ_DECL(pj_status_t)pj_upnp_add_port_mapping(unsigned sock_cnt,
* @return PJ_SUCCESS on success, or the appropriate error
* status.
*/
PJ_DECL(pj_status_t)pj_upnp_del_port_mapping(const pj_sockaddr *mapped_addr);
PJ_DECL(pj_status_t) pj_upnp_del_port_mapping(const pj_sockaddr* mapped_addr);
PJ_END_DECL
@ -145,4 +137,4 @@ PJ_END_DECL
* @}
*/
#endif /* __PJ_UPNP_H__ */
#endif /* __PJ_UPNP_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_XML_H__
#define __PJ_XML_H__
@ -45,32 +44,32 @@ typedef struct pj_xml_node pj_xml_node;
/** This structure declares XML attribute. */
struct pj_xml_attr
{
PJ_DECL_LIST_MEMBER(pj_xml_attr); /**< Standard list elements. */
pj_str_t name; /**< Attribute name. */
pj_str_t value; /**< Attribute value. */
PJ_DECL_LIST_MEMBER(pj_xml_attr); /**< Standard list elements. */
pj_str_t name; /**< Attribute name. */
pj_str_t value; /**< Attribute value. */
};
/** This structure describes XML node head inside XML node structure.
*/
typedef struct pj_xml_node_head
{
PJ_DECL_LIST_MEMBER(pj_xml_node); /**< Standard list elements. */
PJ_DECL_LIST_MEMBER(pj_xml_node); /**< Standard list elements. */
} pj_xml_node_head;
/** This structure describes XML node. */
struct pj_xml_node
{
PJ_DECL_LIST_MEMBER(pj_xml_node); /**< List @a prev and @a next member */
pj_str_t name; /**< Node name. */
pj_xml_attr attr_head; /**< Attribute list. */
pj_xml_node_head node_head; /**< Node list. */
pj_str_t content; /**< Node content. */
PJ_DECL_LIST_MEMBER(pj_xml_node); /**< List @a prev and @a next member */
pj_str_t name; /**< Node name. */
pj_xml_attr attr_head; /**< Attribute list. */
pj_xml_node_head node_head; /**< Node list. */
pj_str_t content; /**< Node content. */
};
/**
* Parse XML message into XML document with a single root node. The parser
* is capable of parsing XML processing instruction construct ("<?") and
* XML comments ("<!--"), however such constructs will be ignored and will not
* is capable of parsing XML processing instruction construct ("<?") and
* XML comments ("<!--"), however such constructs will be ignored and will not
* be included in the resulted XML node tree.
*
* Note that the XML message input buffer MUST be NULL terminated and have
@ -80,10 +79,10 @@ struct pj_xml_node
* @param msg The XML message to parse, MUST be NULL terminated.
* @param len The length of the message, not including NULL terminator.
*
* @return XML root node, or NULL if the XML document can not be parsed.
* @return XML root node, or NULL if the XML document can not be
* parsed.
*/
PJ_DECL(pj_xml_node*) pj_xml_parse( pj_pool_t *pool, char *msg, pj_size_t len);
PJ_DECL(pj_xml_node*) pj_xml_parse(pj_pool_t* pool, char* msg, pj_size_t len);
/**
* Print XML into XML message. Note that the function WILL NOT NULL terminate
@ -94,11 +93,12 @@ PJ_DECL(pj_xml_node*) pj_xml_parse( pj_pool_t *pool, char *msg, pj_size_t len);
* @param len The length of the buffer.
* @param prolog If set to nonzero, will print XML prolog ("<?xml..")
*
* @return The size of the printed message, or -1 if there is not
* @return The size of the printed message, or -1 if there is not
* sufficient space in the buffer to print the message.
*/
PJ_DECL(int) pj_xml_print( const pj_xml_node *node, char *buf, pj_size_t len,
pj_bool_t prolog);
PJ_DECL(int)
pj_xml_print(const pj_xml_node* node, char* buf, pj_size_t len,
pj_bool_t prolog);
/**
* Clone XML node and all subnodes.
@ -108,8 +108,7 @@ PJ_DECL(int) pj_xml_print( const pj_xml_node *node, char *buf, pj_size_t len,
*
* @return Cloned XML node, or NULL on fail.
*/
PJ_DECL(pj_xml_node*) pj_xml_clone( pj_pool_t *pool, const pj_xml_node *rhs);
PJ_DECL(pj_xml_node*) pj_xml_clone(pj_pool_t* pool, const pj_xml_node* rhs);
/**
* Create an empty node.
@ -119,8 +118,7 @@ PJ_DECL(pj_xml_node*) pj_xml_clone( pj_pool_t *pool, const pj_xml_node *rhs);
*
* @return The new node.
*/
PJ_DECL(pj_xml_node*) pj_xml_node_new(pj_pool_t *pool, const pj_str_t *name);
PJ_DECL(pj_xml_node*) pj_xml_node_new(pj_pool_t* pool, const pj_str_t* name);
/**
* Create new XML attribute.
@ -131,8 +129,8 @@ PJ_DECL(pj_xml_node*) pj_xml_node_new(pj_pool_t *pool, const pj_str_t *name);
*
* @return The new XML attribute.
*/
PJ_DECL(pj_xml_attr*) pj_xml_attr_new(pj_pool_t *pool, const pj_str_t *name,
const pj_str_t *value);
PJ_DECL(pj_xml_attr*)
pj_xml_attr_new(pj_pool_t* pool, const pj_str_t* name, const pj_str_t* value);
/**
* Add node to another node.
@ -140,8 +138,7 @@ PJ_DECL(pj_xml_attr*) pj_xml_attr_new(pj_pool_t *pool, const pj_str_t *name,
* @param parent Parent node.
* @param node Node to be added to parent.
*/
PJ_DECL(void) pj_xml_add_node( pj_xml_node *parent, pj_xml_node *node );
PJ_DECL(void) pj_xml_add_node(pj_xml_node* parent, pj_xml_node* node);
/**
* Add attribute to a node.
@ -149,7 +146,7 @@ PJ_DECL(void) pj_xml_add_node( pj_xml_node *parent, pj_xml_node *node );
* @param node Node.
* @param attr Attribute to add to node.
*/
PJ_DECL(void) pj_xml_add_attr( pj_xml_node *node, pj_xml_attr *attr );
PJ_DECL(void) pj_xml_add_attr(pj_xml_node* node, pj_xml_attr* attr);
/**
* Find first direct child node with the specified name.
@ -159,8 +156,8 @@ PJ_DECL(void) pj_xml_add_attr( pj_xml_node *node, pj_xml_attr *attr );
*
* @return XML node found or NULL.
*/
PJ_DECL(pj_xml_node*) pj_xml_find_node(const pj_xml_node *parent,
const pj_str_t *name);
PJ_DECL(pj_xml_node*)
pj_xml_find_node(const pj_xml_node* parent, const pj_str_t* name);
/**
* Find next direct child node with the specified name.
@ -171,9 +168,9 @@ PJ_DECL(pj_xml_node*) pj_xml_find_node(const pj_xml_node *parent,
*
* @return XML node found or NULL.
*/
PJ_DECL(pj_xml_node*) pj_xml_find_next_node(const pj_xml_node *parent,
const pj_xml_node *node,
const pj_str_t *name);
PJ_DECL(pj_xml_node*)
pj_xml_find_next_node(const pj_xml_node* parent, const pj_xml_node* node,
const pj_str_t* name);
/**
* Recursively find the first node with the specified name in the child nodes
@ -184,12 +181,11 @@ PJ_DECL(pj_xml_node*) pj_xml_find_next_node(const pj_xml_node *parent,
*
* @return XML node found or NULL.
*/
PJ_DECL(pj_xml_node*) pj_xml_find_node_rec(const pj_xml_node *parent,
const pj_str_t *name);
PJ_DECL(pj_xml_node*)
pj_xml_find_node_rec(const pj_xml_node* parent, const pj_str_t* name);
/**
* Find first attribute within a node with the specified name and optional
* Find first attribute within a node with the specified name and optional
* value.
*
* @param node XML Node.
@ -198,10 +194,9 @@ PJ_DECL(pj_xml_node*) pj_xml_find_node_rec(const pj_xml_node *parent,
*
* @return XML attribute found, or NULL.
*/
PJ_DECL(pj_xml_attr*) pj_xml_find_attr(const pj_xml_node *node,
const pj_str_t *name,
const pj_str_t *value);
PJ_DECL(pj_xml_attr*)
pj_xml_find_attr(const pj_xml_node* node, const pj_str_t* name,
const pj_str_t* value);
/**
* Find a direct child node with the specified name and match the function.
@ -214,15 +209,12 @@ PJ_DECL(pj_xml_attr*) pj_xml_find_attr(const pj_xml_node *node,
*
* @return The first matched node, or NULL.
*/
PJ_DECL(pj_xml_node*) pj_xml_find( const pj_xml_node *parent,
const pj_str_t *name,
const void *data,
pj_bool_t (*match)(const pj_xml_node *,
const void*));
PJ_DECL(pj_xml_node*)
pj_xml_find(const pj_xml_node* parent, const pj_str_t* name, const void* data,
pj_bool_t (*match)(const pj_xml_node*, const void*));
/**
* Recursively find a child node with the specified name and match the
* Recursively find a child node with the specified name and match the
* function.
*
* @param parent Parent node.
@ -233,12 +225,10 @@ PJ_DECL(pj_xml_node*) pj_xml_find( const pj_xml_node *parent,
*
* @return The first matched node, or NULL.
*/
PJ_DECL(pj_xml_node*) pj_xml_find_rec(const pj_xml_node *parent,
const pj_str_t *name,
const void *data,
pj_bool_t (*match)(const pj_xml_node*,
const void*));
PJ_DECL(pj_xml_node*)
pj_xml_find_rec(const pj_xml_node* parent, const pj_str_t* name,
const void* data,
pj_bool_t (*match)(const pj_xml_node*, const void*));
/**
* @}
@ -246,4 +236,4 @@ PJ_DECL(pj_xml_node*) pj_xml_find_rec(const pj_xml_node *parent,
PJ_END_DECL
#endif /* __PJ_XML_H__ */
#endif /* __PJ_XML_H__ */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,3 @@
/* $Id$ */
/*
* Copyright (C) 2013 Teluu Inc. (http://www.teluu.com)
*
@ -18,16 +17,16 @@
*/
#include "test.h"
#define THIS_FILE "json_test.c"
#define THIS_FILE "json_test.c"
#if INCLUDE_JSON_TEST
#include <pjlib-util/json.h>
#include <pj/log.h>
#include <pj/string.h>
# include <pjlib-util/json.h>
# include <pj/log.h>
# include <pj/string.h>
static char json_doc1[] =
"{\
"{\
\"Object\": {\
\"Integer\": 800,\
\"Negative\": -12,\
@ -55,9 +54,9 @@ static char json_doc1[] =
static int json_verify_1()
{
pj_pool_t *pool;
pj_json_elem *elem;
char *out_buf;
pj_pool_t* pool;
pj_json_elem* elem;
char* out_buf;
unsigned size;
pj_json_err_info err;
@ -66,19 +65,19 @@ static int json_verify_1()
size = (unsigned)strlen(json_doc1);
elem = pj_json_parse(pool, json_doc1, &size, &err);
if (!elem) {
PJ_LOG(1, (THIS_FILE, " Error: json_verify_1() parse error"));
goto on_error;
PJ_LOG(1, (THIS_FILE, " Error: json_verify_1() parse error"));
goto on_error;
}
size = (unsigned)strlen(json_doc1) * 2;
out_buf = pj_pool_alloc(pool, size);
if (pj_json_write(elem, out_buf, &size)) {
PJ_LOG(1, (THIS_FILE, " Error: json_verify_1() write error"));
goto on_error;
PJ_LOG(1, (THIS_FILE, " Error: json_verify_1() write error"));
goto on_error;
}
PJ_LOG(3,(THIS_FILE, "Json document:\n%s", out_buf));
PJ_LOG(3, (THIS_FILE, "Json document:\n%s", out_buf));
pj_pool_release(pool);
return 0;
@ -87,20 +86,17 @@ on_error:
return 10;
}
int json_test(void)
{
int rc;
rc = json_verify_1();
if (rc)
return rc;
return rc;
return 0;
}
#else
int json_dummy;
#endif

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,14 +14,14 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "test.h"
#include <pj/string.h>
#if defined(PJ_SUNOS) && PJ_SUNOS!=0
#if defined(PJ_SUNOS) && PJ_SUNOS != 0
#include <signal.h>
# include <signal.h>
static void init_signals()
{
struct sigaction act;
@ -35,19 +34,19 @@ static void init_signals()
#elif PJ_LINUX || PJ_DARWINOS
#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
# include <execinfo.h>
# include <signal.h>
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
static void print_stack(int sig)
{
void *array[16];
size_t size;
size = backtrace(array, 16);
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
void* array[16];
size_t size;
size = backtrace(array, 16);
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
@ -59,13 +58,13 @@ static void init_signals(void)
#else
#define init_signals()
# define init_signals()
#endif
#define boost()
int main(int argc, char *argv[])
int main(int argc, char* argv[])
{
int rc;
int interractive = 0;
@ -74,28 +73,28 @@ int main(int argc, char *argv[])
boost();
while (argc > 1) {
char *arg = argv[--argc];
char* arg = argv[--argc];
if (*arg=='-' && *(arg+1)=='i') {
interractive = 1;
if (*arg == '-' && *(arg + 1) == 'i') {
interractive = 1;
} else if (*arg=='-' && *(arg+1)=='n') {
no_trap = 1;
}
} else if (*arg == '-' && *(arg + 1) == 'n') {
no_trap = 1;
}
}
if (!no_trap) {
init_signals();
init_signals();
}
rc = test_main();
if (interractive) {
char s[10];
puts("");
puts("Press <ENTER> to exit");
if (!fgets(s, sizeof(s), stdin))
return rc;
char s[10];
puts("");
puts("Press <ENTER> to exit");
if (!fgets(s, sizeof(s), stdin))
return rc;
}
return rc;

View File

@ -1,5 +1,5 @@
/*
/*
* !! OIY OIY !!
*
* The purpose of this file is only to get pjlib-util-test linked. I haven't
@ -7,5 +7,4 @@
*
*/
#include "../../pjlib/src/pjlib-test/main_rtems.c"

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
static int decode_test(void)
@ -70,8 +69,8 @@ static int auth_test(void)
* Username).
*/
/* If long term credential is wanted and REALM is not present, server
* must respond with 434 (Missing Realm)
/* If long term credential is wanted and REALM is not present, server
* must respond with 434 (Missing Realm)
*/
/* If REALM doesn't match, server must respond with 434 (Missing Realm)
@ -84,7 +83,7 @@ static int auth_test(void)
*/
/* Simulate 438 (Stale Nonce) */
/* Simulate 436 (Unknown Username) */
/* When server wants to use short term credential, but request has
@ -108,7 +107,6 @@ static int auth_test(void)
return 0;
}
int stun_test(void)
{
decode_verify();
@ -116,4 +114,3 @@ int stun_test(void)
auth_test();
return 0;
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,36 +14,36 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "test.h"
#include <pjlib.h>
#include <pjlib-util.h>
void app_perror(const char *msg, pj_status_t rc)
void app_perror(const char* msg, pj_status_t rc)
{
char errbuf[256];
PJ_CHECK_STACK();
pj_strerror(rc, errbuf, sizeof(errbuf));
PJ_LOG(1,("test", "%s: [pj_status_t=%d] %s", msg, rc, errbuf));
PJ_LOG(1, ("test", "%s: [pj_status_t=%d] %s", msg, rc, errbuf));
}
#define DO_TEST(test) do { \
PJ_LOG(3, ("test", "Running %s...", #test)); \
rc = test; \
PJ_LOG(3, ("test", \
"%s(%d)", \
(char*)(rc ? "..ERROR" : "..success"), rc)); \
if (rc!=0) goto on_return; \
} while (0)
#define DO_TEST(test) \
do { \
PJ_LOG(3, ("test", "Running %s...", #test)); \
rc = test; \
PJ_LOG(3, \
("test", "%s(%d)", (char*)(rc ? "..ERROR" : "..success"), rc)); \
if (rc != 0) \
goto on_return; \
} while (0)
pj_pool_factory *mem;
pj_pool_factory* mem;
int param_log_decor = PJ_LOG_HAS_NEWLINE | PJ_LOG_HAS_TIME |
PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT;
PJ_LOG_HAS_MICRO_SEC | PJ_LOG_HAS_INDENT;
static int test_inner(void)
{
@ -58,15 +57,15 @@ static int test_inner(void)
rc = pj_init();
if (rc != 0) {
app_perror("pj_init() error!!", rc);
return rc;
app_perror("pj_init() error!!", rc);
return rc;
}
rc = pjlib_util_init();
pj_assert(rc == 0);
pj_dump_config();
pj_caching_pool_init( &caching_pool, &pj_pool_factory_default_policy, 0 );
pj_caching_pool_init(&caching_pool, &pj_pool_factory_default_policy, 0);
#if INCLUDE_XML_TEST
DO_TEST(xml_test());
@ -78,9 +77,9 @@ static int test_inner(void)
#if INCLUDE_ENCRYPTION_TEST
DO_TEST(encryption_test());
# if WITH_BENCHMARK
# if WITH_BENCHMARK
DO_TEST(encryption_benchmark());
# endif
# endif
#endif
#if INCLUDE_STUN_TEST
@ -103,16 +102,17 @@ int test_main(void)
{
PJ_USE_EXCEPTION;
PJ_TRY {
PJ_TRY
{
return test_inner();
}
PJ_CATCH_ANY {
PJ_CATCH_ANY
{
int id = PJ_GET_EXCEPTION();
PJ_LOG(3,("test", "FATAL: unhandled exception id %d (%s)",
id, pj_exception_id_name(id)));
PJ_LOG(3, ("test", "FATAL: unhandled exception id %d (%s)", id,
pj_exception_id_name(id)));
}
PJ_END;
return -1;
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,22 +14,22 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pj/types.h>
#if defined(PJ_EXCLUDE_BENCHMARK_TESTS) && (PJ_EXCLUDE_BENCHMARK_TESTS==1)
# define WITH_BENCHMARK 0
#if defined(PJ_EXCLUDE_BENCHMARK_TESTS) && (PJ_EXCLUDE_BENCHMARK_TESTS == 1)
# define WITH_BENCHMARK 0
#else
# define WITH_BENCHMARK 1
# define WITH_BENCHMARK 1
#endif
#define INCLUDE_XML_TEST 1
#define INCLUDE_JSON_TEST 1
#define INCLUDE_ENCRYPTION_TEST 1
#define INCLUDE_STUN_TEST 1
#define INCLUDE_RESOLVER_TEST 1
#define INCLUDE_HTTP_CLIENT_TEST 1
#define INCLUDE_XML_TEST 1
#define INCLUDE_JSON_TEST 1
#define INCLUDE_ENCRYPTION_TEST 1
#define INCLUDE_STUN_TEST 1
#define INCLUDE_RESOLVER_TEST 1
#define INCLUDE_HTTP_CLIENT_TEST 1
extern int xml_test(void);
extern int json_test(void);
@ -41,6 +40,5 @@ extern int test_main(void);
extern int resolver_test(void);
extern int http_client_test();
extern void app_perror(const char *title, pj_status_t rc);
extern pj_pool_factory *mem;
extern void app_perror(const char* title, pj_status_t rc);
extern pj_pool_factory* mem;

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,111 +14,107 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "test.h"
#if INCLUDE_XML_TEST
#include <pjlib-util/xml.h>
#include <pjlib.h>
# include <pjlib-util/xml.h>
# include <pjlib.h>
#define THIS_FILE "xml_test"
# define THIS_FILE "xml_test"
static const char *xml_doc[] =
{
" <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
" <p:pidf-full xmlns=\"urn:ietf:params:xml:ns:pidf\"\n"
" xmlns:p=\"urn:ietf:params:xml:ns:pidf-diff\"\n"
" xmlns:r=\"urn:ietf:params:xml:ns:pidf:rpid\"\n"
" xmlns:c=\"urn:ietf:params:xml:ns:pidf:caps\"\n"
" entity=\"pres:someone@example.com\"\n"
" version=\"567\">\n"
"\n"
" <tuple id=\"sg89ae\">\n"
" <status>\n"
" <basic>open</basic>\n"
" <r:relationship>assistant</r:relationship>\n"
" </status>\n"
" <c:servcaps>\n"
" <c:audio>true</c:audio>\n"
" <c:video>false</c:video>\n"
" <c:message>true</c:message>\n"
" </c:servcaps>\n"
" <contact priority=\"0.8\">tel:09012345678</contact>\n"
" </tuple>\n"
"\n"
" <tuple id=\"cg231jcr\">\n"
" <status>\n"
" <basic>open</basic>\n"
" </status>\n"
" <contact priority=\"1.0\">im:pep@example.com</contact>\n"
" </tuple>\n"
"\n"
" <tuple id=\"r1230d\">\n"
" <status>\n"
" <basic>closed</basic>\n"
" <r:activity>meeting</r:activity>\n"
" </status>\n"
" <r:homepage>http://example.com/~pep/</r:homepage>\n"
" <r:icon>http://example.com/~pep/icon.gif</r:icon>\n"
" <r:card>http://example.com/~pep/card.vcd</r:card>\n"
" <contact priority=\"0.9\">sip:pep@example.com</contact>\n"
" </tuple>\n"
"\n"
" <note xml:lang=\"en\">Full state presence document</note>\n"
"\n"
" <r:person>\n"
" <r:status>\n"
" <r:activities>\n"
" <r:on-the-phone/>\n"
" <r:busy/>\n"
" </r:activities>\n"
" </r:status>\n"
" </r:person>\n"
"\n"
" <r:device id=\"urn:esn:600b40c7\">\n"
" <r:status>\n"
" <c:devcaps>\n"
" <c:mobility>\n"
" <c:supported>\n"
" <c:mobile/>\n"
" </c:supported>\n"
" </c:mobility>\n"
" </c:devcaps>\n"
" </r:status>\n"
" </r:device>\n"
"\n"
" </p:pidf-full>\n"
}
;
static const char* xml_doc[] = {
" <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
" <p:pidf-full xmlns=\"urn:ietf:params:xml:ns:pidf\"\n"
" xmlns:p=\"urn:ietf:params:xml:ns:pidf-diff\"\n"
" xmlns:r=\"urn:ietf:params:xml:ns:pidf:rpid\"\n"
" xmlns:c=\"urn:ietf:params:xml:ns:pidf:caps\"\n"
" entity=\"pres:someone@example.com\"\n"
" version=\"567\">\n"
"\n"
" <tuple id=\"sg89ae\">\n"
" <status>\n"
" <basic>open</basic>\n"
" <r:relationship>assistant</r:relationship>\n"
" </status>\n"
" <c:servcaps>\n"
" <c:audio>true</c:audio>\n"
" <c:video>false</c:video>\n"
" <c:message>true</c:message>\n"
" </c:servcaps>\n"
" <contact priority=\"0.8\">tel:09012345678</contact>\n"
" </tuple>\n"
"\n"
" <tuple id=\"cg231jcr\">\n"
" <status>\n"
" <basic>open</basic>\n"
" </status>\n"
" <contact priority=\"1.0\">im:pep@example.com</contact>\n"
" </tuple>\n"
"\n"
" <tuple id=\"r1230d\">\n"
" <status>\n"
" <basic>closed</basic>\n"
" <r:activity>meeting</r:activity>\n"
" </status>\n"
" <r:homepage>http://example.com/~pep/</r:homepage>\n"
" <r:icon>http://example.com/~pep/icon.gif</r:icon>\n"
" <r:card>http://example.com/~pep/card.vcd</r:card>\n"
" <contact priority=\"0.9\">sip:pep@example.com</contact>\n"
" </tuple>\n"
"\n"
" <note xml:lang=\"en\">Full state presence document</note>\n"
"\n"
" <r:person>\n"
" <r:status>\n"
" <r:activities>\n"
" <r:on-the-phone/>\n"
" <r:busy/>\n"
" </r:activities>\n"
" </r:status>\n"
" </r:person>\n"
"\n"
" <r:device id=\"urn:esn:600b40c7\">\n"
" <r:status>\n"
" <c:devcaps>\n"
" <c:mobility>\n"
" <c:supported>\n"
" <c:mobile/>\n"
" </c:supported>\n"
" </c:mobility>\n"
" </c:devcaps>\n"
" </r:status>\n"
" </r:device>\n"
"\n"
" </p:pidf-full>\n"
};
static int xml_parse_print_test(const char *doc)
static int xml_parse_print_test(const char* doc)
{
pj_str_t msg;
pj_pool_t *pool;
pj_xml_node *root;
char *output;
pj_pool_t* pool;
pj_xml_node* root;
char* output;
int output_len;
pool = pj_pool_create(mem, "xml", 4096, 1024, NULL);
pj_strdup2(pool, &msg, doc);
root = pj_xml_parse(pool, msg.ptr, msg.slen);
if (!root) {
PJ_LOG(1, (THIS_FILE, " Error: unable to parse XML"));
return -10;
PJ_LOG(1, (THIS_FILE, " Error: unable to parse XML"));
return -10;
}
output = (char*)pj_pool_zalloc(pool, msg.slen + 512);
output_len = pj_xml_print(root, output, msg.slen+512, PJ_TRUE);
output_len = pj_xml_print(root, output, msg.slen + 512, PJ_TRUE);
if (output_len < 1) {
PJ_LOG(1, (THIS_FILE, " Error: buffer too small to print XML file"));
return -20;
PJ_LOG(1, (THIS_FILE, " Error: buffer too small to print XML file"));
return -20;
}
output[output_len] = '\0';
pj_pool_release(pool);
return 0;
}
@ -127,19 +122,17 @@ static int xml_parse_print_test(const char *doc)
int xml_test()
{
unsigned i;
for (i=0; i<sizeof(xml_doc)/sizeof(xml_doc[0]); ++i) {
int status;
if ((status=xml_parse_print_test(xml_doc[i])) != 0)
return status;
for (i = 0; i < sizeof(xml_doc) / sizeof(xml_doc[0]); ++i) {
int status;
if ((status = xml_parse_print_test(xml_doc[i])) != 0)
return status;
}
return 0;
}
#else
/* To prevent warning about "translation unit is empty"
* when this test is disabled.
* when this test is disabled.
*/
int dummy_xml_test;
#endif /* INCLUDE_XML_TEST */
#endif /* INCLUDE_XML_TEST */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,116 +14,112 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/base64.h>
#include <pj/assert.h>
#include <pj/errno.h>
#define INV -1
#define PADDING '='
#define INV -1
#define PADDING '='
static const char base64_char[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
static int base256_char(char c)
{
if (c >= 'A' && c <= 'Z')
return (c - 'A');
return (c - 'A');
else if (c >= 'a' && c <= 'z')
return (c - 'a' + 26);
return (c - 'a' + 26);
else if (c >= '0' && c <= '9')
return (c - '0' + 52);
return (c - '0' + 52);
else if (c == '+')
return (62);
return (62);
else if (c == '/')
return (63);
return (63);
else {
/* It *may* happen on bad input, so this is not a good idea.
* pj_assert(!"Should not happen as '=' should have been filtered");
*/
return INV;
/* It *may* happen on bad input, so this is not a good idea.
* pj_assert(!"Should not happen as '=' should have been filtered");
*/
return INV;
}
}
static void base256to64(pj_uint8_t c1, pj_uint8_t c2, pj_uint8_t c3,
int padding, char *output)
static void base256to64(pj_uint8_t c1, pj_uint8_t c2, pj_uint8_t c3,
int padding, char* output)
{
*output++ = base64_char[c1>>2];
*output++ = base64_char[((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4)];
*output++ = base64_char[c1 >> 2];
*output++ = base64_char[((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)];
switch (padding) {
case 0:
*output++ = base64_char[((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6)];
*output = base64_char[c3 & 0x3F];
break;
*output++ = base64_char[((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6)];
*output = base64_char[c3 & 0x3F];
break;
case 1:
*output++ = base64_char[((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6)];
*output = PADDING;
break;
*output++ = base64_char[((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6)];
*output = PADDING;
break;
case 2:
default:
*output++ = PADDING;
*output = PADDING;
break;
*output++ = PADDING;
*output = PADDING;
break;
}
}
PJ_DEF(pj_status_t) pj_base64_encode(const pj_uint8_t *input, int in_len,
char *output, int *out_len)
PJ_DEF(pj_status_t)
pj_base64_encode(const pj_uint8_t* input, int in_len, char* output,
int* out_len)
{
const pj_uint8_t *pi = input;
const pj_uint8_t* pi = input;
pj_uint8_t c1, c2, c3;
int i = 0;
char *po = output;
char* po = output;
PJ_ASSERT_RETURN(input && output && out_len, PJ_EINVAL);
PJ_ASSERT_RETURN(*out_len >= PJ_BASE256_TO_BASE64_LEN(in_len),
PJ_ETOOSMALL);
PJ_ASSERT_RETURN(*out_len >= PJ_BASE256_TO_BASE64_LEN(in_len),
PJ_ETOOSMALL);
while (i < in_len) {
c1 = *pi++;
++i;
c1 = *pi++;
++i;
if (i == in_len) {
base256to64(c1, 0, 0, 2, po);
po += 4;
break;
} else {
c2 = *pi++;
++i;
if (i == in_len) {
base256to64(c1, 0, 0, 2, po);
po += 4;
break;
} else {
c2 = *pi++;
++i;
if (i == in_len) {
base256to64(c1, c2, 0, 1, po);
po += 4;
break;
} else {
c3 = *pi++;
++i;
base256to64(c1, c2, c3, 0, po);
}
}
if (i == in_len) {
base256to64(c1, c2, 0, 1, po);
po += 4;
break;
} else {
c3 = *pi++;
++i;
base256to64(c1, c2, c3, 0, po);
}
}
po += 4;
po += 4;
}
*out_len = (int)(po - output);
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pj_base64_decode(const pj_str_t *input,
pj_uint8_t *out, int *out_len)
PJ_DEF(pj_status_t)
pj_base64_decode(const pj_str_t* input, pj_uint8_t* out, int* out_len)
{
const char *buf;
const char* buf;
int len;
int i, j, k;
int c[4];
@ -133,34 +128,33 @@ PJ_DEF(pj_status_t) pj_base64_decode(const pj_str_t *input,
buf = input->ptr;
len = (int)input->slen;
while (len && buf[len-1] == '=')
--len;
while (len && buf[len - 1] == '=')
--len;
PJ_ASSERT_RETURN(*out_len >= PJ_BASE64_TO_BASE256_LEN(len),
PJ_ETOOSMALL);
PJ_ASSERT_RETURN(*out_len >= PJ_BASE64_TO_BASE256_LEN(len), PJ_ETOOSMALL);
for (i=0, j=0; i<len; ) {
/* Fill up c, silently ignoring invalid characters */
for (k=0; k<4 && i<len; ++k) {
do {
c[k] = base256_char(buf[i++]);
} while (c[k]==INV && i<len);
}
for (i = 0, j = 0; i < len;) {
/* Fill up c, silently ignoring invalid characters */
for (k = 0; k < 4 && i < len; ++k) {
do {
c[k] = base256_char(buf[i++]);
} while (c[k] == INV && i < len);
}
if (k<4) {
if (k > 1) {
out[j++] = (pj_uint8_t)((c[0]<<2) | ((c[1] & 0x30)>>4));
if (k > 2) {
out[j++] = (pj_uint8_t)
(((c[1] & 0x0F)<<4) | ((c[2] & 0x3C)>>2));
}
}
break;
}
if (k < 4) {
if (k > 1) {
out[j++] = (pj_uint8_t)((c[0] << 2) | ((c[1] & 0x30) >> 4));
if (k > 2) {
out[j++] =
(pj_uint8_t)(((c[1] & 0x0F) << 4) | ((c[2] & 0x3C) >> 2));
}
}
break;
}
out[j++] = (pj_uint8_t)((c[0]<<2) | ((c[1] & 0x30)>>4));
out[j++] = (pj_uint8_t)(((c[1] & 0x0F)<<4) | ((c[2] & 0x3C)>>2));
out[j++] = (pj_uint8_t)(((c[2] & 0x03)<<6) | (c[3] & 0x3F));
out[j++] = (pj_uint8_t)((c[0] << 2) | ((c[1] & 0x30) >> 4));
out[j++] = (pj_uint8_t)(((c[1] & 0x0F) << 4) | ((c[2] & 0x3C) >> 2));
out[j++] = (pj_uint8_t)(((c[2] & 0x03) << 6) | (c[3] & 0x3F));
}
pj_assert(j <= *out_len);
@ -168,5 +162,3 @@ PJ_DEF(pj_status_t) pj_base64_decode(const pj_str_t *input,
return PJ_SUCCESS;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,3 @@
/* $Id$ */
/*
* Copyright (C) 2010 Teluu Inc. (http://www.teluu.com)
*
@ -40,34 +39,34 @@ typedef enum out_parse_state
struct cli_console_fe
{
pj_cli_front_end base;
pj_pool_t *pool;
pj_cli_sess *sess;
pj_thread_t *input_thread;
pj_bool_t thread_quit;
pj_sem_t *thread_sem;
pj_cli_console_cfg cfg;
pj_cli_front_end base;
pj_pool_t* pool;
pj_cli_sess* sess;
pj_thread_t* input_thread;
pj_bool_t thread_quit;
pj_sem_t* thread_sem;
pj_cli_console_cfg cfg;
struct async_input_t
{
char *buf;
unsigned maxlen;
pj_sem_t *sem;
char* buf;
unsigned maxlen;
pj_sem_t* sem;
} input;
};
static void console_write_log(pj_cli_front_end *fe, int level,
const char *data, pj_size_t len)
static void console_write_log(pj_cli_front_end* fe, int level, const char* data,
pj_size_t len)
{
struct cli_console_fe * cfe = (struct cli_console_fe *)fe;
struct cli_console_fe* cfe = (struct cli_console_fe*)fe;
if (cfe->sess->log_level > level)
printf("%.*s", (int)len, data);
}
static void console_quit(pj_cli_front_end *fe, pj_cli_sess *req)
static void console_quit(pj_cli_front_end* fe, pj_cli_sess* req)
{
struct cli_console_fe * cfe = (struct cli_console_fe *)fe;
struct cli_console_fe* cfe = (struct cli_console_fe*)fe;
PJ_UNUSED_ARG(req);
@ -79,9 +78,9 @@ static void console_quit(pj_cli_front_end *fe, pj_cli_sess *req)
}
}
static void console_destroy(pj_cli_front_end *fe)
static void console_destroy(pj_cli_front_end* fe)
{
struct cli_console_fe * cfe = (struct cli_console_fe *)fe;
struct cli_console_fe* cfe = (struct cli_console_fe*)fe;
pj_assert(cfe);
console_quit(fe, NULL);
@ -91,7 +90,7 @@ static void console_destroy(pj_cli_front_end *fe)
if (cfe->input_thread) {
pj_thread_destroy(cfe->input_thread);
cfe->input_thread = NULL;
cfe->input_thread = NULL;
}
pj_sem_destroy(cfe->thread_sem);
@ -99,7 +98,7 @@ static void console_destroy(pj_cli_front_end *fe)
pj_pool_release(cfe->pool);
}
PJ_DEF(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param)
PJ_DEF(void) pj_cli_console_cfg_default(pj_cli_console_cfg* param)
{
pj_assert(param);
@ -108,22 +107,21 @@ PJ_DEF(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param)
param->quit_command.slen = 0;
}
PJ_DEF(pj_status_t) pj_cli_console_create(pj_cli_t *cli,
const pj_cli_console_cfg *param,
pj_cli_sess **p_sess,
pj_cli_front_end **p_fe)
PJ_DEF(pj_status_t)
pj_cli_console_create(pj_cli_t* cli, const pj_cli_console_cfg* param,
pj_cli_sess** p_sess, pj_cli_front_end** p_fe)
{
pj_cli_sess *sess;
struct cli_console_fe *fe;
pj_cli_sess* sess;
struct cli_console_fe* fe;
pj_cli_console_cfg cfg;
pj_pool_t *pool;
pj_pool_t* pool;
pj_status_t status;
PJ_ASSERT_RETURN(cli && p_sess, PJ_EINVAL);
pool = pj_pool_create(pj_cli_get_param(cli)->pf, "console_fe",
PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC,
NULL);
pool =
pj_pool_create(pj_cli_get_param(cli)->pf, "console_fe",
PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC, NULL);
if (!pool)
return PJ_ENOMEM;
@ -147,26 +145,26 @@ PJ_DEF(pj_status_t) pj_cli_console_create(pj_cli_t *cli,
fe->sess = sess;
status = pj_sem_create(pool, "console_fe", 0, 1, &fe->thread_sem);
if (status != PJ_SUCCESS)
return status;
return status;
status = pj_sem_create(pool, "console_fe", 0, 1, &fe->input.sem);
if (status != PJ_SUCCESS)
return status;
return status;
pj_cli_register_front_end(cli, &fe->base);
if (param->prompt_str.slen == 0) {
pj_str_t prompt_sign = pj_str(">>> ");
fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool, prompt_sign.slen+1);
pj_strcpy(&fe->cfg.prompt_str, &prompt_sign);
pj_str_t prompt_sign = pj_str(">>> ");
fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool, prompt_sign.slen + 1);
pj_strcpy(&fe->cfg.prompt_str, &prompt_sign);
} else {
fe->cfg.prompt_str.ptr = pj_pool_alloc(fe->pool,
param->prompt_str.slen+1);
pj_strcpy(&fe->cfg.prompt_str, &param->prompt_str);
fe->cfg.prompt_str.ptr =
pj_pool_alloc(fe->pool, param->prompt_str.slen + 1);
pj_strcpy(&fe->cfg.prompt_str, &param->prompt_str);
}
fe->cfg.prompt_str.ptr[fe->cfg.prompt_str.slen] = 0;
if (param->quit_command.slen)
pj_strdup(fe->pool, &fe->cfg.quit_command, &param->quit_command);
pj_strdup(fe->pool, &fe->cfg.quit_command, &param->quit_command);
*p_sess = sess;
if (p_fe)
@ -175,11 +173,11 @@ PJ_DEF(pj_status_t) pj_cli_console_create(pj_cli_t *cli,
return PJ_SUCCESS;
}
static void send_prompt_str(pj_cli_sess *sess)
static void send_prompt_str(pj_cli_sess* sess)
{
pj_str_t send_data;
char data_str[128];
struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe;
struct cli_console_fe* fe = (struct cli_console_fe*)sess->fe;
send_data.ptr = data_str;
send_data.slen = 0;
@ -190,27 +188,25 @@ static void send_prompt_str(pj_cli_sess *sess)
printf("%s", send_data.ptr);
}
static void send_err_arg(pj_cli_sess *sess,
const pj_cli_exec_info *info,
const pj_str_t *msg,
pj_bool_t with_return)
static void send_err_arg(pj_cli_sess* sess, const pj_cli_exec_info* info,
const pj_str_t* msg, pj_bool_t with_return)
{
pj_str_t send_data;
char data_str[256];
pj_size_t len;
unsigned i;
struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe;
struct cli_console_fe* fe = (struct cli_console_fe*)sess->fe;
send_data.ptr = data_str;
send_data.slen = 0;
if (with_return)
pj_strcat2(&send_data, "\r\n");
pj_strcat2(&send_data, "\r\n");
len = fe->cfg.prompt_str.slen + info->err_pos;
for (i=0;i<len;++i) {
pj_strcat2(&send_data, " ");
for (i = 0; i < len; ++i) {
pj_strcat2(&send_data, " ");
}
pj_strcat2(&send_data, "^");
pj_strcat2(&send_data, "\r\n");
@ -221,146 +217,143 @@ static void send_err_arg(pj_cli_sess *sess,
printf("%s", send_data.ptr);
}
static void send_inv_arg(pj_cli_sess *sess,
const pj_cli_exec_info *info,
pj_bool_t with_return)
static void send_inv_arg(pj_cli_sess* sess, const pj_cli_exec_info* info,
pj_bool_t with_return)
{
static const pj_str_t ERR_MSG = {"%Error : Invalid Arguments\r\n", 28};
static const pj_str_t ERR_MSG = { "%Error : Invalid Arguments\r\n", 28 };
send_err_arg(sess, info, &ERR_MSG, with_return);
}
static void send_too_many_arg(pj_cli_sess *sess,
const pj_cli_exec_info *info,
pj_bool_t with_return)
static void send_too_many_arg(pj_cli_sess* sess, const pj_cli_exec_info* info,
pj_bool_t with_return)
{
static const pj_str_t ERR_MSG = {"%Error : Too Many Arguments\r\n", 29};
static const pj_str_t ERR_MSG = { "%Error : Too Many Arguments\r\n", 29 };
send_err_arg(sess, info, &ERR_MSG, with_return);
}
static void send_hint_arg(pj_str_t *send_data,
const pj_str_t *desc,
pj_ssize_t cmd_len,
pj_ssize_t max_len)
static void send_hint_arg(pj_str_t* send_data, const pj_str_t* desc,
pj_ssize_t cmd_len, pj_ssize_t max_len)
{
if ((desc) && (desc->slen > 0)) {
int j;
int j;
for (j=0;j<(max_len-cmd_len);++j) {
pj_strcat2(send_data, " ");
}
pj_strcat2(send_data, " ");
pj_strcat(send_data, desc);
send_data->ptr[send_data->slen] = 0;
printf("%s", send_data->ptr);
send_data->slen = 0;
for (j = 0; j < (max_len - cmd_len); ++j) {
pj_strcat2(send_data, " ");
}
pj_strcat2(send_data, " ");
pj_strcat(send_data, desc);
send_data->ptr[send_data->slen] = 0;
printf("%s", send_data->ptr);
send_data->slen = 0;
}
}
static void send_ambi_arg(pj_cli_sess *sess,
const pj_cli_exec_info *info,
pj_bool_t with_return)
static void send_ambi_arg(pj_cli_sess* sess, const pj_cli_exec_info* info,
pj_bool_t with_return)
{
unsigned i;
pj_size_t len;
pj_str_t send_data;
char data[1028];
struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe;
const pj_cli_hint_info *hint = info->hint;
struct cli_console_fe* fe = (struct cli_console_fe*)sess->fe;
const pj_cli_hint_info* hint = info->hint;
out_parse_state parse_state = OP_NORMAL;
pj_ssize_t max_length = 0;
pj_ssize_t cmd_length = 0;
static const pj_str_t sc_type = {"sc", 2};
static const pj_str_t choice_type = {"choice", 6};
static const pj_str_t sc_type = { "sc", 2 };
static const pj_str_t choice_type = { "choice", 6 };
send_data.ptr = data;
send_data.slen = 0;
if (with_return)
pj_strcat2(&send_data, "\r\n");
pj_strcat2(&send_data, "\r\n");
len = fe->cfg.prompt_str.slen + info->err_pos;
for (i=0;i<len;++i) {
pj_strcat2(&send_data, " ");
for (i = 0; i < len; ++i) {
pj_strcat2(&send_data, " ");
}
pj_strcat2(&send_data, "^");
/* Get the max length of the command name */
for (i=0;i<info->hint_cnt;++i) {
if (hint[i].type.slen > 0) {
if (pj_stricmp(&hint[i].type, &sc_type) == 0) {
if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) {
cmd_length += (hint[i].name.slen + 3);
} else {
cmd_length = hint[i].name.slen;
}
} else {
cmd_length = hint[i].name.slen;
}
} else {
cmd_length = hint[i].name.slen;
}
for (i = 0; i < info->hint_cnt; ++i) {
if (hint[i].type.slen > 0) {
if (pj_stricmp(&hint[i].type, &sc_type) == 0) {
if ((i > 0) && (!pj_stricmp(&hint[i - 1].desc, &hint[i].desc)))
{
cmd_length += (hint[i].name.slen + 3);
} else {
cmd_length = hint[i].name.slen;
}
} else {
cmd_length = hint[i].name.slen;
}
} else {
cmd_length = hint[i].name.slen;
}
if (cmd_length > max_length) {
max_length = cmd_length;
}
if (cmd_length > max_length) {
max_length = cmd_length;
}
}
cmd_length = 0;
for (i=0;i<info->hint_cnt;++i) {
if (hint[i].type.slen > 0) {
if (pj_stricmp(&hint[i].type, &sc_type) == 0) {
parse_state = OP_SHORTCUT;
} else if (pj_stricmp(&hint[i].type, &choice_type) == 0) {
parse_state = OP_CHOICE;
} else {
parse_state = OP_TYPE;
}
} else {
parse_state = OP_NORMAL;
}
for (i = 0; i < info->hint_cnt; ++i) {
if (hint[i].type.slen > 0) {
if (pj_stricmp(&hint[i].type, &sc_type) == 0) {
parse_state = OP_SHORTCUT;
} else if (pj_stricmp(&hint[i].type, &choice_type) == 0) {
parse_state = OP_CHOICE;
} else {
parse_state = OP_TYPE;
}
} else {
parse_state = OP_NORMAL;
}
if (parse_state != OP_SHORTCUT) {
pj_strcat2(&send_data, "\r\n ");
cmd_length = hint[i].name.slen;
}
if (parse_state != OP_SHORTCUT) {
pj_strcat2(&send_data, "\r\n ");
cmd_length = hint[i].name.slen;
}
switch (parse_state) {
case OP_CHOICE:
pj_strcat2(&send_data, "[");
pj_strcat(&send_data, &hint[i].name);
pj_strcat2(&send_data, "]");
break;
case OP_TYPE:
pj_strcat2(&send_data, "<");
pj_strcat(&send_data, &hint[i].type);
pj_strcat2(&send_data, ">");
break;
case OP_SHORTCUT:
/* Format : "Command | sc | description" */
{
cmd_length += hint[i].name.slen;
if ((i > 0) && (!pj_stricmp(&hint[i-1].desc, &hint[i].desc))) {
pj_strcat2(&send_data, " | ");
cmd_length += 3;
} else {
pj_strcat2(&send_data, "\r\n ");
}
pj_strcat(&send_data, &hint[i].name);
}
break;
default:
pj_strcat(&send_data, &hint[i].name);
break;
}
switch (parse_state) {
case OP_CHOICE:
pj_strcat2(&send_data, "[");
pj_strcat(&send_data, &hint[i].name);
pj_strcat2(&send_data, "]");
break;
case OP_TYPE:
pj_strcat2(&send_data, "<");
pj_strcat(&send_data, &hint[i].type);
pj_strcat2(&send_data, ">");
break;
case OP_SHORTCUT:
/* Format : "Command | sc | description" */
{
cmd_length += hint[i].name.slen;
if ((i > 0) && (!pj_stricmp(&hint[i - 1].desc, &hint[i].desc)))
{
pj_strcat2(&send_data, " | ");
cmd_length += 3;
} else {
pj_strcat2(&send_data, "\r\n ");
}
pj_strcat(&send_data, &hint[i].name);
}
break;
default:
pj_strcat(&send_data, &hint[i].name);
break;
}
if ((parse_state == OP_TYPE) || (parse_state == OP_CHOICE) ||
((i+1) >= info->hint_cnt) ||
(pj_strncmp(&hint[i].desc, &hint[i+1].desc, hint[i].desc.slen)))
{
/* Add description info */
send_hint_arg(&send_data, &hint[i].desc, cmd_length, max_length);
if ((parse_state == OP_TYPE) || (parse_state == OP_CHOICE) ||
((i + 1) >= info->hint_cnt) ||
(pj_strncmp(&hint[i].desc, &hint[i + 1].desc, hint[i].desc.slen)))
{
/* Add description info */
send_hint_arg(&send_data, &hint[i].desc, cmd_length, max_length);
cmd_length = 0;
}
cmd_length = 0;
}
}
pj_strcat2(&send_data, "\r\n");
pj_strcat(&send_data, &fe->cfg.prompt_str);
@ -368,150 +361,148 @@ static void send_ambi_arg(pj_cli_sess *sess,
printf("%s", send_data.ptr);
}
static pj_bool_t handle_hint(pj_cli_sess *sess)
static pj_bool_t handle_hint(pj_cli_sess* sess)
{
pj_status_t status;
pj_bool_t retval = PJ_TRUE;
pj_pool_t *pool;
pj_cli_cmd_val *cmd_val;
pj_pool_t* pool;
pj_cli_cmd_val* cmd_val;
pj_cli_exec_info info;
struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe;
char *recv_buf = fe->input.buf;
pj_cli_t *cli = sess->fe->cli;
struct cli_console_fe* fe = (struct cli_console_fe*)sess->fe;
char* recv_buf = fe->input.buf;
pj_cli_t* cli = sess->fe->cli;
pool = pj_pool_create(pj_cli_get_param(cli)->pf, "handle_hint",
PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC,
NULL);
pool =
pj_pool_create(pj_cli_get_param(cli)->pf, "handle_hint",
PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC, NULL);
cmd_val = PJ_POOL_ZALLOC_T(pool, pj_cli_cmd_val);
status = pj_cli_sess_parse(sess, recv_buf, cmd_val,
pool, &info);
status = pj_cli_sess_parse(sess, recv_buf, cmd_val, pool, &info);
switch (status) {
case PJ_CLI_EINVARG:
send_inv_arg(sess, &info, PJ_TRUE);
break;
send_inv_arg(sess, &info, PJ_TRUE);
break;
case PJ_CLI_ETOOMANYARGS:
send_too_many_arg(sess, &info, PJ_TRUE);
break;
send_too_many_arg(sess, &info, PJ_TRUE);
break;
case PJ_CLI_EMISSINGARG:
case PJ_CLI_EAMBIGUOUS:
send_ambi_arg(sess, &info, PJ_TRUE);
break;
send_ambi_arg(sess, &info, PJ_TRUE);
break;
case PJ_SUCCESS:
if (info.hint_cnt > 0) {
/* Compelete command */
send_ambi_arg(sess, &info, PJ_TRUE);
} else {
retval = PJ_FALSE;
}
break;
if (info.hint_cnt > 0) {
/* Compelete command */
send_ambi_arg(sess, &info, PJ_TRUE);
} else {
retval = PJ_FALSE;
}
break;
}
pj_pool_release(pool);
return retval;
}
static pj_bool_t handle_exec(pj_cli_sess *sess)
static pj_bool_t handle_exec(pj_cli_sess* sess)
{
pj_status_t status;
pj_bool_t retval = PJ_TRUE;
pj_pool_t *pool;
pj_pool_t* pool;
pj_cli_exec_info info;
pj_cli_t *cli = sess->fe->cli;
struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe;
char *recv_buf = fe->input.buf;
pj_cli_t* cli = sess->fe->cli;
struct cli_console_fe* fe = (struct cli_console_fe*)sess->fe;
char* recv_buf = fe->input.buf;
printf("\r\n");
pool = pj_pool_create(pj_cli_get_param(cli)->pf, "handle_exec",
PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC,
NULL);
pool =
pj_pool_create(pj_cli_get_param(cli)->pf, "handle_exec",
PJ_CLI_CONSOLE_POOL_SIZE, PJ_CLI_CONSOLE_POOL_INC, NULL);
status = pj_cli_sess_exec(sess, recv_buf,
pool, &info);
status = pj_cli_sess_exec(sess, recv_buf, pool, &info);
switch (status) {
case PJ_CLI_EINVARG:
send_inv_arg(sess, &info, PJ_FALSE);
break;
send_inv_arg(sess, &info, PJ_FALSE);
break;
case PJ_CLI_ETOOMANYARGS:
send_too_many_arg(sess, &info, PJ_FALSE);
break;
send_too_many_arg(sess, &info, PJ_FALSE);
break;
case PJ_CLI_EAMBIGUOUS:
case PJ_CLI_EMISSINGARG:
send_ambi_arg(sess, &info, PJ_FALSE);
break;
send_ambi_arg(sess, &info, PJ_FALSE);
break;
case PJ_CLI_EEXIT:
retval = PJ_FALSE;
break;
retval = PJ_FALSE;
break;
case PJ_SUCCESS:
send_prompt_str(sess);
break;
send_prompt_str(sess);
break;
}
pj_pool_release(pool);
return retval;
}
static int readline_thread(void * p)
static int readline_thread(void* p)
{
struct cli_console_fe * fe = (struct cli_console_fe *)p;
struct cli_console_fe* fe = (struct cli_console_fe*)p;
printf("%s", fe->cfg.prompt_str.ptr);
while (!fe->thread_quit) {
pj_size_t input_len = 0;
pj_str_t input_str;
char *recv_buf = fe->input.buf;
pj_bool_t is_valid = PJ_TRUE;
pj_size_t input_len = 0;
pj_str_t input_str;
char* recv_buf = fe->input.buf;
pj_bool_t is_valid = PJ_TRUE;
if (fgets(recv_buf, fe->input.maxlen, stdin) == NULL) {
/*
* Be friendly to users who redirect commands into
* program, when file ends, resume with kbd.
* If exit is desired end script with q for quit
*/
/* Reopen stdin/stdout/stderr to /dev/console */
#if ((defined(PJ_WIN32) && PJ_WIN32!=0) || \
(defined(PJ_WIN64) && PJ_WIN64!=0)) && \
(!defined(PJ_WIN32_WINCE) || PJ_WIN32_WINCE==0)
if (freopen ("CONIN$", "r", stdin) == NULL) {
if (fgets(recv_buf, fe->input.maxlen, stdin) == NULL) {
/*
* Be friendly to users who redirect commands into
* program, when file ends, resume with kbd.
* If exit is desired end script with q for quit
*/
/* Reopen stdin/stdout/stderr to /dev/console */
#if ((defined(PJ_WIN32) && PJ_WIN32 != 0) || \
(defined(PJ_WIN64) && PJ_WIN64 != 0)) && \
(!defined(PJ_WIN32_WINCE) || PJ_WIN32_WINCE == 0)
if (freopen("CONIN$", "r", stdin) == NULL) {
#else
if (1) {
if (1) {
#endif
puts("Cannot switch back to console from file redirection");
if (fe->cfg.quit_command.slen) {
pj_memcpy(recv_buf, fe->cfg.quit_command.ptr,
fe->input.maxlen);
}
recv_buf[fe->cfg.quit_command.slen] = '\0';
} else {
puts("Switched back to console from file redirection");
continue;
}
}
puts("Cannot switch back to console from file redirection");
if (fe->cfg.quit_command.slen) {
pj_memcpy(recv_buf, fe->cfg.quit_command.ptr,
fe->input.maxlen);
}
recv_buf[fe->cfg.quit_command.slen] = '\0';
} else {
puts("Switched back to console from file redirection");
continue;
}
}
input_str.ptr = recv_buf;
input_str.slen = pj_ansi_strlen(recv_buf);
pj_strrtrim(&input_str);
recv_buf[input_str.slen] = '\n';
recv_buf[input_str.slen+1] = 0;
if (fe->thread_quit) {
break;
}
input_len = pj_ansi_strlen(fe->input.buf);
if ((input_len > 1) && (fe->input.buf[input_len-2] == '?')) {
fe->input.buf[input_len-1] = 0;
is_valid = handle_hint(fe->sess);
if (!is_valid)
printf("%s", fe->cfg.prompt_str.ptr);
} else {
is_valid = handle_exec(fe->sess);
}
input_str.ptr = recv_buf;
input_str.slen = pj_ansi_strlen(recv_buf);
pj_strrtrim(&input_str);
recv_buf[input_str.slen] = '\n';
recv_buf[input_str.slen + 1] = 0;
if (fe->thread_quit) {
break;
}
input_len = pj_ansi_strlen(fe->input.buf);
if ((input_len > 1) && (fe->input.buf[input_len - 2] == '?')) {
fe->input.buf[input_len - 1] = 0;
is_valid = handle_hint(fe->sess);
if (!is_valid)
printf("%s", fe->cfg.prompt_str.ptr);
} else {
is_valid = handle_exec(fe->sess);
}
pj_sem_post(fe->input.sem);
pj_sem_wait(fe->thread_sem);
@ -520,11 +511,10 @@ static int readline_thread(void * p)
return 0;
}
PJ_DEF(pj_status_t) pj_cli_console_process(pj_cli_sess *sess,
char *buf,
unsigned maxlen)
PJ_DEF(pj_status_t)
pj_cli_console_process(pj_cli_sess* sess, char* buf, unsigned maxlen)
{
struct cli_console_fe *fe = (struct cli_console_fe *)sess->fe;
struct cli_console_fe* fe = (struct cli_console_fe*)sess->fe;
PJ_ASSERT_RETURN(sess, PJ_EINVAL);
@ -534,8 +524,8 @@ PJ_DEF(pj_status_t) pj_cli_console_process(pj_cli_sess *sess,
if (!fe->input_thread) {
pj_status_t status;
status = pj_thread_create(fe->pool, NULL, &readline_thread, fe,
0, 0, &fe->input_thread);
status = pj_thread_create(fe->pool, NULL, &readline_thread, fe, 0, 0,
&fe->input_thread);
if (status != PJ_SUCCESS)
return status;
} else {
@ -545,5 +535,5 @@ PJ_DEF(pj_status_t) pj_cli_console_process(pj_cli_sess *sess,
pj_sem_wait(fe->input.sem);
return (pj_cli_is_quitting(fe->base.cli)? PJ_CLI_EEXIT : PJ_SUCCESS);
return (pj_cli_is_quitting(fe->base.cli) ? PJ_CLI_EEXIT : PJ_SUCCESS);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,5 @@
/* $Id$ */
/*
* This is an implementation of CRC32. See ISO 3309 and ITU-T V.42
* This is an implementation of CRC32. See ISO 3309 and ITU-T V.42
* for a formal specification
*
* This file is partly taken from Crypto++ library (http://www.cryptopp.com)
@ -11,18 +10,17 @@
*/
#include <pjlib-util/crc32.h>
#define CRC32_NEGL 0xffffffffL
#define CRC32_NEGL 0xffffffffL
#if defined(PJ_CRC32_HAS_TABLES) && PJ_CRC32_HAS_TABLES!=0
#if defined(PJ_CRC32_HAS_TABLES) && PJ_CRC32_HAS_TABLES != 0
// crc.cpp - written and placed in the public domain by Wei Dai
/* Table of CRC-32's of all single byte values (made by makecrc.c) */
#if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN != 0
# if defined(PJ_IS_LITTLE_ENDIAN) && PJ_IS_LITTLE_ENDIAN != 0
#define CRC32_INDEX(c) (c & 0xff)
#define CRC32_SHIFTED(c) (c >> 8)
#define CRC32_SWAP(c) (c)
# define CRC32_INDEX(c) (c & 0xff)
# define CRC32_SHIFTED(c) (c >> 8)
# define CRC32_SWAP(c) (c)
static const pj_uint32_t crc_tab[] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
@ -79,14 +77,12 @@ static const pj_uint32_t crc_tab[] = {
0x2d02ef8dL
};
#elif defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN != 0
#define CRC32_INDEX(c) (c >> 24)
#define CRC32_SHIFTED(c) (c << 8)
#define CRC32_SWAP(c) ((((c) & 0xff000000) >> 24) | \
(((c) & 0x00ff0000) >> 8) | \
(((c) & 0x0000ff00) << 8) | \
(((c) & 0x000000ff) << 24))
# elif defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN != 0
# define CRC32_INDEX(c) (c >> 24)
# define CRC32_SHIFTED(c) (c << 8)
# define CRC32_SWAP(c) \
((((c)&0xff000000) >> 24) | (((c)&0x00ff0000) >> 8) | \
(((c)&0x0000ff00) << 8) | (((c)&0x000000ff) << 24))
static const pj_uint32_t crc_tab[] = {
0x00000000L, 0x96300777L, 0x2c610eeeL, 0xba510999L, 0x19c46d07L,
@ -143,38 +139,36 @@ static const pj_uint32_t crc_tab[] = {
0x8def022dL
};
#else
# error "Endianness not defined"
#endif
# else
# error "Endianness not defined"
# endif
PJ_DEF(void) pj_crc32_init(pj_crc32_context *ctx)
PJ_DEF(void) pj_crc32_init(pj_crc32_context* ctx)
{
ctx->crc_state = 0;
}
PJ_DEF(pj_uint32_t) pj_crc32_update(pj_crc32_context *ctx,
const pj_uint8_t *data,
pj_size_t nbytes)
PJ_DEF(pj_uint32_t)
pj_crc32_update(pj_crc32_context* ctx, const pj_uint8_t* data, pj_size_t nbytes)
{
pj_uint32_t crc = ctx->crc_state ^ CRC32_NEGL;
for( ; (((unsigned long)(pj_ssize_t)data) & 0x03) && nbytes > 0; --nbytes) {
crc = crc_tab[CRC32_INDEX(crc) ^ *data++] ^ CRC32_SHIFTED(crc);
for (; (((unsigned long)(pj_ssize_t)data) & 0x03) && nbytes > 0; --nbytes) {
crc = crc_tab[CRC32_INDEX(crc) ^ *data++] ^ CRC32_SHIFTED(crc);
}
while (nbytes >= 4) {
crc ^= *(const pj_uint32_t *)data;
crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
nbytes -= 4;
data += 4;
crc ^= *(const pj_uint32_t*)data;
crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
crc = crc_tab[CRC32_INDEX(crc)] ^ CRC32_SHIFTED(crc);
nbytes -= 4;
data += 4;
}
while (nbytes--) {
crc = crc_tab[CRC32_INDEX(crc) ^ *data++] ^ CRC32_SHIFTED(crc);
crc = crc_tab[CRC32_INDEX(crc) ^ *data++] ^ CRC32_SHIFTED(crc);
}
ctx->crc_state = crc ^ CRC32_NEGL;
@ -182,47 +176,43 @@ PJ_DEF(pj_uint32_t) pj_crc32_update(pj_crc32_context *ctx,
return ctx->crc_state;
}
PJ_DEF(pj_uint32_t) pj_crc32_final(pj_crc32_context *ctx)
PJ_DEF(pj_uint32_t) pj_crc32_final(pj_crc32_context* ctx)
{
return CRC32_SWAP(ctx->crc_state);
}
#else
PJ_DEF(void) pj_crc32_init(pj_crc32_context *ctx)
PJ_DEF(void) pj_crc32_init(pj_crc32_context* ctx)
{
ctx->crc_state = CRC32_NEGL;
}
PJ_DEF(pj_uint32_t) pj_crc32_update(pj_crc32_context *ctx,
const pj_uint8_t *octets,
pj_size_t len)
PJ_DEF(pj_uint32_t)
pj_crc32_update(pj_crc32_context* ctx, const pj_uint8_t* octets, pj_size_t len)
{
pj_uint32_t crc = ctx->crc_state;
while (len--) {
pj_uint32_t temp;
int j;
temp = (pj_uint32_t)((crc & 0xFF) ^ *octets++);
for (j = 0; j < 8; j++)
{
if (temp & 0x1)
temp = (temp >> 1) ^ 0xEDB88320;
else
temp >>= 1;
}
crc = (crc >> 8) ^ temp;
while (len--) {
pj_uint32_t temp;
int j;
temp = (pj_uint32_t)((crc & 0xFF) ^ *octets++);
for (j = 0; j < 8; j++) {
if (temp & 0x1)
temp = (temp >> 1) ^ 0xEDB88320;
else
temp >>= 1;
}
crc = (crc >> 8) ^ temp;
}
ctx->crc_state = crc;
return crc ^ CRC32_NEGL;
}
PJ_DEF(pj_uint32_t) pj_crc32_final(pj_crc32_context *ctx)
PJ_DEF(pj_uint32_t) pj_crc32_final(pj_crc32_context* ctx)
{
ctx->crc_state ^= CRC32_NEGL;
return ctx->crc_state;
@ -230,9 +220,7 @@ PJ_DEF(pj_uint32_t) pj_crc32_final(pj_crc32_context *ctx)
#endif
PJ_DEF(pj_uint32_t) pj_crc32_calc( const pj_uint8_t *data,
pj_size_t nbytes)
PJ_DEF(pj_uint32_t) pj_crc32_calc(const pj_uint8_t* data, pj_size_t nbytes)
{
pj_crc32_context ctx;
@ -240,4 +228,3 @@ PJ_DEF(pj_uint32_t) pj_crc32_calc( const pj_uint8_t *data,
pj_crc32_update(&ctx, data, nbytes);
return pj_crc32_final(&ctx);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,180 +14,171 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/dns.h>
#include <pj/assert.h>
#include <pj/log.h>
#include <pj/string.h>
#define THIS_FILE "dns_dump.c"
#define LEVEL 3
#define THIS_FILE "dns_dump.c"
#define LEVEL 3
static const char *spell_ttl(char *buf, int size, unsigned ttl)
static const char* spell_ttl(char* buf, int size, unsigned ttl)
{
#define DAY (3600*24)
#define HOUR (3600)
#define MINUTE (60)
#define DAY (3600 * 24)
#define HOUR (3600)
#define MINUTE (60)
char *p = buf;
char* p = buf;
int len;
if (ttl > DAY) {
len = pj_ansi_snprintf(p, size, "%dd ", ttl/DAY);
if (len < 1 || len >= size)
return "-err-";
size -= len;
p += len;
ttl %= DAY;
len = pj_ansi_snprintf(p, size, "%dd ", ttl / DAY);
if (len < 1 || len >= size)
return "-err-";
size -= len;
p += len;
ttl %= DAY;
}
if (ttl > HOUR) {
len = pj_ansi_snprintf(p, size, "%dh ", ttl/HOUR);
if (len < 1 || len >= size)
return "-err-";
size -= len;
p += len;
ttl %= HOUR;
len = pj_ansi_snprintf(p, size, "%dh ", ttl / HOUR);
if (len < 1 || len >= size)
return "-err-";
size -= len;
p += len;
ttl %= HOUR;
}
if (ttl > MINUTE) {
len = pj_ansi_snprintf(p, size, "%dm ", ttl/MINUTE);
if (len < 1 || len >= size)
return "-err-";
size -= len;
p += len;
ttl %= MINUTE;
len = pj_ansi_snprintf(p, size, "%dm ", ttl / MINUTE);
if (len < 1 || len >= size)
return "-err-";
size -= len;
p += len;
ttl %= MINUTE;
}
if (ttl > 0) {
len = pj_ansi_snprintf(p, size, "%ds ", ttl);
if (len < 1 || len >= size)
return "-err-";
size -= len;
p += len;
ttl = 0;
len = pj_ansi_snprintf(p, size, "%ds ", ttl);
if (len < 1 || len >= size)
return "-err-";
size -= len;
p += len;
ttl = 0;
}
*p = '\0';
return buf;
}
static void dump_query(unsigned index, const pj_dns_parsed_query *q)
static void dump_query(unsigned index, const pj_dns_parsed_query* q)
{
PJ_LOG(3,(THIS_FILE, " %d. Name: %.*s",
index, (int)q->name.slen, q->name.ptr));
PJ_LOG(3,(THIS_FILE, " Type: %s (%d)",
pj_dns_get_type_name(q->type), q->type));
PJ_LOG(3,(THIS_FILE, " Class: %s (%d)",
(q->dnsclass==1 ? "IN" : "<Unknown>"), q->dnsclass));
PJ_LOG(
3, (THIS_FILE, " %d. Name: %.*s", index, (int)q->name.slen, q->name.ptr));
PJ_LOG(3, (THIS_FILE, " Type: %s (%d)", pj_dns_get_type_name(q->type),
q->type));
PJ_LOG(3, (THIS_FILE, " Class: %s (%d)",
(q->dnsclass == 1 ? "IN" : "<Unknown>"), q->dnsclass));
}
static void dump_answer(unsigned index, const pj_dns_parsed_rr *rr)
static void dump_answer(unsigned index, const pj_dns_parsed_rr* rr)
{
const pj_str_t root_name = { "<Root>", 6 };
const pj_str_t *name = &rr->name;
const pj_str_t* name = &rr->name;
char ttl_words[32];
char addr[PJ_INET6_ADDRSTRLEN];
if (name->slen == 0)
name = &root_name;
name = &root_name;
PJ_LOG(3,(THIS_FILE, " %d. %s record (type=%d)",
index, pj_dns_get_type_name(rr->type),
rr->type));
PJ_LOG(3,(THIS_FILE, " Name: %.*s", (int)name->slen, name->ptr));
PJ_LOG(3,(THIS_FILE, " TTL: %u (%s)", rr->ttl,
spell_ttl(ttl_words, sizeof(ttl_words), rr->ttl)));
PJ_LOG(3,(THIS_FILE, " Data length: %u", rr->rdlength));
PJ_LOG(3, (THIS_FILE, " %d. %s record (type=%d)", index,
pj_dns_get_type_name(rr->type), rr->type));
PJ_LOG(3, (THIS_FILE, " Name: %.*s", (int)name->slen, name->ptr));
PJ_LOG(3, (THIS_FILE, " TTL: %u (%s)", rr->ttl,
spell_ttl(ttl_words, sizeof(ttl_words), rr->ttl)));
PJ_LOG(3, (THIS_FILE, " Data length: %u", rr->rdlength));
if (rr->type == PJ_DNS_TYPE_SRV) {
PJ_LOG(3,(THIS_FILE, " SRV: prio=%d, weight=%d %.*s:%d",
rr->rdata.srv.prio, rr->rdata.srv.weight,
(int)rr->rdata.srv.target.slen,
rr->rdata.srv.target.ptr,
rr->rdata.srv.port));
} else if (rr->type == PJ_DNS_TYPE_CNAME ||
rr->type == PJ_DNS_TYPE_NS ||
rr->type == PJ_DNS_TYPE_PTR)
PJ_LOG(3, (THIS_FILE, " SRV: prio=%d, weight=%d %.*s:%d",
rr->rdata.srv.prio, rr->rdata.srv.weight,
(int)rr->rdata.srv.target.slen, rr->rdata.srv.target.ptr,
rr->rdata.srv.port));
} else if (rr->type == PJ_DNS_TYPE_CNAME || rr->type == PJ_DNS_TYPE_NS ||
rr->type == PJ_DNS_TYPE_PTR)
{
PJ_LOG(3,(THIS_FILE, " Name: %.*s",
(int)rr->rdata.cname.name.slen,
rr->rdata.cname.name.ptr));
PJ_LOG(3, (THIS_FILE, " Name: %.*s", (int)rr->rdata.cname.name.slen,
rr->rdata.cname.name.ptr));
} else if (rr->type == PJ_DNS_TYPE_A) {
PJ_LOG(3,(THIS_FILE, " IP address: %s",
pj_inet_ntop2(pj_AF_INET(), &rr->rdata.a.ip_addr,
addr, sizeof(addr))));
PJ_LOG(3, (THIS_FILE, " IP address: %s",
pj_inet_ntop2(pj_AF_INET(), &rr->rdata.a.ip_addr, addr,
sizeof(addr))));
} else if (rr->type == PJ_DNS_TYPE_AAAA) {
PJ_LOG(3,(THIS_FILE, " IPv6 address: %s",
pj_inet_ntop2(pj_AF_INET6(), &rr->rdata.aaaa.ip_addr,
addr, sizeof(addr))));
PJ_LOG(3, (THIS_FILE, " IPv6 address: %s",
pj_inet_ntop2(pj_AF_INET6(), &rr->rdata.aaaa.ip_addr, addr,
sizeof(addr))));
}
}
PJ_DEF(void) pj_dns_dump_packet(const pj_dns_parsed_packet *res)
PJ_DEF(void) pj_dns_dump_packet(const pj_dns_parsed_packet* res)
{
unsigned i;
PJ_ASSERT_ON_FAIL(res != NULL, return);
PJ_ASSERT_ON_FAIL(res != NULL, return );
/* Header part */
PJ_LOG(3,(THIS_FILE, "Domain Name System packet (%s):",
(PJ_DNS_GET_QR(res->hdr.flags) ? "response" : "query")));
PJ_LOG(3,(THIS_FILE, " Transaction ID: %d", res->hdr.id));
PJ_LOG(3,(THIS_FILE,
" Flags: opcode=%d, authoritative=%d, truncated=%d, rcode=%d",
PJ_DNS_GET_OPCODE(res->hdr.flags),
PJ_DNS_GET_AA(res->hdr.flags),
PJ_DNS_GET_TC(res->hdr.flags),
PJ_DNS_GET_RCODE(res->hdr.flags)));
PJ_LOG(3,(THIS_FILE, " Nb of queries: %d", res->hdr.qdcount));
PJ_LOG(3,(THIS_FILE, " Nb of answer RR: %d", res->hdr.anscount));
PJ_LOG(3,(THIS_FILE, " Nb of authority RR: %d", res->hdr.nscount));
PJ_LOG(3,(THIS_FILE, " Nb of additional RR: %d", res->hdr.arcount));
PJ_LOG(3,(THIS_FILE, ""));
PJ_LOG(3, (THIS_FILE, "Domain Name System packet (%s):",
(PJ_DNS_GET_QR(res->hdr.flags) ? "response" : "query")));
PJ_LOG(3, (THIS_FILE, " Transaction ID: %d", res->hdr.id));
PJ_LOG(
3,
(THIS_FILE, " Flags: opcode=%d, authoritative=%d, truncated=%d, rcode=%d",
PJ_DNS_GET_OPCODE(res->hdr.flags), PJ_DNS_GET_AA(res->hdr.flags),
PJ_DNS_GET_TC(res->hdr.flags), PJ_DNS_GET_RCODE(res->hdr.flags)));
PJ_LOG(3, (THIS_FILE, " Nb of queries: %d", res->hdr.qdcount));
PJ_LOG(3, (THIS_FILE, " Nb of answer RR: %d", res->hdr.anscount));
PJ_LOG(3, (THIS_FILE, " Nb of authority RR: %d", res->hdr.nscount));
PJ_LOG(3, (THIS_FILE, " Nb of additional RR: %d", res->hdr.arcount));
PJ_LOG(3, (THIS_FILE, ""));
/* Dump queries */
if (res->hdr.qdcount) {
PJ_LOG(3,(THIS_FILE, " Queries:"));
PJ_LOG(3, (THIS_FILE, " Queries:"));
for (i=0; i<res->hdr.qdcount; ++i) {
dump_query(i, &res->q[i]);
}
PJ_LOG(3,(THIS_FILE, ""));
for (i = 0; i < res->hdr.qdcount; ++i) {
dump_query(i, &res->q[i]);
}
PJ_LOG(3, (THIS_FILE, ""));
}
/* Dump answers */
if (res->hdr.anscount) {
PJ_LOG(3,(THIS_FILE, " Answers RR:"));
PJ_LOG(3, (THIS_FILE, " Answers RR:"));
for (i=0; i<res->hdr.anscount; ++i) {
dump_answer(i, &res->ans[i]);
}
PJ_LOG(3,(THIS_FILE, ""));
for (i = 0; i < res->hdr.anscount; ++i) {
dump_answer(i, &res->ans[i]);
}
PJ_LOG(3, (THIS_FILE, ""));
}
/* Dump NS sections */
if (res->hdr.nscount) {
PJ_LOG(3,(THIS_FILE, " NS Authority RR:"));
PJ_LOG(3, (THIS_FILE, " NS Authority RR:"));
for (i=0; i<res->hdr.nscount; ++i) {
dump_answer(i, &res->ns[i]);
}
PJ_LOG(3,(THIS_FILE, ""));
for (i = 0; i < res->hdr.nscount; ++i) {
dump_answer(i, &res->ns[i]);
}
PJ_LOG(3, (THIS_FILE, ""));
}
/* Dump Additional info sections */
if (res->hdr.arcount) {
PJ_LOG(3,(THIS_FILE, " Additional Info RR:"));
PJ_LOG(3, (THIS_FILE, " Additional Info RR:"));
for (i=0; i<res->hdr.arcount; ++i) {
dump_answer(i, &res->arr[i]);
}
PJ_LOG(3,(THIS_FILE, ""));
for (i = 0; i < res->hdr.arcount; ++i) {
dump_answer(i, &res->arr[i]);
}
PJ_LOG(3, (THIS_FILE, ""));
}
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/dns_server.h>
#include <pjlib-util/errno.h>
@ -26,64 +25,56 @@
#include <pj/pool.h>
#include <pj/string.h>
#define THIS_FILE "dns_server.c"
#define MAX_ANS 16
#define MAX_PKT 1500
#define MAX_LABEL 32
#define THIS_FILE "dns_server.c"
#define MAX_ANS 16
#define MAX_PKT 1500
#define MAX_LABEL 32
struct label_tab
{
unsigned count;
struct {
unsigned pos;
pj_str_t label;
struct
{
unsigned pos;
pj_str_t label;
} a[MAX_LABEL];
};
struct rr
{
PJ_DECL_LIST_MEMBER(struct rr);
pj_dns_parsed_rr rec;
pj_dns_parsed_rr rec;
};
struct pj_dns_server
{
pj_pool_t *pool;
pj_pool_factory *pf;
pj_activesock_t *asock;
pj_ioqueue_op_key_t send_key;
struct rr rr_list;
pj_pool_t* pool;
pj_pool_factory* pf;
pj_activesock_t* asock;
pj_ioqueue_op_key_t send_key;
struct rr rr_list;
};
static pj_bool_t on_data_recvfrom(pj_activesock_t* asock, void* data,
pj_size_t size, const pj_sockaddr_t* src_addr,
int addr_len, pj_status_t status);
static pj_bool_t on_data_recvfrom(pj_activesock_t *asock,
void *data,
pj_size_t size,
const pj_sockaddr_t *src_addr,
int addr_len,
pj_status_t status);
PJ_DEF(pj_status_t) pj_dns_server_create( pj_pool_factory *pf,
pj_ioqueue_t *ioqueue,
int af,
unsigned port,
unsigned flags,
pj_dns_server **p_srv)
PJ_DEF(pj_status_t)
pj_dns_server_create(pj_pool_factory* pf, pj_ioqueue_t* ioqueue, int af,
unsigned port, unsigned flags, pj_dns_server** p_srv)
{
pj_pool_t *pool;
pj_dns_server *srv;
pj_pool_t* pool;
pj_dns_server* srv;
pj_sockaddr sock_addr;
pj_activesock_cb sock_cb;
pj_status_t status;
PJ_ASSERT_RETURN(pf && ioqueue && p_srv && flags==0, PJ_EINVAL);
PJ_ASSERT_RETURN(af==pj_AF_INET() || af==pj_AF_INET6(), PJ_EINVAL);
PJ_ASSERT_RETURN(pf && ioqueue && p_srv && flags == 0, PJ_EINVAL);
PJ_ASSERT_RETURN(af == pj_AF_INET() || af == pj_AF_INET6(), PJ_EINVAL);
pool = pj_pool_create(pf, "dnsserver", 256, 256, NULL);
srv = (pj_dns_server*) PJ_POOL_ZALLOC_T(pool, pj_dns_server);
srv = (pj_dns_server*)PJ_POOL_ZALLOC_T(pool, pj_dns_server);
srv->pool = pool;
srv->pf = pf;
pj_list_init(&srv->rr_list);
@ -91,20 +82,20 @@ PJ_DEF(pj_status_t) pj_dns_server_create( pj_pool_factory *pf,
pj_bzero(&sock_addr, sizeof(sock_addr));
sock_addr.addr.sa_family = (pj_uint16_t)af;
pj_sockaddr_set_port(&sock_addr, (pj_uint16_t)port);
pj_bzero(&sock_cb, sizeof(sock_cb));
sock_cb.on_data_recvfrom = &on_data_recvfrom;
status = pj_activesock_create_udp(pool, &sock_addr, NULL, ioqueue,
&sock_cb, srv, &srv->asock, NULL);
status = pj_activesock_create_udp(pool, &sock_addr, NULL, ioqueue, &sock_cb,
srv, &srv->asock, NULL);
if (status != PJ_SUCCESS)
goto on_error;
goto on_error;
pj_ioqueue_op_key_init(&srv->send_key, sizeof(srv->send_key));
status = pj_activesock_start_recvfrom(srv->asock, pool, MAX_PKT, 0);
if (status != PJ_SUCCESS)
goto on_error;
goto on_error;
*p_srv = srv;
return PJ_SUCCESS;
@ -114,14 +105,13 @@ on_error:
return status;
}
PJ_DEF(pj_status_t) pj_dns_server_destroy(pj_dns_server *srv)
PJ_DEF(pj_status_t) pj_dns_server_destroy(pj_dns_server* srv)
{
PJ_ASSERT_RETURN(srv, PJ_EINVAL);
if (srv->asock) {
pj_activesock_close(srv->asock);
srv->asock = NULL;
pj_activesock_close(srv->asock);
srv->asock = NULL;
}
pj_pool_safe_release(&srv->pool);
@ -129,109 +119,101 @@ PJ_DEF(pj_status_t) pj_dns_server_destroy(pj_dns_server *srv)
return PJ_SUCCESS;
}
static struct rr* find_rr( pj_dns_server *srv,
unsigned dns_class,
unsigned type /* pj_dns_type */,
const pj_str_t *name)
static struct rr* find_rr(pj_dns_server* srv, unsigned dns_class,
unsigned type /* pj_dns_type */, const pj_str_t* name)
{
struct rr *r;
struct rr* r;
r = srv->rr_list.next;
while (r != &srv->rr_list) {
if (r->rec.dnsclass == dns_class && r->rec.type == type &&
pj_stricmp(&r->rec.name, name)==0)
{
return r;
}
r = r->next;
if (r->rec.dnsclass == dns_class && r->rec.type == type &&
pj_stricmp(&r->rec.name, name) == 0)
{
return r;
}
r = r->next;
}
return NULL;
}
PJ_DEF(pj_status_t) pj_dns_server_add_rec( pj_dns_server *srv,
unsigned count,
const pj_dns_parsed_rr rr_param[])
PJ_DEF(pj_status_t)
pj_dns_server_add_rec(pj_dns_server* srv, unsigned count,
const pj_dns_parsed_rr rr_param[])
{
unsigned i;
PJ_ASSERT_RETURN(srv && count && rr_param, PJ_EINVAL);
for (i=0; i<count; ++i) {
struct rr *rr;
for (i = 0; i < count; ++i) {
struct rr* rr;
PJ_ASSERT_RETURN(find_rr(srv, rr_param[i].dnsclass, rr_param[i].type,
&rr_param[i].name) == NULL,
PJ_EEXISTS);
PJ_ASSERT_RETURN(find_rr(srv, rr_param[i].dnsclass, rr_param[i].type,
&rr_param[i].name) == NULL,
PJ_EEXISTS);
rr = (struct rr*) PJ_POOL_ZALLOC_T(srv->pool, struct rr);
pj_memcpy(&rr->rec, &rr_param[i], sizeof(pj_dns_parsed_rr));
rr = (struct rr*)PJ_POOL_ZALLOC_T(srv->pool, struct rr);
pj_memcpy(&rr->rec, &rr_param[i], sizeof(pj_dns_parsed_rr));
pj_list_push_back(&srv->rr_list, rr);
pj_list_push_back(&srv->rr_list, rr);
}
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pj_dns_server_del_rec( pj_dns_server *srv,
int dns_class,
pj_dns_type type,
const pj_str_t *name)
PJ_DEF(pj_status_t)
pj_dns_server_del_rec(pj_dns_server* srv, int dns_class, pj_dns_type type,
const pj_str_t* name)
{
struct rr *rr;
struct rr* rr;
PJ_ASSERT_RETURN(srv && type && name, PJ_EINVAL);
rr = find_rr(srv, dns_class, type, name);
if (!rr)
return PJ_ENOTFOUND;
return PJ_ENOTFOUND;
pj_list_erase(rr);
return PJ_SUCCESS;
}
static void write16(pj_uint8_t *p, pj_uint16_t val)
static void write16(pj_uint8_t* p, pj_uint16_t val)
{
p[0] = (pj_uint8_t)(val >> 8);
p[1] = (pj_uint8_t)(val & 0xFF);
}
static void write32(pj_uint8_t *p, pj_uint32_t val)
static void write32(pj_uint8_t* p, pj_uint32_t val)
{
val = pj_htonl(val);
pj_memcpy(p, &val, 4);
}
static int print_name(pj_uint8_t *pkt, int size,
pj_uint8_t *pos, const pj_str_t *name,
struct label_tab *tab)
static int print_name(pj_uint8_t* pkt, int size, pj_uint8_t* pos,
const pj_str_t* name, struct label_tab* tab)
{
pj_uint8_t *p = pos;
pj_uint8_t* p = pos;
const char *endlabel, *endname;
unsigned i;
pj_str_t label;
/* Check if name is in the table */
for (i=0; i<tab->count; ++i) {
if (pj_strcmp(&tab->a[i].label, name)==0)
break;
for (i = 0; i < tab->count; ++i) {
if (pj_strcmp(&tab->a[i].label, name) == 0)
break;
}
if (i != tab->count) {
write16(p, (pj_uint16_t)(tab->a[i].pos | (0xc0 << 8)));
return 2;
write16(p, (pj_uint16_t)(tab->a[i].pos | (0xc0 << 8)));
return 2;
} else {
if (tab->count < MAX_LABEL) {
tab->a[tab->count].pos = (unsigned)(p-pkt);
tab->a[tab->count].label.ptr = (char*)(p+1);
tab->a[tab->count].label.slen = name->slen;
++tab->count;
}
if (tab->count < MAX_LABEL) {
tab->a[tab->count].pos = (unsigned)(p - pkt);
tab->a[tab->count].label.ptr = (char*)(p + 1);
tab->a[tab->count].label.slen = name->slen;
++tab->count;
}
}
endlabel = name->ptr;
@ -240,326 +222,315 @@ static int print_name(pj_uint8_t *pkt, int size,
label.ptr = (char*)name->ptr;
while (endlabel != endname) {
while (endlabel != endname && *endlabel != '.')
++endlabel;
while (endlabel != endname && *endlabel != '.')
++endlabel;
label.slen = (endlabel - label.ptr);
label.slen = (endlabel - label.ptr);
if (size < label.slen + 1)
return -1;
if (size < label.slen+1)
return -1;
*p = (pj_uint8_t)label.slen;
pj_memcpy(p + 1, label.ptr, label.slen);
*p = (pj_uint8_t)label.slen;
pj_memcpy(p+1, label.ptr, label.slen);
size -= (int)(label.slen + 1);
p += (label.slen + 1);
size -= (int)(label.slen+1);
p += (label.slen+1);
if (endlabel != endname && *endlabel == '.')
++endlabel;
label.ptr = (char*)endlabel;
if (endlabel != endname && *endlabel == '.')
++endlabel;
label.ptr = (char*)endlabel;
}
if (size == 0)
return -1;
return -1;
*p++ = '\0';
return (int)(p-pos);
return (int)(p - pos);
}
static int print_rr(pj_uint8_t *pkt, int size, pj_uint8_t *pos,
const pj_dns_parsed_rr *rr, struct label_tab *tab)
static int print_rr(pj_uint8_t* pkt, int size, pj_uint8_t* pos,
const pj_dns_parsed_rr* rr, struct label_tab* tab)
{
pj_uint8_t *p = pos;
pj_uint8_t* p = pos;
int len;
len = print_name(pkt, size, pos, &rr->name, tab);
if (len < 0)
return -1;
return -1;
p += len;
size -= len;
if (size < 8)
return -1;
return -1;
pj_assert(rr->dnsclass == 1);
write16(p+0, (pj_uint16_t)rr->type); /* type */
write16(p+2, (pj_uint16_t)rr->dnsclass); /* class */
write32(p+4, rr->ttl); /* TTL */
write16(p + 0, (pj_uint16_t)rr->type); /* type */
write16(p + 2, (pj_uint16_t)rr->dnsclass); /* class */
write32(p + 4, rr->ttl); /* TTL */
p += 8;
size -= 8;
if (rr->type == PJ_DNS_TYPE_A) {
if (size < 6)
return -1;
if (size < 6)
return -1;
/* RDLEN is 4 */
write16(p, 4);
/* RDLEN is 4 */
write16(p, 4);
/* Address */
pj_memcpy(p + 2, &rr->rdata.a.ip_addr, 4);
/* Address */
pj_memcpy(p+2, &rr->rdata.a.ip_addr, 4);
p += 6;
size -= 6;
p += 6;
size -= 6;
} else if (rr->type == PJ_DNS_TYPE_AAAA) {
if (size < 18)
return -1;
if (size < 18)
return -1;
/* RDLEN is 16 */
write16(p, 16);
/* RDLEN is 16 */
write16(p, 16);
/* Address */
pj_memcpy(p + 2, &rr->rdata.aaaa.ip_addr, 16);
/* Address */
pj_memcpy(p+2, &rr->rdata.aaaa.ip_addr, 16);
p += 18;
size -= 18;
p += 18;
size -= 18;
} else if (rr->type == PJ_DNS_TYPE_CNAME ||
rr->type == PJ_DNS_TYPE_NS ||
rr->type == PJ_DNS_TYPE_PTR) {
} else if (rr->type == PJ_DNS_TYPE_CNAME || rr->type == PJ_DNS_TYPE_NS ||
rr->type == PJ_DNS_TYPE_PTR)
{
if (size < 4)
return -1;
if (size < 4)
return -1;
len = print_name(pkt, size - 2, p + 2, &rr->rdata.cname.name, tab);
if (len < 0)
return -1;
len = print_name(pkt, size-2, p+2, &rr->rdata.cname.name, tab);
if (len < 0)
return -1;
write16(p, (pj_uint16_t)len);
write16(p, (pj_uint16_t)len);
p += (len + 2);
size -= (len + 2);
p += (len + 2);
size -= (len + 2);
} else if (rr->type == PJ_DNS_TYPE_SRV) {
if (size < 10)
return -1;
if (size < 10)
return -1;
write16(p + 2, rr->rdata.srv.prio); /* Priority */
write16(p + 4, rr->rdata.srv.weight); /* Weight */
write16(p + 6, rr->rdata.srv.port); /* Port */
write16(p+2, rr->rdata.srv.prio); /* Priority */
write16(p+4, rr->rdata.srv.weight); /* Weight */
write16(p+6, rr->rdata.srv.port); /* Port */
/* Target */
len = print_name(pkt, size - 8, p + 8, &rr->rdata.srv.target, tab);
if (len < 0)
return -1;
/* Target */
len = print_name(pkt, size-8, p+8, &rr->rdata.srv.target, tab);
if (len < 0)
return -1;
/* RDLEN */
write16(p, (pj_uint16_t)(len + 6));
/* RDLEN */
write16(p, (pj_uint16_t)(len + 6));
p += (len + 8);
size -= (len + 8);
p += (len + 8);
size -= (len + 8);
} else {
pj_assert(!"Not supported");
return -1;
pj_assert(!"Not supported");
return -1;
}
return (int)(p-pos);
return (int)(p - pos);
}
static int print_packet(const pj_dns_parsed_packet *rec, pj_uint8_t *pkt,
int size)
static int print_packet(const pj_dns_parsed_packet* rec, pj_uint8_t* pkt,
int size)
{
pj_uint8_t *p = pkt;
pj_uint8_t* p = pkt;
struct label_tab tab;
int i, len;
tab.count = 0;
pj_assert(sizeof(pj_dns_hdr)==12);
pj_assert(sizeof(pj_dns_hdr) == 12);
if (size < (int)sizeof(pj_dns_hdr))
return -1;
return -1;
/* Initialize header */
write16(p+0, rec->hdr.id);
write16(p+2, rec->hdr.flags);
write16(p+4, rec->hdr.qdcount);
write16(p+6, rec->hdr.anscount);
write16(p+8, rec->hdr.nscount);
write16(p+10, rec->hdr.arcount);
write16(p + 0, rec->hdr.id);
write16(p + 2, rec->hdr.flags);
write16(p + 4, rec->hdr.qdcount);
write16(p + 6, rec->hdr.anscount);
write16(p + 8, rec->hdr.nscount);
write16(p + 10, rec->hdr.arcount);
p = pkt + sizeof(pj_dns_hdr);
size -= sizeof(pj_dns_hdr);
/* Print queries */
for (i=0; i<rec->hdr.qdcount; ++i) {
for (i = 0; i < rec->hdr.qdcount; ++i) {
len = print_name(pkt, size, p, &rec->q[i].name, &tab);
if (len < 0)
return -1;
len = print_name(pkt, size, p, &rec->q[i].name, &tab);
if (len < 0)
return -1;
p += len;
size -= len;
p += len;
size -= len;
if (size < 4)
return -1;
if (size < 4)
return -1;
/* Set type */
write16(p + 0, (pj_uint16_t)rec->q[i].type);
/* Set type */
write16(p+0, (pj_uint16_t)rec->q[i].type);
/* Set class (IN=1) */
pj_assert(rec->q[i].dnsclass == 1);
write16(p + 2, rec->q[i].dnsclass);
/* Set class (IN=1) */
pj_assert(rec->q[i].dnsclass == 1);
write16(p+2, rec->q[i].dnsclass);
p += 4;
p += 4;
}
/* Print answers */
for (i=0; i<rec->hdr.anscount; ++i) {
len = print_rr(pkt, size, p, &rec->ans[i], &tab);
if (len < 0)
return -1;
for (i = 0; i < rec->hdr.anscount; ++i) {
len = print_rr(pkt, size, p, &rec->ans[i], &tab);
if (len < 0)
return -1;
p += len;
size -= len;
p += len;
size -= len;
}
/* Print NS records */
for (i=0; i<rec->hdr.nscount; ++i) {
len = print_rr(pkt, size, p, &rec->ns[i], &tab);
if (len < 0)
return -1;
for (i = 0; i < rec->hdr.nscount; ++i) {
len = print_rr(pkt, size, p, &rec->ns[i], &tab);
if (len < 0)
return -1;
p += len;
size -= len;
p += len;
size -= len;
}
/* Print additional records */
for (i=0; i<rec->hdr.arcount; ++i) {
len = print_rr(pkt, size, p, &rec->arr[i], &tab);
if (len < 0)
return -1;
for (i = 0; i < rec->hdr.arcount; ++i) {
len = print_rr(pkt, size, p, &rec->arr[i], &tab);
if (len < 0)
return -1;
p += len;
size -= len;
p += len;
size -= len;
}
return (int)(p - pkt);
}
static pj_bool_t on_data_recvfrom(pj_activesock_t *asock,
void *data,
pj_size_t size,
const pj_sockaddr_t *src_addr,
int addr_len,
pj_status_t status)
static pj_bool_t on_data_recvfrom(pj_activesock_t* asock, void* data,
pj_size_t size, const pj_sockaddr_t* src_addr,
int addr_len, pj_status_t status)
{
pj_dns_server *srv;
pj_pool_t *pool;
pj_dns_parsed_packet *req;
pj_dns_server* srv;
pj_pool_t* pool;
pj_dns_parsed_packet* req;
pj_dns_parsed_packet ans;
struct rr *rr;
struct rr* rr;
pj_ssize_t pkt_len;
unsigned i;
if (status != PJ_SUCCESS)
return PJ_TRUE;
return PJ_TRUE;
srv = (pj_dns_server*) pj_activesock_get_user_data(asock);
srv = (pj_dns_server*)pj_activesock_get_user_data(asock);
pool = pj_pool_create(srv->pf, "dnssrvrx", 512, 256, NULL);
status = pj_dns_parse_packet(pool, data, (unsigned)size, &req);
if (status != PJ_SUCCESS) {
char addrinfo[PJ_INET6_ADDRSTRLEN+10];
pj_sockaddr_print(src_addr, addrinfo, sizeof(addrinfo), 3);
PJ_PERROR(4,(THIS_FILE, status, "Error parsing query from %s",
addrinfo));
goto on_return;
char addrinfo[PJ_INET6_ADDRSTRLEN + 10];
pj_sockaddr_print(src_addr, addrinfo, sizeof(addrinfo), 3);
PJ_PERROR(4,
(THIS_FILE, status, "Error parsing query from %s", addrinfo));
goto on_return;
}
/* Init answer */
pj_bzero(&ans, sizeof(ans));
ans.hdr.id = req->hdr.id;
ans.hdr.qdcount = 1;
ans.q = (pj_dns_parsed_query*) PJ_POOL_ALLOC_T(pool, pj_dns_parsed_query);
ans.q = (pj_dns_parsed_query*)PJ_POOL_ALLOC_T(pool, pj_dns_parsed_query);
pj_memcpy(ans.q, req->q, sizeof(pj_dns_parsed_query));
if (req->hdr.qdcount != 1) {
ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_FORMERR);
goto send_pkt;
ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_FORMERR);
goto send_pkt;
}
if (req->q[0].dnsclass != PJ_DNS_CLASS_IN) {
ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_NOTIMPL);
goto send_pkt;
ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_NOTIMPL);
goto send_pkt;
}
/* Find the record */
rr = find_rr(srv, req->q->dnsclass, req->q->type, &req->q->name);
if (rr == NULL) {
ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_NXDOMAIN);
goto send_pkt;
ans.hdr.flags = PJ_DNS_SET_RCODE(PJ_DNS_RCODE_NXDOMAIN);
goto send_pkt;
}
/* Init answer record */
ans.hdr.anscount = 0;
ans.ans = (pj_dns_parsed_rr*)
pj_pool_calloc(pool, MAX_ANS, sizeof(pj_dns_parsed_rr));
ans.ans = (pj_dns_parsed_rr*)pj_pool_calloc(pool, MAX_ANS,
sizeof(pj_dns_parsed_rr));
/* DNS SRV query needs special treatment since it returns multiple
* records
*/
if (req->q->type == PJ_DNS_TYPE_SRV) {
struct rr *r;
struct rr* r;
r = srv->rr_list.next;
while (r != &srv->rr_list) {
if (r->rec.dnsclass == req->q->dnsclass &&
r->rec.type == PJ_DNS_TYPE_SRV &&
pj_stricmp(&r->rec.name, &req->q->name)==0 &&
ans.hdr.anscount < MAX_ANS)
{
pj_memcpy(&ans.ans[ans.hdr.anscount], &r->rec,
sizeof(pj_dns_parsed_rr));
++ans.hdr.anscount;
}
r = r->next;
}
r = srv->rr_list.next;
while (r != &srv->rr_list) {
if (r->rec.dnsclass == req->q->dnsclass &&
r->rec.type == PJ_DNS_TYPE_SRV &&
pj_stricmp(&r->rec.name, &req->q->name) == 0 &&
ans.hdr.anscount < MAX_ANS)
{
pj_memcpy(&ans.ans[ans.hdr.anscount], &r->rec,
sizeof(pj_dns_parsed_rr));
++ans.hdr.anscount;
}
r = r->next;
}
} else {
/* Otherwise just copy directly from the server record */
pj_memcpy(&ans.ans[ans.hdr.anscount], &rr->rec,
sizeof(pj_dns_parsed_rr));
++ans.hdr.anscount;
/* Otherwise just copy directly from the server record */
pj_memcpy(&ans.ans[ans.hdr.anscount], &rr->rec,
sizeof(pj_dns_parsed_rr));
++ans.hdr.anscount;
}
/* For each CNAME entry, add A entry */
for (i=0; i<ans.hdr.anscount && ans.hdr.anscount < MAX_ANS; ++i) {
if (ans.ans[i].type == PJ_DNS_TYPE_CNAME) {
struct rr *r;
for (i = 0; i < ans.hdr.anscount && ans.hdr.anscount < MAX_ANS; ++i) {
if (ans.ans[i].type == PJ_DNS_TYPE_CNAME) {
struct rr* r;
r = find_rr(srv, ans.ans[i].dnsclass, PJ_DNS_TYPE_A,
&ans.ans[i].name);
pj_memcpy(&ans.ans[ans.hdr.anscount], &r->rec,
sizeof(pj_dns_parsed_rr));
++ans.hdr.anscount;
}
r = find_rr(srv, ans.ans[i].dnsclass, PJ_DNS_TYPE_A,
&ans.ans[i].name);
pj_memcpy(&ans.ans[ans.hdr.anscount], &r->rec,
sizeof(pj_dns_parsed_rr));
++ans.hdr.anscount;
}
}
send_pkt:
pkt_len = print_packet(&ans, (pj_uint8_t*)data, MAX_PKT);
if (pkt_len < 1) {
PJ_LOG(4,(THIS_FILE, "Error: answer too large"));
goto on_return;
PJ_LOG(4, (THIS_FILE, "Error: answer too large"));
goto on_return;
}
status = pj_activesock_sendto(srv->asock, &srv->send_key, data, &pkt_len,
0, src_addr, addr_len);
status = pj_activesock_sendto(srv->asock, &srv->send_key, data, &pkt_len, 0,
src_addr, addr_len);
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
PJ_PERROR(4,(THIS_FILE, status, "Error sending answer"));
goto on_return;
PJ_PERROR(4, (THIS_FILE, status, "Error sending answer"));
goto on_return;
}
on_return:
pj_pool_release(pool);
return PJ_TRUE;
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,173 +14,178 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/errno.h>
#include <pjlib-util/types.h>
#include <pj/assert.h>
#include <pj/string.h>
/* PJLIB_UTIL's own error codes/messages
/* PJLIB_UTIL's own error codes/messages
* MUST KEEP THIS ARRAY SORTED!!
* Message must be limited to 64 chars!
*/
#if defined(PJ_HAS_ERROR_STRING) && PJ_HAS_ERROR_STRING!=0
static const struct
#if defined(PJ_HAS_ERROR_STRING) && PJ_HAS_ERROR_STRING != 0
static const struct
{
int code;
const char *msg;
} err_str[] =
{
const char* msg;
} err_str[] = {
/* STUN errors */
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNRESOLVE, "Unable to resolve STUN server" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINMSGTYPE, "Unknown STUN message type" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINMSGLEN, "Invalid STUN message length" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINATTRLEN, "STUN attribute length error" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINATTRTYPE, "Invalid STUN attribute type" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNININDEX, "Invalid STUN server/socket index" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOBINDRES, "No STUN binding response in the message" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNRECVERRATTR, "Received STUN error attribute" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOMAP, "No STUN mapped address attribute" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOTRESPOND, "Received no response from STUN server" ),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNSYMMETRIC, "Symetric NAT detected by STUN" ),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNRESOLVE, "Unable to resolve STUN server"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNINMSGTYPE, "Unknown STUN message type"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNINMSGLEN, "Invalid STUN message length"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNINATTRLEN, "STUN attribute length error"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNINATTRTYPE, "Invalid STUN attribute type"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNININDEX, "Invalid STUN server/socket index"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNNOBINDRES,
"No STUN binding response in the message"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNRECVERRATTR, "Received STUN error attribute"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNNOMAP, "No STUN mapped address attribute"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNNOTRESPOND,
"Received no response from STUN server"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNSYMMETRIC, "Symetric NAT detected by STUN"),
/* XML errors */
PJ_BUILD_ERR( PJLIB_UTIL_EINXML, "Invalid XML message" ),
PJ_BUILD_ERR(PJLIB_UTIL_EINXML, "Invalid XML message"),
/* JSON errors */
PJ_BUILD_ERR( PJLIB_UTIL_EINJSON, "Invalid JSON document" ),
PJ_BUILD_ERR(PJLIB_UTIL_EINJSON, "Invalid JSON document"),
/* DNS errors */
PJ_BUILD_ERR( PJLIB_UTIL_EDNSQRYTOOSMALL, "DNS query packet buffer is too small"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNSINSIZE, "Invalid DNS packet length"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNSINCLASS, "Invalid DNS class"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNSINNAMEPTR, "Invalid DNS name pointer"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNSINNSADDR, "Invalid DNS nameserver address"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNSNONS, "No nameserver is in DNS resolver"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNSNOWORKINGNS, "No working DNS nameserver"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNSNOANSWERREC, "No answer record in the DNS response"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNSINANSWER, "Invalid DNS answer"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSQRYTOOSMALL,
"DNS query packet buffer is too small"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSINSIZE, "Invalid DNS packet length"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSINCLASS, "Invalid DNS class"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSINNAMEPTR, "Invalid DNS name pointer"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSINNSADDR, "Invalid DNS nameserver address"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSNONS, "No nameserver is in DNS resolver"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSNOWORKINGNS, "No working DNS nameserver"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSNOANSWERREC,
"No answer record in the DNS response"),
PJ_BUILD_ERR(PJLIB_UTIL_EDNSINANSWER, "Invalid DNS answer"),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_FORMERR, "DNS \"Format error\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_SERVFAIL, "DNS \"Server failure\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NXDOMAIN, "DNS \"Name Error\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTIMPL, "DNS \"Not Implemented\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_REFUSED, "DNS \"Refused\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_YXDOMAIN, "DNS \"The name exists\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_YXRRSET, "DNS \"The RRset (name, type) exists\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NXRRSET, "DNS \"The RRset (name, type) does not exist\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTAUTH, "DNS \"Not authorized\""),
PJ_BUILD_ERR( PJLIB_UTIL_EDNS_NOTZONE, "DNS \"The zone specified is not a zone\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_FORMERR, "DNS \"Format error\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_SERVFAIL, "DNS \"Server failure\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_NXDOMAIN, "DNS \"Name Error\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_NOTIMPL, "DNS \"Not Implemented\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_REFUSED, "DNS \"Refused\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_YXDOMAIN, "DNS \"The name exists\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_YXRRSET,
"DNS \"The RRset (name, type) exists\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_NXRRSET,
"DNS \"The RRset (name, type) does not exist\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_NOTAUTH, "DNS \"Not authorized\""),
PJ_BUILD_ERR(PJLIB_UTIL_EDNS_NOTZONE,
"DNS \"The zone specified is not a zone\""),
/* STUN */
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNTOOMANYATTR, "Too many STUN attributes"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNUNKNOWNATTR, "Unknown STUN attribute"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINADDRLEN, "Invalid STUN socket address length"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNIPV6NOTSUPP, "STUN IPv6 attribute not supported"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOTRESPONSE, "Expecting STUN response message"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNINVALIDID, "STUN transaction ID mismatch"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOHANDLER, "Unable to find STUN handler for the request"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNMSGINTPOS, "Found non-FINGERPRINT attr. after MESSAGE-INTEGRITY"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNFINGERPOS, "Found STUN attribute after FINGERPRINT"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOUSERNAME, "Missing STUN USERNAME attribute"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNMSGINT, "Missing/invalid STUN MESSAGE-INTEGRITY attribute"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNDUPATTR, "Found duplicate STUN attribute"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNOREALM, "Missing STUN REALM attribute"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNNONCE, "Missing/stale STUN NONCE attribute value"),
PJ_BUILD_ERR( PJLIB_UTIL_ESTUNTSXFAILED, "STUN transaction terminates with failure"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNTOOMANYATTR, "Too many STUN attributes"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNUNKNOWNATTR, "Unknown STUN attribute"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNINADDRLEN,
"Invalid STUN socket address length"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNIPV6NOTSUPP,
"STUN IPv6 attribute not supported"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNNOTRESPONSE,
"Expecting STUN response message"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNINVALIDID, "STUN transaction ID mismatch"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNNOHANDLER,
"Unable to find STUN handler for the request"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNMSGINTPOS,
"Found non-FINGERPRINT attr. after MESSAGE-INTEGRITY"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNFINGERPOS,
"Found STUN attribute after FINGERPRINT"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNNOUSERNAME, "Missing STUN USERNAME attribute"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNMSGINT,
"Missing/invalid STUN MESSAGE-INTEGRITY attribute"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNDUPATTR, "Found duplicate STUN attribute"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNNOREALM, "Missing STUN REALM attribute"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNNONCE,
"Missing/stale STUN NONCE attribute value"),
PJ_BUILD_ERR(PJLIB_UTIL_ESTUNTSXFAILED,
"STUN transaction terminates with failure"),
/* HTTP Client */
PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINURL, "Invalid URL format"),
PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINPORT, "Invalid URL port number"),
PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINCHDR, "Incomplete response header received"),
PJ_BUILD_ERR( PJLIB_UTIL_EHTTPINSBUF, "Insufficient buffer"),
PJ_BUILD_ERR( PJLIB_UTIL_EHTTPLOST, "Connection lost"),
PJ_BUILD_ERR(PJLIB_UTIL_EHTTPINURL, "Invalid URL format"),
PJ_BUILD_ERR(PJLIB_UTIL_EHTTPINPORT, "Invalid URL port number"),
PJ_BUILD_ERR(PJLIB_UTIL_EHTTPINCHDR, "Incomplete response header received"),
PJ_BUILD_ERR(PJLIB_UTIL_EHTTPINSBUF, "Insufficient buffer"),
PJ_BUILD_ERR(PJLIB_UTIL_EHTTPLOST, "Connection lost"),
/* CLI */
PJ_BUILD_ERR( PJ_CLI_EEXIT, "Exit current session"),
PJ_BUILD_ERR( PJ_CLI_EMISSINGARG, "Missing argument"),
PJ_BUILD_ERR( PJ_CLI_ETOOMANYARGS, "Too many arguments"),
PJ_BUILD_ERR( PJ_CLI_EINVARG, "Invalid argument"),
PJ_BUILD_ERR( PJ_CLI_EBADNAME, "Command name already exists"),
PJ_BUILD_ERR( PJ_CLI_EBADID, "Command id already exists"),
PJ_BUILD_ERR( PJ_CLI_EBADXML, "Invalid XML format"),
PJ_BUILD_ERR( PJ_CLI_ETELNETLOST, "Connection lost"),
PJ_BUILD_ERR(PJ_CLI_EEXIT, "Exit current session"),
PJ_BUILD_ERR(PJ_CLI_EMISSINGARG, "Missing argument"),
PJ_BUILD_ERR(PJ_CLI_ETOOMANYARGS, "Too many arguments"),
PJ_BUILD_ERR(PJ_CLI_EINVARG, "Invalid argument"),
PJ_BUILD_ERR(PJ_CLI_EBADNAME, "Command name already exists"),
PJ_BUILD_ERR(PJ_CLI_EBADID, "Command id already exists"),
PJ_BUILD_ERR(PJ_CLI_EBADXML, "Invalid XML format"),
PJ_BUILD_ERR(PJ_CLI_ETELNETLOST, "Connection lost"),
};
#endif /* PJ_HAS_ERROR_STRING */
#endif /* PJ_HAS_ERROR_STRING */
/*
* pjlib_util_strerror()
*/
pj_str_t pjlib_util_strerror(pj_status_t statcode,
char *buf, pj_size_t bufsize )
pj_str_t pjlib_util_strerror(pj_status_t statcode, char* buf, pj_size_t bufsize)
{
pj_str_t errstr;
#if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0)
if (statcode >= PJLIB_UTIL_ERRNO_START &&
statcode < PJLIB_UTIL_ERRNO_START + PJ_ERRNO_SPACE_SIZE)
if (statcode >= PJLIB_UTIL_ERRNO_START &&
statcode < PJLIB_UTIL_ERRNO_START + PJ_ERRNO_SPACE_SIZE)
{
/* Find the error in the table.
* Use binary search!
*/
int first = 0;
int n = PJ_ARRAY_SIZE(err_str);
/* Find the error in the table.
* Use binary search!
*/
int first = 0;
int n = PJ_ARRAY_SIZE(err_str);
while (n > 0) {
int half = n/2;
int mid = first + half;
while (n > 0) {
int half = n / 2;
int mid = first + half;
if (err_str[mid].code < statcode) {
first = mid+1;
n -= (half+1);
} else if (err_str[mid].code > statcode) {
n = half;
} else {
first = mid;
break;
}
}
if (err_str[mid].code < statcode) {
first = mid + 1;
n -= (half + 1);
} else if (err_str[mid].code > statcode) {
n = half;
} else {
first = mid;
break;
}
}
if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) {
pj_str_t msg;
if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) {
pj_str_t msg;
msg.ptr = (char*)err_str[first].msg;
msg.slen = pj_ansi_strlen(err_str[first].msg);
msg.ptr = (char*)err_str[first].msg;
msg.slen = pj_ansi_strlen(err_str[first].msg);
errstr.ptr = buf;
pj_strncpy_with_null(&errstr, &msg, bufsize);
return errstr;
}
errstr.ptr = buf;
pj_strncpy_with_null(&errstr, &msg, bufsize);
return errstr;
}
}
#endif /* PJ_HAS_ERROR_STRING */
#endif /* PJ_HAS_ERROR_STRING */
/* Error not found. */
errstr.ptr = buf;
errstr.slen = pj_ansi_snprintf(buf, bufsize,
"Unknown pjlib-util error %d",
statcode);
errstr.slen =
pj_ansi_snprintf(buf, bufsize, "Unknown pjlib-util error %d", statcode);
if (errstr.slen < 1 || errstr.slen >= (pj_ssize_t)bufsize)
errstr.slen = bufsize - 1;
errstr.slen = bufsize - 1;
return errstr;
}
PJ_DEF(pj_status_t) pjlib_util_init(void)
{
pj_status_t status;
status = pj_register_strerror(PJLIB_UTIL_ERRNO_START,
PJ_ERRNO_SPACE_SIZE,
&pjlib_util_strerror);
status = pj_register_strerror(PJLIB_UTIL_ERRNO_START, PJ_ERRNO_SPACE_SIZE,
&pjlib_util_strerror);
pj_assert(status == PJ_SUCCESS);
return status;

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* pj_getopt entry points
*
* modified by Mike Borella <mike_borella@mw.3com.com>
@ -9,11 +8,9 @@
#include <pj/string.h>
/* Internal only. Users should not call this directly. */
static
int _getopt_internal (int argc, char *const *argv,
const char *shortopts,
const struct pj_getopt_option *longopts, int *longind,
int long_only);
static int _getopt_internal(int argc, char* const* argv, const char* shortopts,
const struct pj_getopt_option* longopts,
int* longind, int long_only);
/* pj_getopt_long and pj_getopt_long_only entry points for GNU pj_getopt.
Copyright (C) 1987,88,89,90,91,92,93,94,96,97 Free Software Foundation, Inc.
@ -34,7 +31,6 @@ int _getopt_internal (int argc, char *const *argv,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
@ -43,35 +39,29 @@ int _getopt_internal (int argc, char *const *argv,
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
# define GETOPT_INTERFACE_VERSION 2
#define GETOPT_INTERFACE_VERSION 2
int
pj_getopt_long (int argc, char *const *argv, const char *options,
const struct pj_getopt_option *long_options, int *opt_index)
int pj_getopt_long(int argc, char* const* argv, const char* options,
const struct pj_getopt_option* long_options, int* opt_index)
{
return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
return _getopt_internal(argc, argv, options, long_options, opt_index, 0);
}
/* Like pj_getopt_long, but '-' as well as '--' can indicate a long option.
If an option that starts with '-' (not '--') doesn't match a long option,
but does match a short option, it is parsed as a short option
instead. */
int
pj_getopt (int argc, char * const * argv, const char * optstring)
int pj_getopt(int argc, char* const* argv, const char* optstring)
{
return _getopt_internal (argc, argv, optstring,
(const struct pj_getopt_option *) 0,
(int *) 0,
0);
return _getopt_internal(argc, argv, optstring,
(const struct pj_getopt_option*)0, (int*)0, 0);
}
#define _(msgid) (msgid)
#define _(msgid) (msgid)
/* This version of `pj_getopt' appears to the caller like standard Unix `pj_getopt'
but it behaves differently for the user, since it allows the user
/* This version of `pj_getopt' appears to the caller like standard Unix
`pj_getopt' but it behaves differently for the user, since it allows the user
to intersperse the options with the other arguments.
As `pj_getopt' works, it permutes the elements of ARGV so that,
@ -90,7 +80,7 @@ pj_getopt (int argc, char * const * argv, const char * optstring)
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
char *pj_optarg = NULL;
char* pj_optarg = NULL;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
@ -120,7 +110,7 @@ static int __getopt_initialized = 0;
If this is zero, or a null string, it means resume the scan
by advancing to the next ARGV-element. */
static char *nextchar;
static char* nextchar;
/* Set to an option character which was unrecognized.
This must be initialized on some systems to avoid linking in the
@ -159,25 +149,24 @@ int pj_optopt = '?';
static enum
{
REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
REQUIRE_ORDER,
PERMUTE,
RETURN_IN_ORDER
} ordering;
/* Value of POSIXLY_CORRECT environment variable. */
static char *posixly_correct;
static char* posixly_correct;
static char *
my_index (const char *str, int chr)
static char* my_index(const char* str, int chr)
{
while (*str)
{
if (*str == chr)
return (char *) str;
str++;
while (*str) {
if (*str == chr)
return (char*)str;
str++;
}
return 0;
return 0;
}
/* Handle permutation of arguments. */
/* Describe the part of ARGV that contains non-options that have
@ -187,7 +176,7 @@ my_index (const char *str, int chr)
static int first_nonopt;
static int last_nonopt;
# define SWAP_FLAGS(ch1, ch2)
#define SWAP_FLAGS(ch1, ch2)
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
@ -198,100 +187,89 @@ static int last_nonopt;
`first_nonopt' and `last_nonopt' are relocated so that they describe
the new indices of the non-options in ARGV after they are moved. */
static void
exchange (char **argv)
static void exchange(char** argv)
{
int bottom = first_nonopt;
int middle = last_nonopt;
int top = pj_optind;
char *tem;
int bottom = first_nonopt;
int middle = last_nonopt;
int top = pj_optind;
char* tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
while (top > middle && middle > bottom) {
if (top - middle > middle - bottom) {
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else
{
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
SWAP_FLAGS(bottom + i, top - (middle - bottom) + i);
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
} else {
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
SWAP_FLAGS (bottom + i, middle + i);
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
SWAP_FLAGS(bottom + i, middle + i);
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
/* Update records for the slots the non-options now occupy. */
first_nonopt += (pj_optind - last_nonopt);
last_nonopt = pj_optind;
first_nonopt += (pj_optind - last_nonopt);
last_nonopt = pj_optind;
}
/* Initialize the internal data when the first call is made. */
static const char *_getopt_initialize (int argc, char *const *argv,
const char *optstring)
static const char* _getopt_initialize(int argc, char* const* argv,
const char* optstring)
{
PJ_UNUSED_ARG(argc);
PJ_UNUSED_ARG(argv);
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
first_nonopt = last_nonopt = pj_optind;
first_nonopt = last_nonopt = pj_optind;
nextchar = NULL;
nextchar = NULL;
//posixly_correct = getenv ("POSIXLY_CORRECT");
posixly_correct = NULL;
// posixly_correct = getenv ("POSIXLY_CORRECT");
posixly_correct = NULL;
/* Determine how to handle the ordering of options and nonoptions. */
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-')
{
ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
ordering = REQUIRE_ORDER;
++optstring;
}
else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
if (optstring[0] == '-') {
ordering = RETURN_IN_ORDER;
++optstring;
} else if (optstring[0] == '+') {
ordering = REQUIRE_ORDER;
++optstring;
} else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
return optstring;
return optstring;
}
/* Scan elements of ARGV (whose length is ARGC) for option characters
@ -350,382 +328,335 @@ static const char *_getopt_initialize (int argc, char *const *argv,
If LONG_ONLY is nonzero, '-' as well as '--' can introduce
long-named options. */
static int
_getopt_internal (int argc, char *const *argv, const char *optstring,
const struct pj_getopt_option *longopts, int *longind,
int long_only)
static int _getopt_internal(int argc, char* const* argv, const char* optstring,
const struct pj_getopt_option* longopts,
int* longind, int long_only)
{
pj_optarg = NULL;
pj_optarg = NULL;
if (pj_optind == 0 || !__getopt_initialized)
{
if (pj_optind == 0)
pj_optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring);
__getopt_initialized = 1;
if (pj_optind == 0 || !__getopt_initialized) {
if (pj_optind == 0)
pj_optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize(argc, argv, optstring);
__getopt_initialized = 1;
}
/* Test whether ARGV[pj_optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
/* Test whether ARGV[pj_optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
#define NONOPTION_P (argv[pj_optind][0] != '-' || argv[pj_optind][1] == '\0')
if (nextchar == NULL || *nextchar == '\0')
{
/* Advance to the next ARGV-element. */
if (nextchar == NULL || *nextchar == '\0') {
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > pj_optind)
last_nonopt = pj_optind;
if (first_nonopt > pj_optind)
first_nonopt = pj_optind;
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > pj_optind)
last_nonopt = pj_optind;
if (first_nonopt > pj_optind)
first_nonopt = pj_optind;
if (ordering == PERMUTE)
{
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (ordering == PERMUTE) {
/* If we have just processed some options following some
non-options, exchange them so that the options come first. */
if (first_nonopt != last_nonopt && last_nonopt != pj_optind)
exchange ((char **) argv);
else if (last_nonopt != pj_optind)
first_nonopt = pj_optind;
if (first_nonopt != last_nonopt && last_nonopt != pj_optind)
exchange((char**)argv);
else if (last_nonopt != pj_optind)
first_nonopt = pj_optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (pj_optind < argc && NONOPTION_P)
pj_optind++;
last_nonopt = pj_optind;
}
while (pj_optind < argc && NONOPTION_P)
pj_optind++;
last_nonopt = pj_optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (pj_optind != argc && !pj_ansi_strcmp(argv[pj_optind], "--"))
{
pj_optind++;
if (pj_optind != argc && !pj_ansi_strcmp(argv[pj_optind], "--")) {
pj_optind++;
if (first_nonopt != last_nonopt && last_nonopt != pj_optind)
exchange ((char **) argv);
else if (first_nonopt == last_nonopt)
first_nonopt = pj_optind;
last_nonopt = argc;
if (first_nonopt != last_nonopt && last_nonopt != pj_optind)
exchange((char**)argv);
else if (first_nonopt == last_nonopt)
first_nonopt = pj_optind;
last_nonopt = argc;
pj_optind = argc;
}
pj_optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (pj_optind == argc)
{
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
pj_optind = first_nonopt;
return -1;
}
if (pj_optind == argc) {
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
pj_optind = first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
{
if (ordering == REQUIRE_ORDER)
return -1;
pj_optarg = argv[pj_optind++];
return 1;
}
if (NONOPTION_P) {
if (ordering == REQUIRE_ORDER)
return -1;
pj_optarg = argv[pj_optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
nextchar = (argv[pj_optind] + 1
+ (longopts != NULL && argv[pj_optind][1] == '-'));
nextchar = (argv[pj_optind] + 1 +
(longopts != NULL && argv[pj_optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
This distinction seems to be the most useful approach. */
if (longopts != NULL
&& (argv[pj_optind][1] == '-'
|| (long_only && (argv[pj_optind][2] || !my_index (optstring, argv[pj_optind][1])))))
if (longopts != NULL &&
(argv[pj_optind][1] == '-' ||
(long_only &&
(argv[pj_optind][2] || !my_index(optstring, argv[pj_optind][1])))))
{
char *nameend;
const struct pj_getopt_option *p;
const struct pj_getopt_option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
char* nameend;
const struct pj_getopt_option* p;
const struct pj_getopt_option* pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar)
== (unsigned int) strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, nextchar, nameend - nextchar)) {
if ((unsigned int)(nameend - nextchar) ==
(unsigned int)strlen(p->name)) {
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
} else if (pfound == NULL) {
/* First nonexact match found. */
pfound = p;
indfound = option_index;
} else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
nextchar += strlen (nextchar);
pj_optind++;
pj_optopt = 0;
return '?';
}
if (ambig && !exact) {
nextchar += strlen(nextchar);
pj_optind++;
pj_optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
pj_optind++;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
pj_optarg = nameend + 1;
else
{
nextchar += strlen (nextchar);
if (pfound != NULL) {
option_index = indfound;
pj_optind++;
if (*nameend) {
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
pj_optarg = nameend + 1;
else {
nextchar += strlen(nextchar);
pj_optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (pj_optind < argc)
pj_optarg = argv[pj_optind++];
else
{
nextchar += strlen (nextchar);
pj_optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
pj_optopt = pfound->val;
return '?';
}
} else if (pfound->has_arg == 1) {
if (pj_optind < argc)
pj_optarg = argv[pj_optind++];
else {
nextchar += strlen(nextchar);
pj_optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen(nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag) {
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not pj_getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[pj_optind][1] == '-'
|| my_index (optstring, *nextchar) == NULL)
{
nextchar = (char *) "";
pj_optind++;
pj_optopt = 0;
return '?';
}
/* Can't find it as a long option. If this is not pj_getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[pj_optind][1] == '-' ||
my_index(optstring, *nextchar) == NULL)
{
nextchar = (char*)"";
pj_optind++;
pj_optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
/* Look at and handle the next short option-character. */
{
char c = *nextchar++;
char *temp = my_index (optstring, c);
{
char c = *nextchar++;
char* temp = my_index(optstring, c);
/* Increment `pj_optind' when we start to process its last character. */
if (*nextchar == '\0')
++pj_optind;
/* Increment `pj_optind' when we start to process its last character. */
if (*nextchar == '\0')
++pj_optind;
if (temp == NULL || c == ':')
{
pj_optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct pj_getopt_option *p;
const struct pj_getopt_option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
if (temp == NULL || c == ':') {
pj_optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';') {
char* nameend;
const struct pj_getopt_option* p;
const struct pj_getopt_option* pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
pj_optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
pj_optind++;
}
else if (pj_optind == argc)
{
pj_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `pj_optind' once;
increment it again when taking next ARGV-elt as argument. */
pj_optarg = argv[pj_optind++];
/* This is an option that requires an argument. */
if (*nextchar != '\0') {
pj_optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
pj_optind++;
} else if (pj_optind == argc) {
pj_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
} else
/* We already incremented `pj_optind' once;
increment it again when taking next ARGV-elt as argument. */
pj_optarg = argv[pj_optind++];
/* pj_optarg is now the argument, see if it's in the
table of longopts. */
/* pj_optarg is now the argument, see if it's in the
table of longopts. */
for (nextchar = nameend = pj_optarg; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
for (nextchar = nameend = pj_optarg; *nameend && *nameend != '=';
nameend++)
/* Do nothing. */;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar) == strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
nextchar += strlen (nextchar);
pj_optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
pj_optarg = nameend + 1;
else
{
nextchar += strlen (nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (pj_optind < argc)
pj_optarg = argv[pj_optind++];
else
{
nextchar += strlen (nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0')
{
pj_optarg = nextchar;
pj_optind++;
}
else
pj_optarg = NULL;
nextchar = NULL;
}
else
{
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
pj_optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
pj_optind++;
}
else if (pj_optind == argc)
{
pj_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `pj_optind' once;
increment it again when taking next ARGV-elt as argument. */
pj_optarg = argv[pj_optind++];
nextchar = NULL;
}
}
return c;
}
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, nextchar, nameend - nextchar)) {
if ((unsigned int)(nameend - nextchar) == strlen(p->name)) {
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
} else if (pfound == NULL) {
/* First nonexact match found. */
pfound = p;
indfound = option_index;
} else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact) {
nextchar += strlen(nextchar);
pj_optind++;
return '?';
}
if (pfound != NULL) {
option_index = indfound;
if (*nameend) {
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
pj_optarg = nameend + 1;
else {
nextchar += strlen(nextchar);
return '?';
}
} else if (pfound->has_arg == 1) {
if (pj_optind < argc)
pj_optarg = argv[pj_optind++];
else {
nextchar += strlen(nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen(nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag) {
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':') {
if (temp[2] == ':') {
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0') {
pj_optarg = nextchar;
pj_optind++;
} else
pj_optarg = NULL;
nextchar = NULL;
} else {
/* This is an option that requires an argument. */
if (*nextchar != '\0') {
pj_optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
pj_optind++;
} else if (pj_optind == argc) {
pj_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
} else
/* We already incremented `pj_optind' once;
increment it again when taking next ARGV-elt as argument.
*/
pj_optarg = argv[pj_optind++];
nextchar = NULL;
}
}
return c;
}
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,14 +14,14 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/hmac_md5.h>
#include <pj/string.h>
PJ_DEF(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx,
const pj_uint8_t *key, unsigned key_len)
PJ_DEF(void)
pj_hmac_md5_init(pj_hmac_md5_context* hctx, const pj_uint8_t* key,
unsigned key_len)
{
pj_uint8_t k_ipad[64];
pj_uint8_t tk[16];
@ -30,7 +29,7 @@ PJ_DEF(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx,
/* if key is longer than 64 bytes reset it to key=MD5(key) */
if (key_len > 64) {
pj_md5_context tctx;
pj_md5_context tctx;
pj_md5_init(&tctx);
pj_md5_update(&tctx, key, key_len);
@ -45,13 +44,13 @@ PJ_DEF(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx,
*/
/* start out by storing key in pads */
pj_bzero( k_ipad, sizeof(k_ipad));
pj_bzero( hctx->k_opad, sizeof(hctx->k_opad));
pj_memcpy( k_ipad, key, key_len);
pj_memcpy( hctx->k_opad, key, key_len);
pj_bzero(k_ipad, sizeof(k_ipad));
pj_bzero(hctx->k_opad, sizeof(hctx->k_opad));
pj_memcpy(k_ipad, key, key_len);
pj_memcpy(hctx->k_opad, key, key_len);
/* XOR key with ipad and opad values */
for (i=0; i<64; i++) {
for (i = 0; i < 64; i++) {
k_ipad[i] ^= 0x36;
hctx->k_opad[i] ^= 0x5c;
}
@ -60,18 +59,16 @@ PJ_DEF(void) pj_hmac_md5_init(pj_hmac_md5_context *hctx,
*/
pj_md5_init(&hctx->context);
pj_md5_update(&hctx->context, k_ipad, 64);
}
PJ_DEF(void) pj_hmac_md5_update(pj_hmac_md5_context *hctx,
const pj_uint8_t *input,
unsigned input_len)
PJ_DEF(void)
pj_hmac_md5_update(pj_hmac_md5_context* hctx, const pj_uint8_t* input,
unsigned input_len)
{
pj_md5_update(&hctx->context, input, input_len);
}
PJ_DEF(void) pj_hmac_md5_final(pj_hmac_md5_context *hctx,
pj_uint8_t digest[16])
PJ_DEF(void) pj_hmac_md5_final(pj_hmac_md5_context* hctx, pj_uint8_t digest[16])
{
pj_md5_final(&hctx->context, digest);
@ -84,9 +81,9 @@ PJ_DEF(void) pj_hmac_md5_final(pj_hmac_md5_context *hctx,
pj_md5_final(&hctx->context, digest);
}
PJ_DEF(void) pj_hmac_md5( const pj_uint8_t *input, unsigned input_len,
const pj_uint8_t *key, unsigned key_len,
pj_uint8_t digest[16] )
PJ_DEF(void)
pj_hmac_md5(const pj_uint8_t* input, unsigned input_len, const pj_uint8_t* key,
unsigned key_len, pj_uint8_t digest[16])
{
pj_hmac_md5_context ctx;
@ -94,4 +91,3 @@ PJ_DEF(void) pj_hmac_md5( const pj_uint8_t *input, unsigned input_len,
pj_hmac_md5_update(&ctx, input, input_len);
pj_hmac_md5_final(&ctx, digest);
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,14 +14,14 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/hmac_sha1.h>
#include <pj/string.h>
PJ_DEF(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx,
const pj_uint8_t *key, unsigned key_len)
PJ_DEF(void)
pj_hmac_sha1_init(pj_hmac_sha1_context* hctx, const pj_uint8_t* key,
unsigned key_len)
{
pj_uint8_t k_ipad[64];
pj_uint8_t tk[20];
@ -30,7 +29,7 @@ PJ_DEF(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx,
/* if key is longer than 64 bytes reset it to key=SHA1(key) */
if (key_len > 64) {
pj_sha1_context tctx;
pj_sha1_context tctx;
pj_sha1_init(&tctx);
pj_sha1_update(&tctx, key, key_len);
@ -45,13 +44,13 @@ PJ_DEF(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx,
*/
/* start out by storing key in pads */
pj_bzero( k_ipad, sizeof(k_ipad));
pj_bzero( hctx->k_opad, sizeof(hctx->k_opad));
pj_memcpy( k_ipad, key, key_len);
pj_memcpy( hctx->k_opad, key, key_len);
pj_bzero(k_ipad, sizeof(k_ipad));
pj_bzero(hctx->k_opad, sizeof(hctx->k_opad));
pj_memcpy(k_ipad, key, key_len);
pj_memcpy(hctx->k_opad, key, key_len);
/* XOR key with ipad and opad values */
for (i=0; i<64; i++) {
for (i = 0; i < 64; i++) {
k_ipad[i] ^= 0x36;
hctx->k_opad[i] ^= 0x5c;
}
@ -62,14 +61,15 @@ PJ_DEF(void) pj_hmac_sha1_init(pj_hmac_sha1_context *hctx,
pj_sha1_update(&hctx->context, k_ipad, 64);
}
PJ_DEF(void) pj_hmac_sha1_update(pj_hmac_sha1_context *hctx,
const pj_uint8_t *input, unsigned input_len)
PJ_DEF(void)
pj_hmac_sha1_update(pj_hmac_sha1_context* hctx, const pj_uint8_t* input,
unsigned input_len)
{
pj_sha1_update(&hctx->context, input, input_len);
}
PJ_DEF(void) pj_hmac_sha1_final(pj_hmac_sha1_context *hctx,
pj_uint8_t digest[20])
PJ_DEF(void)
pj_hmac_sha1_final(pj_hmac_sha1_context* hctx, pj_uint8_t digest[20])
{
pj_sha1_final(&hctx->context, digest);
@ -82,9 +82,9 @@ PJ_DEF(void) pj_hmac_sha1_final(pj_hmac_sha1_context *hctx,
pj_sha1_final(&hctx->context, digest);
}
PJ_DEF(void) pj_hmac_sha1(const pj_uint8_t *input, unsigned input_len,
const pj_uint8_t *key, unsigned key_len,
pj_uint8_t digest[20] )
PJ_DEF(void)
pj_hmac_sha1(const pj_uint8_t* input, unsigned input_len, const pj_uint8_t* key,
unsigned key_len, pj_uint8_t digest[20])
{
pj_hmac_sha1_context ctx;
@ -92,4 +92,3 @@ PJ_DEF(void) pj_hmac_sha1(const pj_uint8_t *input, unsigned input_len,
pj_hmac_sha1_update(&ctx, input, input_len);
pj_hmac_sha1_final(&ctx, digest);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,3 @@
/* $Id$ */
/*
* Copyright (C) 2013 Teluu Inc. (http://www.teluu.com)
*
@ -24,67 +23,64 @@
#include <pj/except.h>
#include <pj/string.h>
#define EL_INIT(p_el, nm, typ) do { \
if (nm) { \
p_el->name = *nm; \
} else { \
p_el->name.ptr = (char*)""; \
p_el->name.slen = 0; \
} \
p_el->type = typ; \
} while (0)
#define EL_INIT(p_el, nm, typ) \
do { \
if (nm) { \
p_el->name = *nm; \
} else { \
p_el->name.ptr = (char*)""; \
p_el->name.slen = 0; \
} \
p_el->type = typ; \
} while (0)
struct write_state;
struct parse_state;
#define NO_NAME 1
#define NO_NAME 1
static pj_status_t elem_write(const pj_json_elem *elem,
struct write_state *st,
static pj_status_t elem_write(const pj_json_elem* elem, struct write_state* st,
unsigned flags);
static pj_json_elem* parse_elem_throw(struct parse_state *st,
pj_json_elem *elem);
static pj_json_elem* parse_elem_throw(struct parse_state* st,
pj_json_elem* elem);
PJ_DEF(void) pj_json_elem_null(pj_json_elem *el, pj_str_t *name)
PJ_DEF(void) pj_json_elem_null(pj_json_elem* el, pj_str_t* name)
{
EL_INIT(el, name, PJ_JSON_VAL_NULL);
}
PJ_DEF(void) pj_json_elem_bool(pj_json_elem *el, pj_str_t *name,
pj_bool_t val)
PJ_DEF(void) pj_json_elem_bool(pj_json_elem* el, pj_str_t* name, pj_bool_t val)
{
EL_INIT(el, name, PJ_JSON_VAL_BOOL);
el->value.is_true = val;
}
PJ_DEF(void) pj_json_elem_number(pj_json_elem *el, pj_str_t *name,
float val)
PJ_DEF(void) pj_json_elem_number(pj_json_elem* el, pj_str_t* name, float val)
{
EL_INIT(el, name, PJ_JSON_VAL_NUMBER);
el->value.num = val;
}
PJ_DEF(void) pj_json_elem_string( pj_json_elem *el, pj_str_t *name,
pj_str_t *value)
PJ_DEF(void)
pj_json_elem_string(pj_json_elem* el, pj_str_t* name, pj_str_t* value)
{
EL_INIT(el, name, PJ_JSON_VAL_STRING);
el->value.str = *value;
}
PJ_DEF(void) pj_json_elem_array(pj_json_elem *el, pj_str_t *name)
PJ_DEF(void) pj_json_elem_array(pj_json_elem* el, pj_str_t* name)
{
EL_INIT(el, name, PJ_JSON_VAL_ARRAY);
pj_list_init(&el->value.children);
}
PJ_DEF(void) pj_json_elem_obj(pj_json_elem *el, pj_str_t *name)
PJ_DEF(void) pj_json_elem_obj(pj_json_elem* el, pj_str_t* name)
{
EL_INIT(el, name, PJ_JSON_VAL_OBJ);
pj_list_init(&el->value.children);
}
PJ_DEF(void) pj_json_elem_add(pj_json_elem *el, pj_json_elem *child)
PJ_DEF(void) pj_json_elem_add(pj_json_elem* el, pj_json_elem* child)
{
pj_assert(el->type == PJ_JSON_VAL_OBJ || el->type == PJ_JSON_VAL_ARRAY);
pj_list_push_back(&el->value.children, child);
@ -92,33 +88,32 @@ PJ_DEF(void) pj_json_elem_add(pj_json_elem *el, pj_json_elem *child)
struct parse_state
{
pj_pool_t *pool;
pj_scanner scanner;
pj_json_err_info *err_info;
pj_cis_t float_spec; /* numbers with dot! */
pj_pool_t* pool;
pj_scanner scanner;
pj_json_err_info* err_info;
pj_cis_t float_spec; /* numbers with dot! */
};
static pj_status_t parse_children(struct parse_state *st,
pj_json_elem *parent)
static pj_status_t parse_children(struct parse_state* st, pj_json_elem* parent)
{
char end_quote = (parent->type == PJ_JSON_VAL_ARRAY)? ']' : '}';
char end_quote = (parent->type == PJ_JSON_VAL_ARRAY) ? ']' : '}';
pj_scan_get_char(&st->scanner);
while (*st->scanner.curptr != end_quote) {
pj_json_elem *child;
pj_json_elem* child;
while (*st->scanner.curptr == ',')
pj_scan_get_char(&st->scanner);
while (*st->scanner.curptr == ',')
pj_scan_get_char(&st->scanner);
if (*st->scanner.curptr == end_quote)
break;
if (*st->scanner.curptr == end_quote)
break;
child = parse_elem_throw(st, NULL);
if (!child)
return PJLIB_UTIL_EINJSON;
child = parse_elem_throw(st, NULL);
if (!child)
return PJLIB_UTIL_EINJSON;
pj_json_elem_add(parent, child);
pj_json_elem_add(parent, child);
}
pj_scan_get_char(&st->scanner);
@ -126,8 +121,7 @@ static pj_status_t parse_children(struct parse_state *st,
}
/* Return 0 if success or the index of the invalid char in the string */
static unsigned parse_quoted_string(struct parse_state *st,
pj_str_t *output)
static unsigned parse_quoted_string(struct parse_state* st, pj_str_t* output)
{
pj_str_t token;
char *op, *ip, *iend;
@ -136,11 +130,11 @@ static unsigned parse_quoted_string(struct parse_state *st,
/* Remove the quote characters */
token.ptr++;
token.slen-=2;
token.slen -= 2;
if (pj_strchr(&token, '\\') == NULL) {
*output = token;
return 0;
*output = token;
return 0;
}
output->ptr = op = pj_pool_alloc(st->pool, token.slen);
@ -149,45 +143,45 @@ static unsigned parse_quoted_string(struct parse_state *st,
iend = token.ptr + token.slen;
while (ip != iend) {
if (*ip == '\\') {
++ip;
if (ip==iend) {
goto on_error;
}
if (*ip == 'u') {
ip++;
if (iend - ip < 4) {
ip = iend -1;
goto on_error;
}
/* Only use the last two hext digits because we're on
* ASCII */
*op++ = (char)(pj_hex_digit_to_val(ip[2]) * 16 +
pj_hex_digit_to_val(ip[3]));
ip += 4;
} else if (*ip=='"' || *ip=='\\' || *ip=='/') {
*op++ = *ip++;
} else if (*ip=='b') {
*op++ = '\b';
ip++;
} else if (*ip=='f') {
*op++ = '\f';
ip++;
} else if (*ip=='n') {
*op++ = '\n';
ip++;
} else if (*ip=='r') {
*op++ = '\r';
ip++;
} else if (*ip=='t') {
*op++ = '\t';
ip++;
} else {
goto on_error;
}
} else {
*op++ = *ip++;
}
if (*ip == '\\') {
++ip;
if (ip == iend) {
goto on_error;
}
if (*ip == 'u') {
ip++;
if (iend - ip < 4) {
ip = iend - 1;
goto on_error;
}
/* Only use the last two hext digits because we're on
* ASCII */
*op++ = (char)(pj_hex_digit_to_val(ip[2]) * 16 +
pj_hex_digit_to_val(ip[3]));
ip += 4;
} else if (*ip == '"' || *ip == '\\' || *ip == '/') {
*op++ = *ip++;
} else if (*ip == 'b') {
*op++ = '\b';
ip++;
} else if (*ip == 'f') {
*op++ = '\f';
ip++;
} else if (*ip == 'n') {
*op++ = '\n';
ip++;
} else if (*ip == 'r') {
*op++ = '\r';
ip++;
} else if (*ip == 't') {
*op++ = '\t';
ip++;
} else {
goto on_error;
}
} else {
*op++ = *ip++;
}
}
output->slen = op - output->ptr;
@ -198,117 +192,116 @@ on_error:
return (unsigned)(ip - token.ptr);
}
static pj_json_elem* parse_elem_throw(struct parse_state *st,
pj_json_elem *elem)
static pj_json_elem* parse_elem_throw(struct parse_state* st,
pj_json_elem* elem)
{
pj_str_t name = {NULL, 0}, value = {NULL, 0};
pj_str_t name = { NULL, 0 }, value = { NULL, 0 };
pj_str_t token;
if (!elem)
elem = pj_pool_alloc(st->pool, sizeof(*elem));
elem = pj_pool_alloc(st->pool, sizeof(*elem));
/* Parse name */
if (*st->scanner.curptr == '"') {
pj_scan_get_char(&st->scanner);
pj_scan_get_until_ch(&st->scanner, '"', &token);
pj_scan_get_char(&st->scanner);
pj_scan_get_char(&st->scanner);
pj_scan_get_until_ch(&st->scanner, '"', &token);
pj_scan_get_char(&st->scanner);
if (*st->scanner.curptr == ':') {
pj_scan_get_char(&st->scanner);
name = token;
} else {
value = token;
}
if (*st->scanner.curptr == ':') {
pj_scan_get_char(&st->scanner);
name = token;
} else {
value = token;
}
}
if (value.slen) {
/* Element with string value and no name */
pj_json_elem_string(elem, &name, &value);
return elem;
/* Element with string value and no name */
pj_json_elem_string(elem, &name, &value);
return elem;
}
/* Parse value */
if (pj_cis_match(&st->float_spec, *st->scanner.curptr) ||
*st->scanner.curptr == '-')
*st->scanner.curptr == '-')
{
float val;
pj_bool_t neg = PJ_FALSE;
float val;
pj_bool_t neg = PJ_FALSE;
if (*st->scanner.curptr == '-') {
pj_scan_get_char(&st->scanner);
neg = PJ_TRUE;
}
if (*st->scanner.curptr == '-') {
pj_scan_get_char(&st->scanner);
neg = PJ_TRUE;
}
pj_scan_get(&st->scanner, &st->float_spec, &token);
val = pj_strtof(&token);
if (neg) val = -val;
pj_scan_get(&st->scanner, &st->float_spec, &token);
val = pj_strtof(&token);
if (neg)
val = -val;
pj_json_elem_number(elem, &name, val);
pj_json_elem_number(elem, &name, val);
} else if (*st->scanner.curptr == '"') {
unsigned err;
char *start = st->scanner.curptr;
unsigned err;
char* start = st->scanner.curptr;
err = parse_quoted_string(st, &token);
if (err) {
st->scanner.curptr = start + err;
return NULL;
}
err = parse_quoted_string(st, &token);
if (err) {
st->scanner.curptr = start + err;
return NULL;
}
pj_json_elem_string(elem, &name, &token);
pj_json_elem_string(elem, &name, &token);
} else if (pj_isalpha(*st->scanner.curptr)) {
if (pj_scan_strcmp(&st->scanner, "false", 5)==0) {
pj_json_elem_bool(elem, &name, PJ_FALSE);
pj_scan_advance_n(&st->scanner, 5, PJ_TRUE);
} else if (pj_scan_strcmp(&st->scanner, "true", 4)==0) {
pj_json_elem_bool(elem, &name, PJ_TRUE);
pj_scan_advance_n(&st->scanner, 4, PJ_TRUE);
} else if (pj_scan_strcmp(&st->scanner, "null", 4)==0) {
pj_json_elem_null(elem, &name);
pj_scan_advance_n(&st->scanner, 4, PJ_TRUE);
} else {
return NULL;
}
if (pj_scan_strcmp(&st->scanner, "false", 5) == 0) {
pj_json_elem_bool(elem, &name, PJ_FALSE);
pj_scan_advance_n(&st->scanner, 5, PJ_TRUE);
} else if (pj_scan_strcmp(&st->scanner, "true", 4) == 0) {
pj_json_elem_bool(elem, &name, PJ_TRUE);
pj_scan_advance_n(&st->scanner, 4, PJ_TRUE);
} else if (pj_scan_strcmp(&st->scanner, "null", 4) == 0) {
pj_json_elem_null(elem, &name);
pj_scan_advance_n(&st->scanner, 4, PJ_TRUE);
} else {
return NULL;
}
} else if (*st->scanner.curptr == '[') {
pj_json_elem_array(elem, &name);
if (parse_children(st, elem) != PJ_SUCCESS)
return NULL;
pj_json_elem_array(elem, &name);
if (parse_children(st, elem) != PJ_SUCCESS)
return NULL;
} else if (*st->scanner.curptr == '{') {
pj_json_elem_obj(elem, &name);
if (parse_children(st, elem) != PJ_SUCCESS)
return NULL;
pj_json_elem_obj(elem, &name);
if (parse_children(st, elem) != PJ_SUCCESS)
return NULL;
} else {
return NULL;
return NULL;
}
return elem;
}
static void on_syntax_error(pj_scanner *scanner)
static void on_syntax_error(pj_scanner* scanner)
{
PJ_UNUSED_ARG(scanner);
PJ_THROW(11);
}
PJ_DEF(pj_json_elem*) pj_json_parse(pj_pool_t *pool,
char *buffer,
unsigned *size,
pj_json_err_info *err_info)
PJ_DEF(pj_json_elem*)
pj_json_parse(pj_pool_t* pool, char* buffer, unsigned* size,
pj_json_err_info* err_info)
{
pj_cis_buf_t cis_buf;
struct parse_state st;
pj_json_elem *root;
pj_json_elem* root;
PJ_USE_EXCEPTION;
PJ_ASSERT_RETURN(pool && buffer && size, NULL);
if (!*size)
return NULL;
return NULL;
pj_bzero(&st, sizeof(st));
st.pool = pool;
@ -320,18 +313,20 @@ PJ_DEF(pj_json_elem*) pj_json_parse(pj_pool_t *pool,
pj_cis_init(&cis_buf, &st.float_spec);
pj_cis_add_str(&st.float_spec, ".0123456789");
PJ_TRY {
root = parse_elem_throw(&st, NULL);
PJ_TRY
{
root = parse_elem_throw(&st, NULL);
}
PJ_CATCH_ANY {
root = NULL;
PJ_CATCH_ANY
{
root = NULL;
}
PJ_END
if (!root && err_info) {
err_info->line = st.scanner.line;
err_info->col = pj_scan_get_col(&st.scanner) + 1;
err_info->err_char = *st.scanner.curptr;
err_info->line = st.scanner.line;
err_info->col = pj_scan_get_col(&st.scanner) + 1;
err_info->err_char = *st.scanner.curptr;
}
*size = (unsigned)((buffer + *size) - st.scanner.curptr);
@ -343,17 +338,15 @@ PJ_DEF(pj_json_elem*) pj_json_parse(pj_pool_t *pool,
struct buf_writer_data
{
char *pos;
unsigned size;
char* pos;
unsigned size;
};
static pj_status_t buf_writer(const char *s,
unsigned size,
void *user_data)
static pj_status_t buf_writer(const char* s, unsigned size, void* user_data)
{
struct buf_writer_data *buf_data = (struct buf_writer_data*)user_data;
if (size+1 >= buf_data->size)
return PJ_ETOOBIG;
struct buf_writer_data* buf_data = (struct buf_writer_data*)user_data;
if (size + 1 >= buf_data->size)
return PJ_ETOOBIG;
pj_memcpy(buf_data->pos, s, size);
buf_data->pos += size;
@ -362,8 +355,8 @@ static pj_status_t buf_writer(const char *s,
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pj_json_write(const pj_json_elem *elem,
char *buffer, unsigned *size)
PJ_DEF(pj_status_t)
pj_json_write(const pj_json_elem* elem, char* buffer, unsigned* size)
{
struct buf_writer_data buf_data;
pj_status_t status;
@ -375,227 +368,225 @@ PJ_DEF(pj_status_t) pj_json_write(const pj_json_elem *elem,
status = pj_json_writef(elem, &buf_writer, &buf_data);
if (status != PJ_SUCCESS)
return status;
return status;
*buf_data.pos = '\0';
*size = (unsigned)(buf_data.pos - buffer);
return PJ_SUCCESS;
}
#define MAX_INDENT 100
#define MAX_INDENT 100
#ifndef PJ_JSON_NAME_MIN_LEN
# define PJ_JSON_NAME_MIN_LEN 20
# define PJ_JSON_NAME_MIN_LEN 20
#endif
#define ESC_BUF_LEN 64
#define ESC_BUF_LEN 64
#ifndef PJ_JSON_INDENT_SIZE
# define PJ_JSON_INDENT_SIZE 3
# define PJ_JSON_INDENT_SIZE 3
#endif
struct write_state
{
pj_json_writer writer;
void *user_data;
char indent_buf[MAX_INDENT];
int indent;
char space[PJ_JSON_NAME_MIN_LEN];
pj_json_writer writer;
void* user_data;
char indent_buf[MAX_INDENT];
int indent;
char space[PJ_JSON_NAME_MIN_LEN];
};
#define CHECK(expr) do { \
status=expr; if (status!=PJ_SUCCESS) return status; } \
while (0)
#define CHECK(expr) \
do { \
status = expr; \
if (status != PJ_SUCCESS) \
return status; \
} while (0)
static pj_status_t write_string_escaped(const pj_str_t *value,
struct write_state *st)
static pj_status_t write_string_escaped(const pj_str_t* value,
struct write_state* st)
{
const char *ip = value->ptr;
const char *iend = value->ptr + value->slen;
const char* ip = value->ptr;
const char* iend = value->ptr + value->slen;
char buf[ESC_BUF_LEN];
char *op = buf;
char *oend = buf + ESC_BUF_LEN;
char* op = buf;
char* oend = buf + ESC_BUF_LEN;
pj_status_t status;
while (ip != iend) {
/* Write to buffer to speedup writing instead of calling
* the callback one by one for each character.
*/
while (ip != iend && op != oend) {
if (oend - op < 2)
break;
/* Write to buffer to speedup writing instead of calling
* the callback one by one for each character.
*/
while (ip != iend && op != oend) {
if (oend - op < 2)
break;
if (*ip == '"') {
*op++ = '\\';
*op++ = '"';
ip++;
} else if (*ip == '\\') {
*op++ = '\\';
*op++ = '\\';
ip++;
} else if (*ip == '/') {
*op++ = '\\';
*op++ = '/';
ip++;
} else if (*ip == '\b') {
*op++ = '\\';
*op++ = 'b';
ip++;
} else if (*ip == '\f') {
*op++ = '\\';
*op++ = 'f';
ip++;
} else if (*ip == '\n') {
*op++ = '\\';
*op++ = 'n';
ip++;
} else if (*ip == '\r') {
*op++ = '\\';
*op++ = 'r';
ip++;
} else if (*ip == '\t') {
*op++ = '\\';
*op++ = 't';
ip++;
} else if ((*ip >= 32 && *ip < 127)) {
/* unescaped */
*op++ = *ip++;
} else {
/* escaped */
if (oend - op < 6)
break;
*op++ = '\\';
*op++ = 'u';
*op++ = '0';
*op++ = '0';
pj_val_to_hex_digit(*ip, op);
op+=2;
ip++;
}
}
if (*ip == '"') {
*op++ = '\\';
*op++ = '"';
ip++;
} else if (*ip == '\\') {
*op++ = '\\';
*op++ = '\\';
ip++;
} else if (*ip == '/') {
*op++ = '\\';
*op++ = '/';
ip++;
} else if (*ip == '\b') {
*op++ = '\\';
*op++ = 'b';
ip++;
} else if (*ip == '\f') {
*op++ = '\\';
*op++ = 'f';
ip++;
} else if (*ip == '\n') {
*op++ = '\\';
*op++ = 'n';
ip++;
} else if (*ip == '\r') {
*op++ = '\\';
*op++ = 'r';
ip++;
} else if (*ip == '\t') {
*op++ = '\\';
*op++ = 't';
ip++;
} else if ((*ip >= 32 && *ip < 127)) {
/* unescaped */
*op++ = *ip++;
} else {
/* escaped */
if (oend - op < 6)
break;
*op++ = '\\';
*op++ = 'u';
*op++ = '0';
*op++ = '0';
pj_val_to_hex_digit(*ip, op);
op += 2;
ip++;
}
}
CHECK( st->writer( buf, (unsigned)(op-buf), st->user_data) );
op = buf;
CHECK(st->writer(buf, (unsigned)(op - buf), st->user_data));
op = buf;
}
return PJ_SUCCESS;
}
static pj_status_t write_children(const pj_json_list *list,
const char quotes[2],
struct write_state *st)
static pj_status_t write_children(const pj_json_list* list,
const char quotes[2], struct write_state* st)
{
unsigned flags = (quotes[0]=='[') ? NO_NAME : 0;
unsigned flags = (quotes[0] == '[') ? NO_NAME : 0;
pj_status_t status;
//CHECK( st->writer( st->indent_buf, st->indent, st->user_data) );
CHECK( st->writer( &quotes[0], 1, st->user_data) );
CHECK( st->writer( " ", 1, st->user_data) );
// CHECK( st->writer( st->indent_buf, st->indent, st->user_data) );
CHECK(st->writer(&quotes[0], 1, st->user_data));
CHECK(st->writer(" ", 1, st->user_data));
if (!pj_list_empty(list)) {
pj_bool_t indent_added = PJ_FALSE;
pj_json_elem *child = list->next;
pj_bool_t indent_added = PJ_FALSE;
pj_json_elem* child = list->next;
if (child->name.slen == 0) {
/* Simple list */
while (child != (pj_json_elem*)list) {
status = elem_write(child, st, flags);
if (status != PJ_SUCCESS)
return status;
if (child->name.slen == 0) {
/* Simple list */
while (child != (pj_json_elem*)list) {
status = elem_write(child, st, flags);
if (status != PJ_SUCCESS)
return status;
if (child->next != (pj_json_elem*)list)
CHECK( st->writer( ", ", 2, st->user_data) );
child = child->next;
}
} else {
if (st->indent < sizeof(st->indent_buf)) {
st->indent += PJ_JSON_INDENT_SIZE;
indent_added = PJ_TRUE;
}
CHECK( st->writer( "\n", 1, st->user_data) );
while (child != (pj_json_elem*)list) {
status = elem_write(child, st, flags);
if (status != PJ_SUCCESS)
return status;
if (child->next != (pj_json_elem*)list)
CHECK(st->writer(", ", 2, st->user_data));
child = child->next;
}
} else {
if (st->indent < sizeof(st->indent_buf)) {
st->indent += PJ_JSON_INDENT_SIZE;
indent_added = PJ_TRUE;
}
CHECK(st->writer("\n", 1, st->user_data));
while (child != (pj_json_elem*)list) {
status = elem_write(child, st, flags);
if (status != PJ_SUCCESS)
return status;
if (child->next != (pj_json_elem*)list)
CHECK( st->writer( ",\n", 2, st->user_data) );
else
CHECK( st->writer( "\n", 1, st->user_data) );
child = child->next;
}
if (indent_added) {
st->indent -= PJ_JSON_INDENT_SIZE;
}
CHECK( st->writer( st->indent_buf, st->indent, st->user_data) );
}
if (child->next != (pj_json_elem*)list)
CHECK(st->writer(",\n", 2, st->user_data));
else
CHECK(st->writer("\n", 1, st->user_data));
child = child->next;
}
if (indent_added) {
st->indent -= PJ_JSON_INDENT_SIZE;
}
CHECK(st->writer(st->indent_buf, st->indent, st->user_data));
}
}
CHECK( st->writer( &quotes[1], 1, st->user_data) );
CHECK(st->writer(&quotes[1], 1, st->user_data));
return PJ_SUCCESS;
}
static pj_status_t elem_write(const pj_json_elem *elem,
struct write_state *st,
static pj_status_t elem_write(const pj_json_elem* elem, struct write_state* st,
unsigned flags)
{
pj_status_t status;
if (elem->name.slen) {
CHECK( st->writer( st->indent_buf, st->indent, st->user_data) );
if ((flags & NO_NAME)==0) {
CHECK( st->writer( "\"", 1, st->user_data) );
CHECK( write_string_escaped(&elem->name, st) );
CHECK( st->writer( "\": ", 3, st->user_data) );
if (elem->name.slen < PJ_JSON_NAME_MIN_LEN /*&&
CHECK(st->writer(st->indent_buf, st->indent, st->user_data));
if ((flags & NO_NAME) == 0) {
CHECK(st->writer("\"", 1, st->user_data));
CHECK(write_string_escaped(&elem->name, st));
CHECK(st->writer("\": ", 3, st->user_data));
if (elem->name.slen < PJ_JSON_NAME_MIN_LEN /*&&
elem->type != PJ_JSON_VAL_OBJ &&
elem->type != PJ_JSON_VAL_ARRAY*/)
{
CHECK( st->writer( st->space,
(unsigned)(PJ_JSON_NAME_MIN_LEN -
elem->name.slen),
st->user_data) );
}
}
{
CHECK(st->writer(
st->space, (unsigned)(PJ_JSON_NAME_MIN_LEN - elem->name.slen),
st->user_data));
}
}
}
switch (elem->type) {
case PJ_JSON_VAL_NULL:
CHECK( st->writer( "null", 4, st->user_data) );
break;
CHECK(st->writer("null", 4, st->user_data));
break;
case PJ_JSON_VAL_BOOL:
if (elem->value.is_true)
CHECK( st->writer( "true", 4, st->user_data) );
else
CHECK( st->writer( "false", 5, st->user_data) );
break;
case PJ_JSON_VAL_NUMBER:
{
char num_buf[65];
int len;
if (elem->value.is_true)
CHECK(st->writer("true", 4, st->user_data));
else
CHECK(st->writer("false", 5, st->user_data));
break;
case PJ_JSON_VAL_NUMBER: {
char num_buf[65];
int len;
if (elem->value.num == (int)elem->value.num)
len = pj_ansi_snprintf(num_buf, sizeof(num_buf), "%d",
(int)elem->value.num);
else
len = pj_ansi_snprintf(num_buf, sizeof(num_buf), "%f",
elem->value.num);
if (elem->value.num == (int)elem->value.num)
len = pj_ansi_snprintf(num_buf, sizeof(num_buf), "%d",
(int)elem->value.num);
else
len =
pj_ansi_snprintf(num_buf, sizeof(num_buf), "%f", elem->value.num);
if (len < 0 || len >= sizeof(num_buf))
return PJ_ETOOBIG;
CHECK( st->writer( num_buf, len, st->user_data) );
}
break;
if (len < 0 || len >= sizeof(num_buf))
return PJ_ETOOBIG;
CHECK(st->writer(num_buf, len, st->user_data));
} break;
case PJ_JSON_VAL_STRING:
CHECK( st->writer( "\"", 1, st->user_data) );
CHECK( write_string_escaped( &elem->value.str, st) );
CHECK( st->writer( "\"", 1, st->user_data) );
break;
CHECK(st->writer("\"", 1, st->user_data));
CHECK(write_string_escaped(&elem->value.str, st));
CHECK(st->writer("\"", 1, st->user_data));
break;
case PJ_JSON_VAL_ARRAY:
CHECK( write_children(&elem->value.children, "[]", st) );
break;
CHECK(write_children(&elem->value.children, "[]", st));
break;
case PJ_JSON_VAL_OBJ:
CHECK( write_children(&elem->value.children, "{}", st) );
break;
CHECK(write_children(&elem->value.children, "{}", st));
break;
default:
pj_assert(!"Unhandled value type");
pj_assert(!"Unhandled value type");
}
return PJ_SUCCESS;
@ -603,20 +594,18 @@ static pj_status_t elem_write(const pj_json_elem *elem,
#undef CHECK
PJ_DEF(pj_status_t) pj_json_writef( const pj_json_elem *elem,
pj_json_writer writer,
void *user_data)
PJ_DEF(pj_status_t)
pj_json_writef(const pj_json_elem* elem, pj_json_writer writer, void* user_data)
{
struct write_state st;
PJ_ASSERT_RETURN(elem && writer, PJ_EINVAL);
st.writer = writer;
st.user_data = user_data;
st.indent = 0;
st.writer = writer;
st.user_data = user_data;
st.indent = 0;
pj_memset(st.indent_buf, ' ', MAX_INDENT);
pj_memset(st.space, ' ', PJ_JSON_NAME_MIN_LEN);
return elem_write(elem, &st, 0);
}

View File

@ -1,10 +1,9 @@
/* $Id$ */
/*
/*
* This is the implementation of MD5 algorithm, based on the code
* written by Colin Plumb. This file is put in public domain.
*/
#include <pjlib-util/md5.h>
#include <pj/string.h> /* pj_memcpy */
#include <pj/string.h> /* pj_memcpy */
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
@ -23,39 +22,38 @@
*/
#if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN != 0
#define HIGHFIRST 1
# define HIGHFIRST 1
#endif
#ifndef HIGHFIRST
#define byteReverse(buf, len) /* Nothing */
# define byteReverse(buf, len) /* Nothing */
#else
static void byteReverse(unsigned char *buf, unsigned longs);
static void byteReverse(unsigned char* buf, unsigned longs);
#ifndef ASM_MD5
# ifndef ASM_MD5
/*
* Note: this code is harmless on little-endian machines.
*/
static void byteReverse(unsigned char *buf, unsigned longs)
static void byteReverse(unsigned char* buf, unsigned longs)
{
pj_uint32_t t;
do {
t = (pj_uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(pj_uint32_t *) buf = t;
buf += 4;
t = (pj_uint32_t)((unsigned)buf[3] << 8 | buf[2]) << 16 |
((unsigned)buf[1] << 8 | buf[0]);
*(pj_uint32_t*)buf = t;
buf += 4;
} while (--longs);
}
#endif
# endif
#endif
static void MD5Transform(pj_uint32_t buf[4], pj_uint32_t const in[16]);
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
PJ_DEF(void) pj_md5_init(pj_md5_context *ctx)
PJ_DEF(void) pj_md5_init(pj_md5_context* ctx)
{
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
@ -70,44 +68,44 @@ PJ_DEF(void) pj_md5_init(pj_md5_context *ctx)
* Update context to reflect the concatenation of another buffer full
* of bytes.
*/
PJ_DEF(void) pj_md5_update( pj_md5_context *ctx,
unsigned char const *buf, unsigned len)
PJ_DEF(void)
pj_md5_update(pj_md5_context* ctx, unsigned char const* buf, unsigned len)
{
pj_uint32_t t;
/* Update bitcount */
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((pj_uint32_t) len << 3)) < t)
ctx->bits[1]++; /* Carry from low to high */
if ((ctx->bits[0] = t + ((pj_uint32_t)len << 3)) < t)
ctx->bits[1]++; /* Carry from low to high */
ctx->bits[1] += len >> 29;
t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
/* Handle any leading odd-sized chunks */
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
unsigned char* p = (unsigned char*)ctx->in + t;
t = 64 - t;
if (len < t) {
pj_memcpy(p, buf, len);
return;
}
pj_memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in);
buf += t;
len -= t;
t = 64 - t;
if (len < t) {
pj_memcpy(p, buf, len);
return;
}
pj_memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (pj_uint32_t*)ctx->in);
buf += t;
len -= t;
}
/* Process data in 64-byte chunks */
while (len >= 64) {
pj_memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in);
buf += 64;
len -= 64;
pj_memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (pj_uint32_t*)ctx->in);
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
@ -116,13 +114,13 @@ PJ_DEF(void) pj_md5_update( pj_md5_context *ctx,
}
/*
* Final wrapup - pad to 64-byte boundary with the bit pattern
* Final wrapup - pad to 64-byte boundary with the bit pattern
* 1 0* (64-bit count of bits processed, MSB-first)
*/
PJ_DEF(void) pj_md5_final(pj_md5_context *ctx, unsigned char digest[16])
PJ_DEF(void) pj_md5_final(pj_md5_context* ctx, unsigned char digest[16])
{
unsigned count;
unsigned char *p;
unsigned char* p;
/* Compute number of bytes mod 64 */
count = (ctx->bits[0] >> 3) & 0x3F;
@ -137,16 +135,16 @@ PJ_DEF(void) pj_md5_final(pj_md5_context *ctx, unsigned char digest[16])
/* Pad out to 56 mod 64 */
if (count < 8) {
/* Two lots of padding: Pad the first block to 64 bytes */
pj_bzero(p, count);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in);
/* Two lots of padding: Pad the first block to 64 bytes */
pj_bzero(p, count);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (pj_uint32_t*)ctx->in);
/* Now fill the next block with 56 bytes */
pj_bzero(ctx->in, 56);
/* Now fill the next block with 56 bytes */
pj_bzero(ctx->in, 56);
} else {
/* Pad block to 56 bytes */
pj_bzero(p, count - 8);
/* Pad block to 56 bytes */
pj_bzero(p, count - 8);
}
byteReverse(ctx->in, 14);
@ -156,10 +154,10 @@ PJ_DEF(void) pj_md5_final(pj_md5_context *ctx, unsigned char digest[16])
pj_memcpy(&ctx->in[14 << 2], &ctx->bits[0], sizeof(ctx->bits[0]));
pj_memcpy(&ctx->in[15 << 2], &ctx->bits[1], sizeof(ctx->bits[1]));
MD5Transform(ctx->buf, (pj_uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
MD5Transform(ctx->buf, (pj_uint32_t*)ctx->in);
byteReverse((unsigned char*)ctx->buf, 4);
pj_memcpy(digest, ctx->buf, 16);
pj_bzero(ctx, sizeof(*ctx)); /* In case it's sensitive */
pj_bzero(ctx, sizeof(*ctx)); /* In case it's sensitive */
}
#ifndef ASM_MD5
@ -167,14 +165,14 @@ PJ_DEF(void) pj_md5_final(pj_md5_context *ctx, unsigned char digest[16])
/* The four core functions - F1 is optimized somewhat */
/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
# define F1(x, y, z) (z ^ (x & (y ^ z)))
# define F2(x, y, z) F1(z, x, y)
# define F3(x, y, z) (x ^ y ^ z)
# define F4(x, y, z) (y ^ (x | ~z))
/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s) \
( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
# define MD5STEP(f, w, x, y, z, data, s) \
(w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
/*
* The core of the MD5 algorithm, this alters an existing MD5 hash to
@ -265,4 +263,3 @@ static void MD5Transform(pj_uint32_t buf[4], pj_uint32_t const in[16])
}
#endif

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/pcap.h>
#include <pj/assert.h>
@ -27,31 +26,30 @@
#include <pj/string.h>
#if 0
# define TRACE_(x) PJ_LOG(5,x)
# define TRACE_(x) PJ_LOG(5, x)
#else
# define TRACE_(x)
# define TRACE_(x)
#endif
#pragma pack(1)
typedef struct pj_pcap_hdr
typedef struct pj_pcap_hdr
{
pj_uint32_t magic_number; /* magic number */
pj_uint16_t version_major; /* major version number */
pj_uint16_t version_minor; /* minor version number */
pj_int32_t thiszone; /* GMT to local correction */
pj_uint32_t sigfigs; /* accuracy of timestamps */
pj_uint32_t snaplen; /* max length of captured packets, in octets */
pj_uint32_t network; /* data link type */
pj_uint32_t magic_number; /* magic number */
pj_uint16_t version_major; /* major version number */
pj_uint16_t version_minor; /* minor version number */
pj_int32_t thiszone; /* GMT to local correction */
pj_uint32_t sigfigs; /* accuracy of timestamps */
pj_uint32_t snaplen; /* max length of captured packets, in octets */
pj_uint32_t network; /* data link type */
} pj_pcap_hdr;
typedef struct pj_pcap_rec_hdr
typedef struct pj_pcap_rec_hdr
{
pj_uint32_t ts_sec; /* timestamp seconds */
pj_uint32_t ts_usec; /* timestamp microseconds */
pj_uint32_t incl_len; /* number of octets of packet saved in file */
pj_uint32_t orig_len; /* actual length of packet */
pj_uint32_t ts_sec; /* timestamp seconds */
pj_uint32_t ts_usec; /* timestamp microseconds */
pj_uint32_t incl_len; /* number of octets of packet saved in file */
pj_uint32_t orig_len; /* actual length of packet */
} pj_pcap_rec_hdr;
#if 0
@ -66,96 +64,92 @@ typedef struct pj_pcap_eth_hdr
typedef pj_uint8_t pj_pcap_eth_hdr[14];
#endif
typedef struct pj_pcap_ip_hdr
typedef struct pj_pcap_ip_hdr
{
pj_uint8_t v_ihl;
pj_uint8_t tos;
pj_uint16_t len;
pj_uint16_t id;
pj_uint16_t flags_fragment;
pj_uint8_t ttl;
pj_uint8_t proto;
pj_uint16_t csum;
pj_uint32_t ip_src;
pj_uint32_t ip_dst;
pj_uint8_t v_ihl;
pj_uint8_t tos;
pj_uint16_t len;
pj_uint16_t id;
pj_uint16_t flags_fragment;
pj_uint8_t ttl;
pj_uint8_t proto;
pj_uint16_t csum;
pj_uint32_t ip_src;
pj_uint32_t ip_dst;
} pj_pcap_ip_hdr;
/* Implementation of pcap file */
struct pj_pcap_file
{
char obj_name[PJ_MAX_OBJ_NAME];
pj_oshandle_t fd;
pj_bool_t swap;
pj_pcap_hdr hdr;
pj_pcap_filter filter;
char obj_name[PJ_MAX_OBJ_NAME];
pj_oshandle_t fd;
pj_bool_t swap;
pj_pcap_hdr hdr;
pj_pcap_filter filter;
};
#pragma pack()
/* Init default filter */
PJ_DEF(void) pj_pcap_filter_default(pj_pcap_filter *filter)
PJ_DEF(void) pj_pcap_filter_default(pj_pcap_filter* filter)
{
pj_bzero(filter, sizeof(*filter));
}
/* Open pcap file */
PJ_DEF(pj_status_t) pj_pcap_open(pj_pool_t *pool,
const char *path,
pj_pcap_file **p_file)
PJ_DEF(pj_status_t)
pj_pcap_open(pj_pool_t* pool, const char* path, pj_pcap_file** p_file)
{
pj_pcap_file *file;
pj_pcap_file* file;
pj_ssize_t sz;
pj_status_t status;
PJ_ASSERT_RETURN(pool && path && p_file, PJ_EINVAL);
/* More sanity checks */
TRACE_(("pcap", "sizeof(pj_pcap_eth_hdr)=%d",
sizeof(pj_pcap_eth_hdr)));
PJ_ASSERT_RETURN(sizeof(pj_pcap_eth_hdr)==14, PJ_EBUG);
TRACE_(("pcap", "sizeof(pj_pcap_ip_hdr)=%d",
sizeof(pj_pcap_ip_hdr)));
PJ_ASSERT_RETURN(sizeof(pj_pcap_ip_hdr)==20, PJ_EBUG);
TRACE_(("pcap", "sizeof(pj_pcap_udp_hdr)=%d",
sizeof(pj_pcap_udp_hdr)));
PJ_ASSERT_RETURN(sizeof(pj_pcap_udp_hdr)==8, PJ_EBUG);
TRACE_(("pcap", "sizeof(pj_pcap_eth_hdr)=%d", sizeof(pj_pcap_eth_hdr)));
PJ_ASSERT_RETURN(sizeof(pj_pcap_eth_hdr) == 14, PJ_EBUG);
TRACE_(("pcap", "sizeof(pj_pcap_ip_hdr)=%d", sizeof(pj_pcap_ip_hdr)));
PJ_ASSERT_RETURN(sizeof(pj_pcap_ip_hdr) == 20, PJ_EBUG);
TRACE_(("pcap", "sizeof(pj_pcap_udp_hdr)=%d", sizeof(pj_pcap_udp_hdr)));
PJ_ASSERT_RETURN(sizeof(pj_pcap_udp_hdr) == 8, PJ_EBUG);
file = PJ_POOL_ZALLOC_T(pool, pj_pcap_file);
pj_ansi_strcpy(file->obj_name, "pcap");
status = pj_file_open(pool, path, PJ_O_RDONLY, &file->fd);
if (status != PJ_SUCCESS)
return status;
return status;
/* Read file pcap header */
sz = sizeof(file->hdr);
status = pj_file_read(file->fd, &file->hdr, &sz);
if (status != PJ_SUCCESS) {
pj_file_close(file->fd);
return status;
pj_file_close(file->fd);
return status;
}
/* Check magic number */
if (file->hdr.magic_number == 0xa1b2c3d4) {
file->swap = PJ_FALSE;
file->swap = PJ_FALSE;
} else if (file->hdr.magic_number == 0xd4c3b2a1) {
file->swap = PJ_TRUE;
file->hdr.network = pj_ntohl(file->hdr.network);
file->swap = PJ_TRUE;
file->hdr.network = pj_ntohl(file->hdr.network);
} else {
/* Not PCAP file */
pj_file_close(file->fd);
return PJ_EINVALIDOP;
/* Not PCAP file */
pj_file_close(file->fd);
return PJ_EINVALIDOP;
}
TRACE_((file->obj_name, "PCAP file %s opened", path));
*p_file = file;
return PJ_SUCCESS;
}
/* Close pcap file */
PJ_DEF(pj_status_t) pj_pcap_close(pj_pcap_file *file)
PJ_DEF(pj_status_t) pj_pcap_close(pj_pcap_file* file)
{
PJ_ASSERT_RETURN(file, PJ_EINVAL);
TRACE_((file->obj_name, "PCAP file closed"));
@ -163,8 +157,8 @@ PJ_DEF(pj_status_t) pj_pcap_close(pj_pcap_file *file)
}
/* Setup filter */
PJ_DEF(pj_status_t) pj_pcap_set_filter(pj_pcap_file *file,
const pj_pcap_filter *fil)
PJ_DEF(pj_status_t)
pj_pcap_set_filter(pj_pcap_file* file, const pj_pcap_filter* fil)
{
PJ_ASSERT_RETURN(file && fil, PJ_EINVAL);
pj_memcpy(&file->filter, fil, sizeof(pj_pcap_filter));
@ -172,16 +166,14 @@ PJ_DEF(pj_status_t) pj_pcap_set_filter(pj_pcap_file *file,
}
/* Read file */
static pj_status_t read_file(pj_pcap_file *file,
void *buf,
pj_ssize_t *sz)
static pj_status_t read_file(pj_pcap_file* file, void* buf, pj_ssize_t* sz)
{
pj_status_t status;
status = pj_file_read(file->fd, buf, sz);
if (status != PJ_SUCCESS)
return status;
return status;
if (*sz == 0)
return PJ_EEOF;
return PJ_EEOF;
return PJ_SUCCESS;
}
@ -190,209 +182,205 @@ static pj_status_t skip(pj_oshandle_t fd, pj_off_t bytes)
pj_status_t status;
status = pj_file_setpos(fd, bytes, PJ_SEEK_CUR);
if (status != PJ_SUCCESS)
return status;
return status;
return PJ_SUCCESS;
}
#define SKIP_PKT() \
if (rec_incl > sz_read) { \
status = skip(file->fd, rec_incl-sz_read);\
if (status != PJ_SUCCESS) \
return status; \
}
#define SKIP_PKT() \
if (rec_incl > sz_read) { \
status = skip(file->fd, rec_incl - sz_read); \
if (status != PJ_SUCCESS) \
return status; \
}
/* Read UDP packet */
PJ_DEF(pj_status_t) pj_pcap_read_udp(pj_pcap_file *file,
pj_pcap_udp_hdr *udp_hdr,
pj_uint8_t *udp_payload,
pj_size_t *udp_payload_size)
PJ_DEF(pj_status_t)
pj_pcap_read_udp(pj_pcap_file* file, pj_pcap_udp_hdr* udp_hdr,
pj_uint8_t* udp_payload, pj_size_t* udp_payload_size)
{
PJ_ASSERT_RETURN(file && udp_payload && udp_payload_size, PJ_EINVAL);
PJ_ASSERT_RETURN(*udp_payload_size, PJ_EINVAL);
/* Check data link type in PCAP file header */
if ((file->filter.link &&
file->hdr.network != (pj_uint32_t)file->filter.link) ||
file->hdr.network != PJ_PCAP_LINK_TYPE_ETH)
if ((file->filter.link &&
file->hdr.network != (pj_uint32_t)file->filter.link) ||
file->hdr.network != PJ_PCAP_LINK_TYPE_ETH)
{
/* Link header other than Ethernet is not supported for now */
return PJ_ENOTSUP;
/* Link header other than Ethernet is not supported for now */
return PJ_ENOTSUP;
}
/* Loop until we have the packet */
for (;;) {
union {
pj_pcap_rec_hdr rec;
pj_pcap_eth_hdr eth;
pj_pcap_ip_hdr ip;
pj_pcap_udp_hdr udp;
} tmp;
unsigned rec_incl;
pj_ssize_t sz;
pj_size_t sz_read = 0;
char addr[PJ_INET_ADDRSTRLEN];
pj_status_t status;
union
{
pj_pcap_rec_hdr rec;
pj_pcap_eth_hdr eth;
pj_pcap_ip_hdr ip;
pj_pcap_udp_hdr udp;
} tmp;
unsigned rec_incl;
pj_ssize_t sz;
pj_size_t sz_read = 0;
char addr[PJ_INET_ADDRSTRLEN];
pj_status_t status;
TRACE_((file->obj_name, "Reading packet.."));
pj_bzero(&addr, sizeof(addr));
TRACE_((file->obj_name, "Reading packet.."));
pj_bzero(&addr, sizeof(addr));
/* Read PCAP packet header */
sz = sizeof(tmp.rec);
status = read_file(file, &tmp.rec, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "read_file() error: %d", status));
return status;
}
/* Read PCAP packet header */
sz = sizeof(tmp.rec);
status = read_file(file, &tmp.rec, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "read_file() error: %d", status));
return status;
}
rec_incl = tmp.rec.incl_len;
rec_incl = tmp.rec.incl_len;
/* Swap byte ordering */
if (file->swap) {
tmp.rec.incl_len = pj_ntohl(tmp.rec.incl_len);
tmp.rec.orig_len = pj_ntohl(tmp.rec.orig_len);
tmp.rec.ts_sec = pj_ntohl(tmp.rec.ts_sec);
tmp.rec.ts_usec = pj_ntohl(tmp.rec.ts_usec);
}
/* Swap byte ordering */
if (file->swap) {
tmp.rec.incl_len = pj_ntohl(tmp.rec.incl_len);
tmp.rec.orig_len = pj_ntohl(tmp.rec.orig_len);
tmp.rec.ts_sec = pj_ntohl(tmp.rec.ts_sec);
tmp.rec.ts_usec = pj_ntohl(tmp.rec.ts_usec);
}
/* Read link layer header */
switch (file->hdr.network) {
case PJ_PCAP_LINK_TYPE_ETH:
sz = sizeof(tmp.eth);
status = read_file(file, &tmp.eth, &sz);
break;
default:
TRACE_((file->obj_name, "Error: link layer not Ethernet"));
return PJ_ENOTSUP;
}
/* Read link layer header */
switch (file->hdr.network) {
case PJ_PCAP_LINK_TYPE_ETH:
sz = sizeof(tmp.eth);
status = read_file(file, &tmp.eth, &sz);
break;
default:
TRACE_((file->obj_name, "Error: link layer not Ethernet"));
return PJ_ENOTSUP;
}
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading Eth header: %d", status));
return status;
}
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading Eth header: %d", status));
return status;
}
sz_read += sz;
/* Read IP header */
sz = sizeof(tmp.ip);
status = read_file(file, &tmp.ip, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading IP header: %d", status));
return status;
}
sz_read += sz;
sz_read += sz;
/* Read IP header */
sz = sizeof(tmp.ip);
status = read_file(file, &tmp.ip, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading IP header: %d", status));
return status;
}
/* Skip if IP source mismatch */
if (file->filter.ip_src && tmp.ip.ip_src != file->filter.ip_src) {
TRACE_((file->obj_name, "IP source %s mismatch, skipping",
pj_inet_ntop2(pj_AF_INET(), (pj_in_addr*)&tmp.ip.ip_src,
addr, sizeof(addr))));
SKIP_PKT();
continue;
}
sz_read += sz;
/* Skip if IP destination mismatch */
if (file->filter.ip_dst && tmp.ip.ip_dst != file->filter.ip_dst) {
TRACE_((file->obj_name, "IP detination %s mismatch, skipping",
pj_inet_ntop2(pj_AF_INET(), (pj_in_addr*)&tmp.ip.ip_dst,
addr, sizeof(addr))));
SKIP_PKT();
continue;
}
/* Skip if IP source mismatch */
if (file->filter.ip_src && tmp.ip.ip_src != file->filter.ip_src) {
TRACE_((file->obj_name, "IP source %s mismatch, skipping",
pj_inet_ntop2(pj_AF_INET(), (pj_in_addr*)&tmp.ip.ip_src,
addr, sizeof(addr))));
SKIP_PKT();
continue;
}
/* Skip if proto mismatch */
if (file->filter.proto && tmp.ip.proto != file->filter.proto) {
TRACE_((file->obj_name, "IP proto %d mismatch, skipping",
tmp.ip.proto));
SKIP_PKT();
continue;
}
/* Skip if IP destination mismatch */
if (file->filter.ip_dst && tmp.ip.ip_dst != file->filter.ip_dst) {
TRACE_((file->obj_name, "IP detination %s mismatch, skipping",
pj_inet_ntop2(pj_AF_INET(), (pj_in_addr*)&tmp.ip.ip_dst,
addr, sizeof(addr))));
SKIP_PKT();
continue;
}
/* Read transport layer header */
switch (tmp.ip.proto) {
case PJ_PCAP_PROTO_TYPE_UDP:
sz = sizeof(tmp.udp);
status = read_file(file, &tmp.udp, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading UDP header: %d",status));
return status;
}
/* Skip if proto mismatch */
if (file->filter.proto && tmp.ip.proto != file->filter.proto) {
TRACE_(
(file->obj_name, "IP proto %d mismatch, skipping", tmp.ip.proto));
SKIP_PKT();
continue;
}
sz_read += sz;
/* Read transport layer header */
switch (tmp.ip.proto) {
case PJ_PCAP_PROTO_TYPE_UDP:
sz = sizeof(tmp.udp);
status = read_file(file, &tmp.udp, &sz);
if (status != PJ_SUCCESS) {
TRACE_(
(file->obj_name, "Error reading UDP header: %d", status));
return status;
}
/* Skip if source port mismatch */
if (file->filter.src_port &&
tmp.udp.src_port != file->filter.src_port)
{
TRACE_((file->obj_name, "UDP src port %d mismatch, skipping",
pj_ntohs(tmp.udp.src_port)));
SKIP_PKT();
continue;
}
sz_read += sz;
/* Skip if destination port mismatch */
if (file->filter.dst_port &&
tmp.udp.dst_port != file->filter.dst_port)
{
TRACE_((file->obj_name, "UDP dst port %d mismatch, skipping",
pj_ntohs(tmp.udp.dst_port)));
SKIP_PKT();
continue;
}
/* Skip if source port mismatch */
if (file->filter.src_port &&
tmp.udp.src_port != file->filter.src_port) {
TRACE_((file->obj_name, "UDP src port %d mismatch, skipping",
pj_ntohs(tmp.udp.src_port)));
SKIP_PKT();
continue;
}
/* Copy UDP header if caller wants it */
if (udp_hdr) {
pj_memcpy(udp_hdr, &tmp.udp, sizeof(*udp_hdr));
}
/* Skip if destination port mismatch */
if (file->filter.dst_port &&
tmp.udp.dst_port != file->filter.dst_port) {
TRACE_((file->obj_name, "UDP dst port %d mismatch, skipping",
pj_ntohs(tmp.udp.dst_port)));
SKIP_PKT();
continue;
}
/* Calculate payload size */
sz = pj_ntohs(tmp.udp.len) - sizeof(tmp.udp);
break;
default:
TRACE_((file->obj_name, "Not UDP, skipping"));
SKIP_PKT();
continue;
}
/* Copy UDP header if caller wants it */
if (udp_hdr) {
pj_memcpy(udp_hdr, &tmp.udp, sizeof(*udp_hdr));
}
/* Check if payload fits the buffer */
if (sz > (pj_ssize_t)*udp_payload_size) {
TRACE_((file->obj_name,
"Error: packet too large (%d bytes required)", sz));
SKIP_PKT();
return PJ_ETOOSMALL;
}
/* Calculate payload size */
sz = pj_ntohs(tmp.udp.len) - sizeof(tmp.udp);
break;
default:
TRACE_((file->obj_name, "Not UDP, skipping"));
SKIP_PKT();
continue;
}
/* Read the payload */
status = read_file(file, udp_payload, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading payload: %d", status));
return status;
}
/* Check if payload fits the buffer */
if (sz > (pj_ssize_t)*udp_payload_size) {
TRACE_((file->obj_name,
"Error: packet too large (%d bytes required)", sz));
SKIP_PKT();
return PJ_ETOOSMALL;
}
sz_read += sz;
/* Read the payload */
status = read_file(file, udp_payload, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading payload: %d", status));
return status;
}
*udp_payload_size = sz;
sz_read += sz;
// Some layers may have trailer, e.g: link eth2.
/* Check that we've read all the packets */
//PJ_ASSERT_RETURN(sz_read == rec_incl, PJ_EBUG);
*udp_payload_size = sz;
/* Skip trailer */
while (sz_read < rec_incl) {
sz = rec_incl - sz_read;
status = read_file(file, &tmp.eth, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading trailer: %d", status));
return status;
}
sz_read += sz;
}
// Some layers may have trailer, e.g: link eth2.
/* Check that we've read all the packets */
// PJ_ASSERT_RETURN(sz_read == rec_incl, PJ_EBUG);
return PJ_SUCCESS;
/* Skip trailer */
while (sz_read < rec_incl) {
sz = rec_incl - sz_read;
status = read_file(file, &tmp.eth, &sz);
if (status != PJ_SUCCESS) {
TRACE_((file->obj_name, "Error reading trailer: %d", status));
return status;
}
sz_read += sz;
}
return PJ_SUCCESS;
}
/* Does not reach here */
}

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
@ -14,7 +13,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/scanner.h>
#include <pj/ctype.h>
@ -26,67 +25,64 @@
#include <pj/errno.h>
#include <pj/assert.h>
#define THIS_FILE "scanner.c"
#define PJ_SCAN_IS_SPACE(c) ((c)==' ' || (c)=='\t')
#define PJ_SCAN_IS_NEWLINE(c) ((c)=='\r' || (c)=='\n')
#define PJ_SCAN_IS_PROBABLY_SPACE(c) ((c) <= 32)
#define PJ_SCAN_CHECK_EOF(s) (s != scanner->end)
#define THIS_FILE "scanner.c"
#define PJ_SCAN_IS_SPACE(c) ((c) == ' ' || (c) == '\t')
#define PJ_SCAN_IS_NEWLINE(c) ((c) == '\r' || (c) == '\n')
#define PJ_SCAN_IS_PROBABLY_SPACE(c) ((c) <= 32)
#define PJ_SCAN_CHECK_EOF(s) (s != scanner->end)
#if defined(PJ_SCANNER_USE_BITWISE) && PJ_SCANNER_USE_BITWISE != 0
# include "scanner_cis_bitwise.c"
# include "scanner_cis_bitwise.c"
#else
# include "scanner_cis_uint.c"
# include "scanner_cis_uint.c"
#endif
static void pj_scan_syntax_err(pj_scanner *scanner)
static void pj_scan_syntax_err(pj_scanner* scanner)
{
(*scanner->callback)(scanner);
}
PJ_DEF(void) pj_cis_add_range(pj_cis_t *cis, int cstart, int cend)
PJ_DEF(void) pj_cis_add_range(pj_cis_t* cis, int cstart, int cend)
{
/* Can not set zero. This is the requirement of the parser. */
pj_assert(cstart > 0);
while (cstart != cend) {
PJ_CIS_SET(cis, cstart);
++cstart;
++cstart;
}
}
PJ_DEF(void) pj_cis_add_alpha(pj_cis_t *cis)
PJ_DEF(void) pj_cis_add_alpha(pj_cis_t* cis)
{
pj_cis_add_range( cis, 'a', 'z'+1);
pj_cis_add_range( cis, 'A', 'Z'+1);
pj_cis_add_range(cis, 'a', 'z' + 1);
pj_cis_add_range(cis, 'A', 'Z' + 1);
}
PJ_DEF(void) pj_cis_add_num(pj_cis_t *cis)
PJ_DEF(void) pj_cis_add_num(pj_cis_t* cis)
{
pj_cis_add_range( cis, '0', '9'+1);
pj_cis_add_range(cis, '0', '9' + 1);
}
PJ_DEF(void) pj_cis_add_str( pj_cis_t *cis, const char *str)
PJ_DEF(void) pj_cis_add_str(pj_cis_t* cis, const char* str)
{
while (*str) {
PJ_CIS_SET(cis, *str);
++str;
++str;
}
}
PJ_DEF(void) pj_cis_add_cis( pj_cis_t *cis, const pj_cis_t *rhs)
PJ_DEF(void) pj_cis_add_cis(pj_cis_t* cis, const pj_cis_t* rhs)
{
int i;
for (i=0; i<256; ++i) {
if (PJ_CIS_ISSET(rhs, i))
PJ_CIS_SET(cis, i);
for (i = 0; i < 256; ++i) {
if (PJ_CIS_ISSET(rhs, i))
PJ_CIS_SET(cis, i);
}
}
PJ_DEF(void) pj_cis_del_range( pj_cis_t *cis, int cstart, int cend)
PJ_DEF(void) pj_cis_del_range(pj_cis_t* cis, int cstart, int cend)
{
while (cstart != cend) {
PJ_CIS_CLR(cis, cstart);
@ -94,29 +90,29 @@ PJ_DEF(void) pj_cis_del_range( pj_cis_t *cis, int cstart, int cend)
}
}
PJ_DEF(void) pj_cis_del_str( pj_cis_t *cis, const char *str)
PJ_DEF(void) pj_cis_del_str(pj_cis_t* cis, const char* str)
{
while (*str) {
PJ_CIS_CLR(cis, *str);
++str;
++str;
}
}
PJ_DEF(void) pj_cis_invert( pj_cis_t *cis )
PJ_DEF(void) pj_cis_invert(pj_cis_t* cis)
{
unsigned i;
/* Can not set zero. This is the requirement of the parser. */
for (i=1; i<256; ++i) {
if (PJ_CIS_ISSET(cis,i))
PJ_CIS_CLR(cis,i);
for (i = 1; i < 256; ++i) {
if (PJ_CIS_ISSET(cis, i))
PJ_CIS_CLR(cis, i);
else
PJ_CIS_SET(cis,i);
PJ_CIS_SET(cis, i);
}
}
PJ_DEF(void) pj_scan_init( pj_scanner *scanner, char *bufstart,
pj_size_t buflen, unsigned options,
pj_syn_err_func_ptr callback )
PJ_DEF(void)
pj_scan_init(pj_scanner* scanner, char* bufstart, pj_size_t buflen,
unsigned options, pj_syn_err_func_ptr callback)
{
PJ_CHECK_STACK();
@ -127,151 +123,150 @@ PJ_DEF(void) pj_scan_init( pj_scanner *scanner, char *bufstart,
scanner->callback = callback;
scanner->skip_ws = options;
if (scanner->skip_ws)
pj_scan_skip_whitespace(scanner);
if (scanner->skip_ws)
pj_scan_skip_whitespace(scanner);
}
PJ_DEF(void) pj_scan_fini( pj_scanner *scanner )
PJ_DEF(void) pj_scan_fini(pj_scanner* scanner)
{
PJ_CHECK_STACK();
PJ_UNUSED_ARG(scanner);
}
PJ_DEF(void) pj_scan_skip_whitespace( pj_scanner *scanner )
PJ_DEF(void) pj_scan_skip_whitespace(pj_scanner* scanner)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
while (PJ_SCAN_IS_SPACE(*s)) {
++s;
++s;
}
if (PJ_SCAN_IS_NEWLINE(*s) && (scanner->skip_ws & PJ_SCAN_AUTOSKIP_NEWLINE)) {
for (;;) {
if (*s == '\r') {
++s;
if (*s == '\n') ++s;
++scanner->line;
scanner->curptr = scanner->start_line = s;
} else if (*s == '\n') {
++s;
++scanner->line;
scanner->curptr = scanner->start_line = s;
} else if (PJ_SCAN_IS_SPACE(*s)) {
do {
++s;
} while (PJ_SCAN_IS_SPACE(*s));
} else {
break;
}
}
if (PJ_SCAN_IS_NEWLINE(*s) && (scanner->skip_ws & PJ_SCAN_AUTOSKIP_NEWLINE))
{
for (;;) {
if (*s == '\r') {
++s;
if (*s == '\n')
++s;
++scanner->line;
scanner->curptr = scanner->start_line = s;
} else if (*s == '\n') {
++s;
++scanner->line;
scanner->curptr = scanner->start_line = s;
} else if (PJ_SCAN_IS_SPACE(*s)) {
do {
++s;
} while (PJ_SCAN_IS_SPACE(*s));
} else {
break;
}
}
}
if (PJ_SCAN_IS_NEWLINE(*s) && (scanner->skip_ws & PJ_SCAN_AUTOSKIP_WS_HEADER)==PJ_SCAN_AUTOSKIP_WS_HEADER) {
/* Check for header continuation. */
scanner->curptr = s;
if (PJ_SCAN_IS_NEWLINE(*s) &&
(scanner->skip_ws & PJ_SCAN_AUTOSKIP_WS_HEADER) ==
PJ_SCAN_AUTOSKIP_WS_HEADER)
{
/* Check for header continuation. */
scanner->curptr = s;
if (*s == '\r') {
++s;
}
if (*s == '\n') {
++s;
}
scanner->start_line = s;
if (*s == '\r') {
++s;
}
if (*s == '\n') {
++s;
}
scanner->start_line = s;
if (PJ_SCAN_IS_SPACE(*s)) {
register char *t = s;
do {
++t;
} while (PJ_SCAN_IS_SPACE(*t));
if (PJ_SCAN_IS_SPACE(*s)) {
register char* t = s;
do {
++t;
} while (PJ_SCAN_IS_SPACE(*t));
++scanner->line;
scanner->curptr = t;
}
++scanner->line;
scanner->curptr = t;
}
} else {
scanner->curptr = s;
scanner->curptr = s;
}
}
PJ_DEF(void) pj_scan_skip_line( pj_scanner *scanner )
PJ_DEF(void) pj_scan_skip_line(pj_scanner* scanner)
{
char *s = pj_memchr(scanner->curptr, '\n', scanner->end - scanner->curptr);
char* s = pj_memchr(scanner->curptr, '\n', scanner->end - scanner->curptr);
if (!s) {
scanner->curptr = scanner->end;
scanner->curptr = scanner->end;
} else {
scanner->curptr = scanner->start_line = s+1;
scanner->line++;
}
scanner->curptr = scanner->start_line = s + 1;
scanner->line++;
}
}
PJ_DEF(int) pj_scan_peek( pj_scanner *scanner,
const pj_cis_t *spec, pj_str_t *out)
PJ_DEF(int)
pj_scan_peek(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
if (s >= scanner->end) {
pj_scan_syntax_err(scanner);
return -1;
pj_scan_syntax_err(scanner);
return -1;
}
/* Don't need to check EOF with PJ_SCAN_CHECK_EOF(s) */
while (pj_cis_match(spec, *s))
++s;
++s;
pj_strset3(out, scanner->curptr, s);
return *s;
}
PJ_DEF(int) pj_scan_peek_n( pj_scanner *scanner,
pj_size_t len, pj_str_t *out)
PJ_DEF(int) pj_scan_peek_n(pj_scanner* scanner, pj_size_t len, pj_str_t* out)
{
char *endpos = scanner->curptr + len;
char* endpos = scanner->curptr + len;
if (endpos > scanner->end) {
pj_scan_syntax_err(scanner);
return -1;
pj_scan_syntax_err(scanner);
return -1;
}
pj_strset(out, scanner->curptr, len);
return *endpos;
}
PJ_DEF(int) pj_scan_peek_until( pj_scanner *scanner,
const pj_cis_t *spec,
pj_str_t *out)
PJ_DEF(int)
pj_scan_peek_until(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
if (s >= scanner->end) {
pj_scan_syntax_err(scanner);
return -1;
pj_scan_syntax_err(scanner);
return -1;
}
while (PJ_SCAN_CHECK_EOF(s) && !pj_cis_match( spec, *s))
++s;
while (PJ_SCAN_CHECK_EOF(s) && !pj_cis_match(spec, *s))
++s;
pj_strset3(out, scanner->curptr, s);
return *s;
}
PJ_DEF(void) pj_scan_get( pj_scanner *scanner,
const pj_cis_t *spec, pj_str_t *out)
PJ_DEF(void)
pj_scan_get(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
pj_assert(pj_cis_match(spec,0)==0);
pj_assert(pj_cis_match(spec, 0) == 0);
/* EOF is detected implicitly */
if (!pj_cis_match(spec, *s)) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
do {
++s;
++s;
} while (pj_cis_match(spec, *s));
/* No need to check EOF here (PJ_SCAN_CHECK_EOF(s)) because
* buffer is NULL terminated and pj_cis_match(spec,0) should be
@ -283,80 +278,78 @@ PJ_DEF(void) pj_scan_get( pj_scanner *scanner,
scanner->curptr = s;
if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
pj_scan_skip_whitespace(scanner);
}
}
PJ_DEF(void) pj_scan_get_unescape( pj_scanner *scanner,
const pj_cis_t *spec, pj_str_t *out)
PJ_DEF(void)
pj_scan_get_unescape(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out)
{
register char *s = scanner->curptr;
char *dst = s;
register char* s = scanner->curptr;
char* dst = s;
pj_assert(pj_cis_match(spec,0)==0);
pj_assert(pj_cis_match(spec, 0) == 0);
/* Must not match character '%' */
pj_assert(pj_cis_match(spec,'%')==0);
pj_assert(pj_cis_match(spec, '%') == 0);
/* EOF is detected implicitly */
if (!pj_cis_match(spec, *s) && *s != '%') {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
out->ptr = s;
do {
if (*s == '%') {
if (s+3 <= scanner->end && pj_isxdigit(*(s+1)) &&
pj_isxdigit(*(s+2)))
{
*dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(s+1)) << 4) +
pj_hex_digit_to_val(*(s+2)));
++dst;
s += 3;
} else {
*dst++ = *s++;
*dst++ = *s++;
break;
}
}
if (pj_cis_match(spec, *s)) {
char *start = s;
do {
++s;
} while (pj_cis_match(spec, *s));
if (*s == '%') {
if (s + 3 <= scanner->end && pj_isxdigit(*(s + 1)) &&
pj_isxdigit(*(s + 2))) {
*dst = (pj_uint8_t)((pj_hex_digit_to_val(*(s + 1)) << 4) +
pj_hex_digit_to_val(*(s + 2)));
++dst;
s += 3;
} else {
*dst++ = *s++;
*dst++ = *s++;
break;
}
}
if (pj_cis_match(spec, *s)) {
char* start = s;
do {
++s;
} while (pj_cis_match(spec, *s));
if (dst != start)
pj_memmove(dst, start, s - start);
dst += (s - start);
}
if (dst != start) pj_memmove(dst, start, s-start);
dst += (s-start);
}
} while (*s == '%');
scanner->curptr = s;
out->slen = (dst - out->ptr);
if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
pj_scan_skip_whitespace(scanner);
}
}
PJ_DEF(void) pj_scan_get_quote( pj_scanner *scanner,
int begin_quote, int end_quote,
pj_str_t *out)
PJ_DEF(void)
pj_scan_get_quote(pj_scanner* scanner, int begin_quote, int end_quote,
pj_str_t* out)
{
char beg = (char)begin_quote;
char end = (char)end_quote;
pj_scan_get_quotes(scanner, &beg, &end, 1, out);
}
PJ_DEF(void) pj_scan_get_quotes(pj_scanner *scanner,
const char *begin_quote, const char *end_quote,
int qsize, pj_str_t *out)
PJ_DEF(void)
pj_scan_get_quotes(pj_scanner* scanner, const char* begin_quote,
const char* end_quote, int qsize, pj_str_t* out)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
int qpair = -1;
int i;
@ -364,53 +357,53 @@ PJ_DEF(void) pj_scan_get_quotes(pj_scanner *scanner,
/* Check and eat the begin_quote. */
for (i = 0; i < qsize; ++i) {
if (*s == begin_quote[i]) {
qpair = i;
break;
}
if (*s == begin_quote[i]) {
qpair = i;
break;
}
}
if (qpair == -1) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
++s;
/* Loop until end_quote is found.
/* Loop until end_quote is found.
*/
do {
/* loop until end_quote is found. */
while (PJ_SCAN_CHECK_EOF(s) && *s != '\n' && *s != end_quote[qpair]) {
++s;
}
/* loop until end_quote is found. */
while (PJ_SCAN_CHECK_EOF(s) && *s != '\n' && *s != end_quote[qpair]) {
++s;
}
/* check that no backslash character precedes the end_quote. */
if (*s == end_quote[qpair]) {
if (*(s-1) == '\\') {
char *q = s-2;
char *r = s-2;
/* check that no backslash character precedes the end_quote. */
if (*s == end_quote[qpair]) {
if (*(s - 1) == '\\') {
char* q = s - 2;
char* r = s - 2;
while (r != scanner->begin && *r == '\\') {
--r;
}
/* break from main loop if we have odd number of backslashes */
if (((unsigned)(q-r) & 0x01) == 1) {
break;
}
++s;
} else {
/* end_quote is not preceeded by backslash. break now. */
break;
}
} else {
/* loop ended by non-end_quote character. break now. */
break;
}
while (r != scanner->begin && *r == '\\') {
--r;
}
/* break from main loop if we have odd number of backslashes */
if (((unsigned)(q - r) & 0x01) == 1) {
break;
}
++s;
} else {
/* end_quote is not preceeded by backslash. break now. */
break;
}
} else {
/* loop ended by non-end_quote character. break now. */
break;
}
} while (1);
/* Check and eat the end quote. */
if (*s != end_quote[qpair]) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
++s;
@ -419,37 +412,34 @@ PJ_DEF(void) pj_scan_get_quotes(pj_scanner *scanner,
scanner->curptr = s;
if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
pj_scan_skip_whitespace(scanner);
}
}
PJ_DEF(void) pj_scan_get_n( pj_scanner *scanner,
unsigned N, pj_str_t *out)
PJ_DEF(void) pj_scan_get_n(pj_scanner* scanner, unsigned N, pj_str_t* out)
{
if (scanner->curptr + N > scanner->end) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
pj_strset(out, scanner->curptr, N);
scanner->curptr += N;
if (PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
pj_scan_skip_whitespace(scanner);
}
}
PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner )
PJ_DEF(int) pj_scan_get_char(pj_scanner* scanner)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
int chr;
if (s >= scanner->end || !*s) {
pj_scan_syntax_err(scanner);
return 0;
pj_scan_syntax_err(scanner);
return 0;
}
chr = *s;
@ -457,26 +447,24 @@ PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner )
++s;
scanner->curptr = s;
if (PJ_SCAN_CHECK_EOF(s) && PJ_SCAN_IS_PROBABLY_SPACE(*s) &&
scanner->skip_ws)
{
pj_scan_skip_whitespace(scanner);
scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
}
return chr;
}
PJ_DEF(void) pj_scan_get_newline( pj_scanner *scanner )
PJ_DEF(void) pj_scan_get_newline(pj_scanner* scanner)
{
if (!PJ_SCAN_IS_NEWLINE(*scanner->curptr)) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
if (*scanner->curptr == '\r') {
++scanner->curptr;
++scanner->curptr;
}
if (*scanner->curptr == '\n') {
++scanner->curptr;
++scanner->curptr;
}
++scanner->line;
@ -486,7 +474,7 @@ PJ_DEF(void) pj_scan_get_newline( pj_scanner *scanner )
* This probably is a bug, see PROTOS test #2480.
* This would cause scanner to incorrectly eat two new lines, e.g.
* when parsing:
*
*
* Content-Length: 120\r\n
* \r\n
* <space><space><space>...
@ -501,19 +489,18 @@ PJ_DEF(void) pj_scan_get_newline( pj_scanner *scanner )
*/
}
PJ_DEF(void) pj_scan_get_until( pj_scanner *scanner,
const pj_cis_t *spec, pj_str_t *out)
PJ_DEF(void)
pj_scan_get_until(pj_scanner* scanner, const pj_cis_t* spec, pj_str_t* out)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
if (s >= scanner->end) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
while (PJ_SCAN_CHECK_EOF(s) && !pj_cis_match(spec, *s)) {
++s;
++s;
}
pj_strset3(out, scanner->curptr, s);
@ -521,23 +508,22 @@ PJ_DEF(void) pj_scan_get_until( pj_scanner *scanner,
scanner->curptr = s;
if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
pj_scan_skip_whitespace(scanner);
}
}
PJ_DEF(void) pj_scan_get_until_ch( pj_scanner *scanner,
int until_char, pj_str_t *out)
PJ_DEF(void)
pj_scan_get_until_ch(pj_scanner* scanner, int until_char, pj_str_t* out)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
if (s >= scanner->end) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
while (PJ_SCAN_CHECK_EOF(s) && *s != until_char) {
++s;
++s;
}
pj_strset3(out, scanner->curptr, s);
@ -545,25 +531,25 @@ PJ_DEF(void) pj_scan_get_until_ch( pj_scanner *scanner,
scanner->curptr = s;
if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
pj_scan_skip_whitespace(scanner);
}
}
PJ_DEF(void) pj_scan_get_until_chr( pj_scanner *scanner,
const char *until_spec, pj_str_t *out)
PJ_DEF(void)
pj_scan_get_until_chr(pj_scanner* scanner, const char* until_spec,
pj_str_t* out)
{
register char *s = scanner->curptr;
register char* s = scanner->curptr;
pj_size_t speclen;
if (s >= scanner->end) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
speclen = strlen(until_spec);
while (PJ_SCAN_CHECK_EOF(s) && !memchr(until_spec, *s, speclen)) {
++s;
++s;
}
pj_strset3(out, scanner->curptr, s);
@ -571,70 +557,62 @@ PJ_DEF(void) pj_scan_get_until_chr( pj_scanner *scanner,
scanner->curptr = s;
if (PJ_SCAN_IS_PROBABLY_SPACE(*s) && scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
pj_scan_skip_whitespace(scanner);
}
}
PJ_DEF(void) pj_scan_advance_n( pj_scanner *scanner,
unsigned N, pj_bool_t skip_ws)
PJ_DEF(void)
pj_scan_advance_n(pj_scanner* scanner, unsigned N, pj_bool_t skip_ws)
{
if (scanner->curptr + N > scanner->end) {
pj_scan_syntax_err(scanner);
return;
pj_scan_syntax_err(scanner);
return;
}
scanner->curptr += N;
if (PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && skip_ws) {
pj_scan_skip_whitespace(scanner);
pj_scan_skip_whitespace(scanner);
}
}
PJ_DEF(int) pj_scan_strcmp( pj_scanner *scanner, const char *s, int len)
PJ_DEF(int) pj_scan_strcmp(pj_scanner* scanner, const char* s, int len)
{
if (scanner->curptr + len > scanner->end) {
pj_scan_syntax_err(scanner);
return -1;
pj_scan_syntax_err(scanner);
return -1;
}
return strncmp(scanner->curptr, s, len);
}
PJ_DEF(int) pj_scan_stricmp( pj_scanner *scanner, const char *s, int len)
PJ_DEF(int) pj_scan_stricmp(pj_scanner* scanner, const char* s, int len)
{
if (scanner->curptr + len > scanner->end) {
pj_scan_syntax_err(scanner);
return -1;
pj_scan_syntax_err(scanner);
return -1;
}
return pj_ansi_strnicmp(scanner->curptr, s, len);
}
PJ_DEF(int) pj_scan_stricmp_alnum( pj_scanner *scanner, const char *s,
int len)
PJ_DEF(int) pj_scan_stricmp_alnum(pj_scanner* scanner, const char* s, int len)
{
if (scanner->curptr + len > scanner->end) {
pj_scan_syntax_err(scanner);
return -1;
pj_scan_syntax_err(scanner);
return -1;
}
return strnicmp_alnum(scanner->curptr, s, len);
}
PJ_DEF(void) pj_scan_save_state( const pj_scanner *scanner,
pj_scan_state *state)
PJ_DEF(void) pj_scan_save_state(const pj_scanner* scanner, pj_scan_state* state)
{
state->curptr = scanner->curptr;
state->line = scanner->line;
state->start_line = scanner->start_line;
}
PJ_DEF(void) pj_scan_restore_state( pj_scanner *scanner,
pj_scan_state *state)
PJ_DEF(void) pj_scan_restore_state(pj_scanner* scanner, pj_scan_state* state)
{
scanner->curptr = state->curptr;
scanner->line = state->line;
scanner->start_line = state->start_line;
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
@ -23,22 +22,22 @@
* DO NOT COMPILE THIS FILE ALONE!
*/
PJ_DEF(void) pj_cis_buf_init( pj_cis_buf_t *cis_buf)
PJ_DEF(void) pj_cis_buf_init(pj_cis_buf_t* cis_buf)
{
pj_bzero(cis_buf->cis_buf, sizeof(cis_buf->cis_buf));
cis_buf->use_mask = 0;
}
PJ_DEF(pj_status_t) pj_cis_init(pj_cis_buf_t *cis_buf, pj_cis_t *cis)
PJ_DEF(pj_status_t) pj_cis_init(pj_cis_buf_t* cis_buf, pj_cis_t* cis)
{
unsigned i;
cis->cis_buf = cis_buf->cis_buf;
for (i=0; i<PJ_CIS_MAX_INDEX; ++i) {
for (i = 0; i < PJ_CIS_MAX_INDEX; ++i) {
if ((cis_buf->use_mask & (1 << i)) == 0) {
cis->cis_id = i;
cis_buf->use_mask |= (1 << i);
cis_buf->use_mask |= (1 << i);
return PJ_SUCCESS;
}
}
@ -47,7 +46,7 @@ PJ_DEF(pj_status_t) pj_cis_init(pj_cis_buf_t *cis_buf, pj_cis_t *cis)
return PJ_ETOOMANY;
}
PJ_DEF(pj_status_t) pj_cis_dup( pj_cis_t *new_cis, pj_cis_t *existing)
PJ_DEF(pj_status_t) pj_cis_dup(pj_cis_t* new_cis, pj_cis_t* existing)
{
pj_status_t status;
unsigned i;
@ -57,7 +56,7 @@ PJ_DEF(pj_status_t) pj_cis_dup( pj_cis_t *new_cis, pj_cis_t *existing)
if (status != PJ_SUCCESS)
return status;
for (i=0; i<256; ++i) {
for (i = 0; i < 256; ++i) {
if (PJ_CIS_ISSET(existing, i))
PJ_CIS_SET(new_cis, i);
else
@ -66,4 +65,3 @@ PJ_DEF(pj_status_t) pj_cis_dup( pj_cis_t *new_cis, pj_cis_t *existing)
return PJ_SUCCESS;
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
@ -23,24 +22,21 @@
* DO NOT COMPILE THIS FILE ALONE!
*/
PJ_DEF(void) pj_cis_buf_init( pj_cis_buf_t *cis_buf)
PJ_DEF(void) pj_cis_buf_init(pj_cis_buf_t* cis_buf)
{
/* Do nothing. */
PJ_UNUSED_ARG(cis_buf);
}
PJ_DEF(pj_status_t) pj_cis_init(pj_cis_buf_t *cis_buf, pj_cis_t *cis)
PJ_DEF(pj_status_t) pj_cis_init(pj_cis_buf_t* cis_buf, pj_cis_t* cis)
{
PJ_UNUSED_ARG(cis_buf);
pj_bzero(cis->cis_buf, sizeof(cis->cis_buf));
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pj_cis_dup( pj_cis_t *new_cis, pj_cis_t *existing)
PJ_DEF(pj_status_t) pj_cis_dup(pj_cis_t* new_cis, pj_cis_t* existing)
{
pj_memcpy(new_cis, existing, sizeof(pj_cis_t));
return PJ_SUCCESS;
}

View File

@ -1,4 +1,3 @@
/* $Id$ */
/*
* Modified 2/07
* By Benny Prijono <benny@prijono.org>
@ -14,16 +13,16 @@ By Steve Reid <sreid@sea-to-sky.net>
100% Public Domain
-----------------
Modified 7/98
Modified 7/98
By James H. Brown <jbrown@burgoyne.com>
Still 100% Public Domain
Corrected a problem which generated improper hash values on 16 bit machines
Routine SHA1Update changed from
void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int
void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int
len)
to
void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned
void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned
long len)
The 'len' parameter was declared an int which works fine on 32 bit machines.
@ -36,7 +35,7 @@ Since the file IO in main() reads 16K at a time, any file 8K or larger would
be guaranteed to generate the wrong hash (e.g. Test Vector #3, a million
"a"s).
I also changed the declaration of variables i & j in SHA1Update to
I also changed the declaration of variables i & j in SHA1Update to
unsigned long from unsigned int for the same reason.
These changes should make no difference to any 32 bit implementations since
@ -63,7 +62,7 @@ Still 100% public domain
Modified 4/01
By Saul Kravitz <Saul.Kravitz@celera.com>
Still 100% PD
Modified to run on Compaq Alpha hardware.
Modified to run on Compaq Alpha hardware.
-----------------
Modified 07/2002
@ -104,7 +103,6 @@ A million repetitions of "a"
#undef SHA1HANDSOFF
static void SHA1_Transform(pj_uint32_t state[5], pj_uint8_t buffer[64]);
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
@ -114,27 +112,40 @@ static void SHA1_Transform(pj_uint32_t state[5], pj_uint8_t buffer[64]);
/* FIXME: can we do this in an endian-proof way? */
/* #ifdef WORDS_BIGENDIAN */
#if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN != 0
#define blk0(i) block->l[i]
# define blk0(i) block->l[i]
#else
#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
|(rol(block->l[i],8)&0x00FF00FF))
# define blk0(i) \
(block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | \
(rol(block->l[i], 8) & 0x00FF00FF))
#endif
#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
^block->l[(i+2)&15]^block->l[i&15],1))
#define blk(i) \
(block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
block->l[(i + 2) & 15] ^ block->l[i & 15], \
1))
/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
#define R0(v, w, x, y, z, i) \
z += ((w & (x ^ y)) ^ y) + blk0(i) + 0x5A827999 + rol(v, 5); \
w = rol(w, 30);
#define R1(v, w, x, y, z, i) \
z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
w = rol(w, 30);
#define R2(v, w, x, y, z, i) \
z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
w = rol(w, 30);
#define R3(v, w, x, y, z, i) \
z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
w = rol(w, 30);
#define R4(v, w, x, y, z, i) \
z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
w = rol(w, 30);
/* Hash a single 512-bit block. This is the core of the algorithm. */
static void SHA1_Transform(pj_uint32_t state[5], pj_uint8_t buffer[64])
{
pj_uint32_t a, b, c, d, e;
typedef union {
typedef union
{
pj_uint8_t c[64];
pj_uint32_t l[16];
} CHAR64LONG16;
@ -156,26 +167,86 @@ static void SHA1_Transform(pj_uint32_t state[5], pj_uint8_t buffer[64])
e = state[4];
/* 4 rounds of 20 operations each. Loop unrolled. */
R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
R0(a, b, c, d, e, 0);
R0(e, a, b, c, d, 1);
R0(d, e, a, b, c, 2);
R0(c, d, e, a, b, 3);
R0(b, c, d, e, a, 4);
R0(a, b, c, d, e, 5);
R0(e, a, b, c, d, 6);
R0(d, e, a, b, c, 7);
R0(c, d, e, a, b, 8);
R0(b, c, d, e, a, 9);
R0(a, b, c, d, e, 10);
R0(e, a, b, c, d, 11);
R0(d, e, a, b, c, 12);
R0(c, d, e, a, b, 13);
R0(b, c, d, e, a, 14);
R0(a, b, c, d, e, 15);
R1(e, a, b, c, d, 16);
R1(d, e, a, b, c, 17);
R1(c, d, e, a, b, 18);
R1(b, c, d, e, a, 19);
R2(a, b, c, d, e, 20);
R2(e, a, b, c, d, 21);
R2(d, e, a, b, c, 22);
R2(c, d, e, a, b, 23);
R2(b, c, d, e, a, 24);
R2(a, b, c, d, e, 25);
R2(e, a, b, c, d, 26);
R2(d, e, a, b, c, 27);
R2(c, d, e, a, b, 28);
R2(b, c, d, e, a, 29);
R2(a, b, c, d, e, 30);
R2(e, a, b, c, d, 31);
R2(d, e, a, b, c, 32);
R2(c, d, e, a, b, 33);
R2(b, c, d, e, a, 34);
R2(a, b, c, d, e, 35);
R2(e, a, b, c, d, 36);
R2(d, e, a, b, c, 37);
R2(c, d, e, a, b, 38);
R2(b, c, d, e, a, 39);
R3(a, b, c, d, e, 40);
R3(e, a, b, c, d, 41);
R3(d, e, a, b, c, 42);
R3(c, d, e, a, b, 43);
R3(b, c, d, e, a, 44);
R3(a, b, c, d, e, 45);
R3(e, a, b, c, d, 46);
R3(d, e, a, b, c, 47);
R3(c, d, e, a, b, 48);
R3(b, c, d, e, a, 49);
R3(a, b, c, d, e, 50);
R3(e, a, b, c, d, 51);
R3(d, e, a, b, c, 52);
R3(c, d, e, a, b, 53);
R3(b, c, d, e, a, 54);
R3(a, b, c, d, e, 55);
R3(e, a, b, c, d, 56);
R3(d, e, a, b, c, 57);
R3(c, d, e, a, b, 58);
R3(b, c, d, e, a, 59);
R4(a, b, c, d, e, 60);
R4(e, a, b, c, d, 61);
R4(d, e, a, b, c, 62);
R4(c, d, e, a, b, 63);
R4(b, c, d, e, a, 64);
R4(a, b, c, d, e, 65);
R4(e, a, b, c, d, 66);
R4(d, e, a, b, c, 67);
R4(c, d, e, a, b, 68);
R4(b, c, d, e, a, 69);
R4(a, b, c, d, e, 70);
R4(e, a, b, c, d, 71);
R4(d, e, a, b, c, 72);
R4(c, d, e, a, b, 73);
R4(b, c, d, e, a, 74);
R4(a, b, c, d, e, 75);
R4(e, a, b, c, d, 76);
R4(d, e, a, b, c, 77);
R4(c, d, e, a, b, 78);
R4(b, c, d, e, a, 79);
/* Add the working vars back into context.state[] */
state[0] += a;
@ -188,7 +259,6 @@ static void SHA1_Transform(pj_uint32_t state[5], pj_uint8_t buffer[64])
a = b = c = d = e = 0;
}
/* SHA1Init - Initialize new context */
PJ_DEF(void) pj_sha1_init(pj_sha1_context* context)
{
@ -201,63 +271,62 @@ PJ_DEF(void) pj_sha1_init(pj_sha1_context* context)
context->count[0] = context->count[1] = 0;
}
/* Run your data through this. */
PJ_DEF(void) pj_sha1_update(pj_sha1_context* context,
const pj_uint8_t* data, const pj_size_t len)
PJ_DEF(void)
pj_sha1_update(pj_sha1_context* context, const pj_uint8_t* data,
const pj_size_t len)
{
pj_size_t i, j;
j = (context->count[0] >> 3) & 63;
if ((context->count[0] += (pj_uint32_t)len << 3) < (len << 3))
context->count[1]++;
if ((context->count[0] += (pj_uint32_t)len << 3) < (len << 3))
context->count[1]++;
context->count[1] += ((pj_uint32_t)len >> 29);
if ((j + len) > 63) {
pj_memcpy(&context->buffer[j], data, (i = 64-j));
pj_memcpy(&context->buffer[j], data, (i = 64 - j));
SHA1_Transform(context->state, context->buffer);
for ( ; i + 63 < len; i += 64) {
pj_uint8_t tmp[64];
pj_memcpy(tmp, data + i, 64);
for (; i + 63 < len; i += 64) {
pj_uint8_t tmp[64];
pj_memcpy(tmp, data + i, 64);
SHA1_Transform(context->state, tmp);
}
j = 0;
}
else i = 0;
} else
i = 0;
pj_memcpy(&context->buffer[j], &data[i], len - i);
}
/* Add padding and return the message digest. */
PJ_DEF(void) pj_sha1_final(pj_sha1_context* context,
pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE])
PJ_DEF(void)
pj_sha1_final(pj_sha1_context* context, pj_uint8_t digest[PJ_SHA1_DIGEST_SIZE])
{
pj_uint32_t i;
pj_uint8_t finalcount[8];
pj_uint8_t finalcount[8];
for (i = 0; i < 8; i++) {
finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
>> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >>
((3 - (i & 3)) * 8)) &
255); /* Endian independent */
}
pj_sha1_update(context, (pj_uint8_t *)"\200", 1);
pj_sha1_update(context, (pj_uint8_t*)"\200", 1);
while ((context->count[0] & 504) != 448) {
pj_sha1_update(context, (pj_uint8_t *)"\0", 1);
pj_sha1_update(context, (pj_uint8_t*)"\0", 1);
}
pj_sha1_update(context, finalcount, 8); /* Should cause a SHA1_Transform() */
pj_sha1_update(context, finalcount,
8); /* Should cause a SHA1_Transform() */
for (i = 0; i < PJ_SHA1_DIGEST_SIZE; i++) {
digest[i] = (pj_uint8_t)
((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
digest[i] =
(pj_uint8_t)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
/* Wipe variables */
i = 0;
pj_memset(context->buffer, 0, 64);
pj_memset(context->state, 0, 20);
pj_memset(context->count, 0, 8);
pj_memset(finalcount, 0, 8); /* SWR */
pj_memset(finalcount, 0, 8); /* SWR */
#ifdef SHA1HANDSOFF /* make SHA1Transform overwrite its own static vars */
#ifdef SHA1HANDSOFF /* make SHA1Transform overwrite its own static vars */
SHA1_Transform(context->state, context->buffer);
#endif
}

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,96 +14,95 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/string.h>
#include <pj/ctype.h>
#include <pj/string.h>
#include <pj/pool.h>
PJ_DEF(pj_str_t) pj_str_unescape( pj_pool_t *pool, const pj_str_t *src_str)
PJ_DEF(pj_str_t) pj_str_unescape(pj_pool_t* pool, const pj_str_t* src_str)
{
char *src = src_str->ptr;
char *end = src + src_str->slen;
char* src = src_str->ptr;
char* end = src + src_str->slen;
pj_str_t dst_str;
char *dst;
if (pj_strchr(src_str, '%')==NULL)
return *src_str;
char* dst;
dst = dst_str.ptr = (char*) pj_pool_alloc(pool, src_str->slen);
if (pj_strchr(src_str, '%') == NULL)
return *src_str;
dst = dst_str.ptr = (char*)pj_pool_alloc(pool, src_str->slen);
while (src != end) {
if (*src == '%' && src < end-2 && pj_isxdigit(*(src+1)) &&
pj_isxdigit(*(src+2)))
{
*dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(src+1)) << 4) +
pj_hex_digit_to_val(*(src+2)));
++dst;
src += 3;
} else {
*dst++ = *src++;
}
if (*src == '%' && src < end - 2 && pj_isxdigit(*(src + 1)) &&
pj_isxdigit(*(src + 2)))
{
*dst = (pj_uint8_t)((pj_hex_digit_to_val(*(src + 1)) << 4) +
pj_hex_digit_to_val(*(src + 2)));
++dst;
src += 3;
} else {
*dst++ = *src++;
}
}
dst_str.slen = dst - dst_str.ptr;
return dst_str;
}
PJ_DEF(pj_str_t*) pj_strcpy_unescape(pj_str_t *dst_str,
const pj_str_t *src_str)
PJ_DEF(pj_str_t*) pj_strcpy_unescape(pj_str_t* dst_str, const pj_str_t* src_str)
{
const char *src = src_str->ptr;
const char *end = src + src_str->slen;
char *dst = dst_str->ptr;
const char* src = src_str->ptr;
const char* end = src + src_str->slen;
char* dst = dst_str->ptr;
while (src != end) {
if (*src == '%' && src < end-2) {
*dst = (pj_uint8_t) ((pj_hex_digit_to_val(*(src+1)) << 4) +
pj_hex_digit_to_val(*(src+2)));
++dst;
src += 3;
} else {
*dst++ = *src++;
}
if (*src == '%' && src < end - 2) {
*dst = (pj_uint8_t)((pj_hex_digit_to_val(*(src + 1)) << 4) +
pj_hex_digit_to_val(*(src + 2)));
++dst;
src += 3;
} else {
*dst++ = *src++;
}
}
dst_str->slen = dst - dst_str->ptr;
return dst_str;
}
PJ_DEF(pj_ssize_t) pj_strncpy2_escape( char *dst_str, const pj_str_t *src_str,
pj_ssize_t max, const pj_cis_t *unres)
PJ_DEF(pj_ssize_t)
pj_strncpy2_escape(char* dst_str, const pj_str_t* src_str, pj_ssize_t max,
const pj_cis_t* unres)
{
const char *src = src_str->ptr;
const char *src_end = src + src_str->slen;
char *dst = dst_str;
char *dst_end = dst + max;
const char* src = src_str->ptr;
const char* src_end = src + src_str->slen;
char* dst = dst_str;
char* dst_end = dst + max;
if (max < src_str->slen)
return -1;
return -1;
while (src != src_end && dst != dst_end) {
if (pj_cis_match(unres, *src)) {
*dst++ = *src++;
} else {
if (dst < dst_end-2) {
*dst++ = '%';
pj_val_to_hex_digit(*src, dst);
dst+=2;
++src;
} else {
break;
}
}
if (pj_cis_match(unres, *src)) {
*dst++ = *src++;
} else {
if (dst < dst_end - 2) {
*dst++ = '%';
pj_val_to_hex_digit(*src, dst);
dst += 2;
++src;
} else {
break;
}
}
}
return src==src_end ? dst-dst_str : -1;
return src == src_end ? dst - dst_str : -1;
}
PJ_DEF(pj_str_t*) pj_strncpy_escape(pj_str_t *dst_str,
const pj_str_t *src_str,
pj_ssize_t max, const pj_cis_t *unres)
PJ_DEF(pj_str_t*)
pj_strncpy_escape(pj_str_t* dst_str, const pj_str_t* src_str, pj_ssize_t max,
const pj_cis_t* unres)
{
dst_str->slen = pj_strncpy2_escape(dst_str->ptr, src_str, max, unres);
return dst_str->slen < 0 ? NULL : dst_str;
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/stun_simple.h>
#include <pjlib-util/errno.h>
@ -24,21 +23,19 @@
#include <pj/sock.h>
#include <pj/os.h>
#define THIS_FILE "stun_simple.c"
#define THIS_FILE "stun_simple.c"
PJ_DEF(pj_status_t) pjstun_create_bind_req( pj_pool_t *pool,
void **msg, pj_size_t *len,
pj_uint32_t id_hi,
pj_uint32_t id_lo)
PJ_DEF(pj_status_t)
pjstun_create_bind_req(pj_pool_t* pool, void** msg, pj_size_t* len,
pj_uint32_t id_hi, pj_uint32_t id_lo)
{
pjstun_msg_hdr *hdr;
PJ_CHECK_STACK();
pjstun_msg_hdr* hdr;
PJ_CHECK_STACK();
hdr = PJ_POOL_ZALLOC_T(pool, pjstun_msg_hdr);
if (!hdr)
return PJ_ENOMEM;
return PJ_ENOMEM;
hdr->type = pj_htons(PJSTUN_BINDING_REQUEST);
hdr->tsx[2] = pj_htonl(id_hi);
@ -49,11 +46,11 @@ PJ_DEF(pj_status_t) pjstun_create_bind_req( pj_pool_t *pool,
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len,
pjstun_msg *msg)
PJ_DEF(pj_status_t)
pjstun_parse_msg(void* buf, pj_size_t buf_len, pjstun_msg* msg)
{
pj_uint16_t msg_type, msg_len;
char *p_attr;
char* p_attr;
int attr_max_cnt = PJ_ARRAY_SIZE(msg->attr);
PJ_CHECK_STACK();
@ -68,68 +65,70 @@ PJ_DEF(pj_status_t) pjstun_parse_msg( void *buf, pj_size_t buf_len,
case PJSTUN_SHARED_SECRET_REQUEST:
case PJSTUN_SHARED_SECRET_RESPONSE:
case PJSTUN_SHARED_SECRET_ERROR_RESPONSE:
break;
break;
default:
PJ_LOG(4,(THIS_FILE, "Error: unknown msg type %d", msg_type));
return PJLIB_UTIL_ESTUNINMSGTYPE;
PJ_LOG(4, (THIS_FILE, "Error: unknown msg type %d", msg_type));
return PJLIB_UTIL_ESTUNINMSGTYPE;
}
msg_len = pj_ntohs(msg->hdr->length);
if (msg_len != buf_len - sizeof(pjstun_msg_hdr)) {
PJ_LOG(4,(THIS_FILE, "Error: invalid msg_len %d (expecting %d)",
msg_len, buf_len - sizeof(pjstun_msg_hdr)));
return PJLIB_UTIL_ESTUNINMSGLEN;
PJ_LOG(4, (THIS_FILE, "Error: invalid msg_len %d (expecting %d)",
msg_len, buf_len - sizeof(pjstun_msg_hdr)));
return PJLIB_UTIL_ESTUNINMSGLEN;
}
msg->attr_count = 0;
p_attr = (char*)buf + sizeof(pjstun_msg_hdr);
while (msg_len > 0 && msg->attr_count < attr_max_cnt) {
pjstun_attr_hdr **attr = &msg->attr[msg->attr_count];
pj_uint32_t len;
pj_uint16_t attr_type;
pjstun_attr_hdr** attr = &msg->attr[msg->attr_count];
pj_uint32_t len;
pj_uint16_t attr_type;
*attr = (pjstun_attr_hdr*)p_attr;
len = pj_ntohs((pj_uint16_t) ((*attr)->length)) + sizeof(pjstun_attr_hdr);
len = (len + 3) & ~3;
*attr = (pjstun_attr_hdr*)p_attr;
len =
pj_ntohs((pj_uint16_t)((*attr)->length)) + sizeof(pjstun_attr_hdr);
len = (len + 3) & ~3;
if (msg_len < len) {
PJ_LOG(4,(THIS_FILE, "Error: length mismatch in attr %d",
msg->attr_count));
return PJLIB_UTIL_ESTUNINATTRLEN;
}
if (msg_len < len) {
PJ_LOG(4, (THIS_FILE, "Error: length mismatch in attr %d",
msg->attr_count));
return PJLIB_UTIL_ESTUNINATTRLEN;
}
attr_type = pj_ntohs((*attr)->type);
if (attr_type > PJSTUN_ATTR_REFLECTED_FROM &&
attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR)
{
PJ_LOG(5,(THIS_FILE, "Warning: unknown attr type %x in attr %d. "
"Attribute was ignored.",
attr_type, msg->attr_count));
}
attr_type = pj_ntohs((*attr)->type);
if (attr_type > PJSTUN_ATTR_REFLECTED_FROM &&
attr_type != PJSTUN_ATTR_XOR_MAPPED_ADDR)
{
PJ_LOG(5, (THIS_FILE,
"Warning: unknown attr type %x in attr %d. "
"Attribute was ignored.",
attr_type, msg->attr_count));
}
msg_len = (pj_uint16_t)(msg_len - len);
p_attr += len;
++msg->attr_count;
msg_len = (pj_uint16_t)(msg_len - len);
p_attr += len;
++msg->attr_count;
}
if (msg->attr_count == attr_max_cnt) {
PJ_LOG(4, (THIS_FILE, "Warning: max number attribute %d reached.",
attr_max_cnt));
PJ_LOG(4, (THIS_FILE, "Warning: max number attribute %d reached.",
attr_max_cnt));
}
return PJ_SUCCESS;
}
PJ_DEF(void*) pjstun_msg_find_attr( pjstun_msg *msg, pjstun_attr_type t)
PJ_DEF(void*) pjstun_msg_find_attr(pjstun_msg* msg, pjstun_attr_type t)
{
int i;
PJ_CHECK_STACK();
for (i=0; i<msg->attr_count; ++i) {
pjstun_attr_hdr *attr = msg->attr[i];
if (pj_ntohs(attr->type) == t)
return attr;
for (i = 0; i < msg->attr_count; ++i) {
pjstun_attr_hdr* attr = msg->attr[i];
if (pj_ntohs(attr->type) == t)
return attr;
}
return 0;

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,11 +14,11 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/stun_simple.h>
#include <pjlib-util/errno.h>
#include <pj/compat/socket.h>
#include <pj/compat/socket.h>
#include <pj/log.h>
#include <pj/os.h>
#include <pj/pool.h>
@ -27,20 +26,21 @@
#include <pj/sock_select.h>
#include <pj/string.h>
enum { MAX_REQUEST = 4 };
static int stun_timer[] = {500, 500, 500, 500 };
enum
{
MAX_REQUEST = 4
};
static int stun_timer[] = { 500, 500, 500, 500 };
#define STUN_MAGIC 0x2112A442
#define THIS_FILE "stun_client.c"
#define THIS_FILE "stun_client.c"
#define TRACE_(x) PJ_LOG(6,x)
#define TRACE_(x) PJ_LOG(6, x)
PJ_DEF(pj_status_t) pjstun_get_mapped_addr( pj_pool_factory *pf,
int sock_cnt, pj_sock_t sock[],
const pj_str_t *srv1, int port1,
const pj_str_t *srv2, int port2,
pj_sockaddr_in mapped_addr[])
PJ_DEF(pj_status_t)
pjstun_get_mapped_addr(pj_pool_factory* pf, int sock_cnt, pj_sock_t sock[],
const pj_str_t* srv1, int port1, const pj_str_t* srv2,
int port2, pj_sockaddr_in mapped_addr[])
{
pjstun_setting opt;
@ -54,26 +54,27 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr( pj_pool_factory *pf,
return pjstun_get_mapped_addr2(pf, &opt, sock_cnt, sock, mapped_addr);
}
PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf,
const pjstun_setting *opt,
int sock_cnt,
pj_sock_t sock[],
pj_sockaddr_in mapped_addr[])
PJ_DEF(pj_status_t)
pjstun_get_mapped_addr2(pj_pool_factory* pf, const pjstun_setting* opt,
int sock_cnt, pj_sock_t sock[],
pj_sockaddr_in mapped_addr[])
{
unsigned srv_cnt;
const pj_str_t *srv1, *srv2;
int port1, port2;
pj_sockaddr srv_addr[2];
int i, send_cnt = 0, nfds;
pj_pool_t *pool;
struct query_rec {
struct {
pj_uint32_t mapped_addr;
pj_uint32_t mapped_port;
} srv[2];
} *rec;
void *out_msg;
pj_size_t out_msg_len;
pj_pool_t* pool;
struct query_rec
{
struct
{
pj_uint32_t mapped_addr;
pj_uint32_t mapped_port;
} srv[2];
} * rec;
void* out_msg;
pj_size_t out_msg_len;
int wait_resp = 0;
pj_status_t status;
@ -89,28 +90,27 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf,
/* Create pool. */
pool = pj_pool_create(pf, "stun%p", 400, 400, NULL);
if (!pool)
return PJ_ENOMEM;
return PJ_ENOMEM;
/* Allocate client records */
rec = (struct query_rec*) pj_pool_calloc(pool, sock_cnt, sizeof(*rec));
rec = (struct query_rec*)pj_pool_calloc(pool, sock_cnt, sizeof(*rec));
if (!rec) {
status = PJ_ENOMEM;
goto on_error;
status = PJ_ENOMEM;
goto on_error;
}
TRACE_((THIS_FILE, " Memory allocated."));
/* Create the outgoing BIND REQUEST message template */
status = pjstun_create_bind_req( pool, &out_msg, &out_msg_len,
pj_rand(), pj_rand());
status = pjstun_create_bind_req(pool, &out_msg, &out_msg_len, pj_rand(),
pj_rand());
if (status != PJ_SUCCESS)
goto on_error;
goto on_error;
/* Insert magic cookie (specified in RFC 5389) when requested to. */
if (opt->use_stun2) {
pjstun_msg_hdr *hdr = (pjstun_msg_hdr*)out_msg;
hdr->tsx[0] = pj_htonl(STUN_MAGIC);
pjstun_msg_hdr* hdr = (pjstun_msg_hdr*)out_msg;
hdr->tsx[0] = pj_htonl(STUN_MAGIC);
}
TRACE_((THIS_FILE, " Binding request created."));
@ -118,19 +118,19 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf,
/* Resolve servers. */
status = pj_sockaddr_init(opt->af, &srv_addr[0], srv1, (pj_uint16_t)port1);
if (status != PJ_SUCCESS)
goto on_error;
goto on_error;
srv_cnt = 1;
if (srv2 && port2) {
status = pj_sockaddr_init(opt->af, &srv_addr[1], srv2,
(pj_uint16_t)port2);
if (status != PJ_SUCCESS)
goto on_error;
status =
pj_sockaddr_init(opt->af, &srv_addr[1], srv2, (pj_uint16_t)port2);
if (status != PJ_SUCCESS)
goto on_error;
if (pj_sockaddr_cmp(&srv_addr[1], &srv_addr[0]) != 0) {
srv_cnt++;
}
if (pj_sockaddr_cmp(&srv_addr[1], &srv_addr[0]) != 0) {
srv_cnt++;
}
}
TRACE_((THIS_FILE, " Server initialized, using %d server(s)", srv_cnt));
@ -143,211 +143,214 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf,
TRACE_((THIS_FILE, " Done initialization."));
#if defined(PJ_SELECT_NEEDS_NFDS) && PJ_SELECT_NEEDS_NFDS!=0
#if defined(PJ_SELECT_NEEDS_NFDS) && PJ_SELECT_NEEDS_NFDS != 0
nfds = -1;
for (i=0; i<sock_cnt; ++i) {
if (sock[i] > nfds) {
nfds = sock[i];
}
for (i = 0; i < sock_cnt; ++i) {
if (sock[i] > nfds) {
nfds = sock[i];
}
}
#else
nfds = FD_SETSIZE-1;
nfds = FD_SETSIZE - 1;
#endif
/* Main retransmission loop. */
for (send_cnt=0; send_cnt<MAX_REQUEST; ++send_cnt) {
pj_time_val next_tx, now;
pj_fd_set_t r;
int select_rc;
for (send_cnt = 0; send_cnt < MAX_REQUEST; ++send_cnt) {
pj_time_val next_tx, now;
pj_fd_set_t r;
int select_rc;
PJ_FD_ZERO(&r);
PJ_FD_ZERO(&r);
/* Send messages to servers that has not given us response. */
for (i=0; i<sock_cnt && status==PJ_SUCCESS; ++i) {
unsigned j;
for (j=0; j<srv_cnt && status==PJ_SUCCESS; ++j) {
pjstun_msg_hdr *msg_hdr = (pjstun_msg_hdr*) out_msg;
/* Send messages to servers that has not given us response. */
for (i = 0; i < sock_cnt && status == PJ_SUCCESS; ++i) {
unsigned j;
for (j = 0; j < srv_cnt && status == PJ_SUCCESS; ++j) {
pjstun_msg_hdr* msg_hdr = (pjstun_msg_hdr*)out_msg;
pj_ssize_t sent_len;
if (rec[i].srv[j].mapped_port != 0)
continue;
if (rec[i].srv[j].mapped_port != 0)
continue;
/* Modify message so that we can distinguish response. */
msg_hdr->tsx[2] = pj_htonl(i);
msg_hdr->tsx[3] = pj_htonl(j);
/* Modify message so that we can distinguish response. */
msg_hdr->tsx[2] = pj_htonl(i);
msg_hdr->tsx[3] = pj_htonl(j);
/* Send! */
/* Send! */
sent_len = out_msg_len;
status = pj_sock_sendto(sock[i], out_msg, &sent_len, 0,
(pj_sockaddr_t*)&srv_addr[j],
pj_sockaddr_get_len(&srv_addr[j]));
}
}
status = pj_sock_sendto(sock[i], out_msg, &sent_len, 0,
(pj_sockaddr_t*)&srv_addr[j],
pj_sockaddr_get_len(&srv_addr[j]));
}
}
/* All requests sent.
* The loop below will wait for responses until all responses have
* been received (i.e. wait_resp==0) or timeout occurs, which then
* we'll go to the next retransmission iteration.
*/
TRACE_((THIS_FILE, " Request(s) sent, counter=%d", send_cnt));
/* All requests sent.
* The loop below will wait for responses until all responses have
* been received (i.e. wait_resp==0) or timeout occurs, which then
* we'll go to the next retransmission iteration.
*/
TRACE_((THIS_FILE, " Request(s) sent, counter=%d", send_cnt));
/* Calculate time of next retransmission. */
pj_gettickcount(&next_tx);
next_tx.sec += (stun_timer[send_cnt]/1000);
next_tx.msec += (stun_timer[send_cnt]%1000);
pj_time_val_normalize(&next_tx);
/* Calculate time of next retransmission. */
pj_gettickcount(&next_tx);
next_tx.sec += (stun_timer[send_cnt] / 1000);
next_tx.msec += (stun_timer[send_cnt] % 1000);
pj_time_val_normalize(&next_tx);
for (pj_gettickcount(&now), select_rc=1;
status==PJ_SUCCESS && select_rc>=1 && wait_resp>0
&& PJ_TIME_VAL_LT(now, next_tx);
pj_gettickcount(&now))
{
pj_time_val timeout;
for (pj_gettickcount(&now), select_rc = 1;
status == PJ_SUCCESS && select_rc >= 1 && wait_resp > 0 &&
PJ_TIME_VAL_LT(now, next_tx);
pj_gettickcount(&now))
{
pj_time_val timeout;
timeout = next_tx;
PJ_TIME_VAL_SUB(timeout, now);
timeout = next_tx;
PJ_TIME_VAL_SUB(timeout, now);
for (i=0; i<sock_cnt; ++i) {
PJ_FD_SET(sock[i], &r);
}
for (i = 0; i < sock_cnt; ++i) {
PJ_FD_SET(sock[i], &r);
}
select_rc = pj_sock_select(nfds+1, &r, NULL, NULL, &timeout);
TRACE_((THIS_FILE, " select() rc=%d", select_rc));
if (select_rc < 1)
continue;
select_rc = pj_sock_select(nfds + 1, &r, NULL, NULL, &timeout);
TRACE_((THIS_FILE, " select() rc=%d", select_rc));
if (select_rc < 1)
continue;
for (i=0; i<sock_cnt; ++i) {
int sock_idx, srv_idx;
for (i = 0; i < sock_cnt; ++i) {
int sock_idx, srv_idx;
pj_ssize_t len;
pjstun_msg msg;
pj_sockaddr addr;
int addrlen = sizeof(addr);
pjstun_mapped_addr_attr *attr;
char recv_buf[128];
pjstun_msg msg;
pj_sockaddr addr;
int addrlen = sizeof(addr);
pjstun_mapped_addr_attr* attr;
char recv_buf[128];
if (!PJ_FD_ISSET(sock[i], &r))
continue;
if (!PJ_FD_ISSET(sock[i], &r))
continue;
len = sizeof(recv_buf);
status = pj_sock_recvfrom( sock[i], recv_buf,
&len, 0,
(pj_sockaddr_t*)&addr,
&addrlen);
status = pj_sock_recvfrom(sock[i], recv_buf, &len, 0,
(pj_sockaddr_t*)&addr, &addrlen);
if (status != PJ_SUCCESS) {
PJ_PERROR(4,(THIS_FILE, status,
"recvfrom() error ignored"));
if (status != PJ_SUCCESS) {
PJ_PERROR(4,
(THIS_FILE, status, "recvfrom() error ignored"));
/* Ignore non-PJ_SUCCESS status.
* It possible that other SIP entity is currently
* sending SIP request to us, and because SIP message
* is larger than STUN, we could get EMSGSIZE when
* we call recvfrom().
*/
status = PJ_SUCCESS;
continue;
}
/* Ignore non-PJ_SUCCESS status.
* It possible that other SIP entity is currently
* sending SIP request to us, and because SIP message
* is larger than STUN, we could get EMSGSIZE when
* we call recvfrom().
*/
status = PJ_SUCCESS;
continue;
}
status = pjstun_parse_msg(recv_buf, len, &msg);
if (status != PJ_SUCCESS) {
PJ_PERROR(4,(THIS_FILE, status,
"STUN parsing error ignored"));
status = pjstun_parse_msg(recv_buf, len, &msg);
if (status != PJ_SUCCESS) {
PJ_PERROR(
4, (THIS_FILE, status, "STUN parsing error ignored"));
/* Also ignore non-successful parsing. This may not
* be STUN response at all. See the comment above.
*/
status = PJ_SUCCESS;
continue;
}
/* Also ignore non-successful parsing. This may not
* be STUN response at all. See the comment above.
*/
status = PJ_SUCCESS;
continue;
}
sock_idx = pj_ntohl(msg.hdr->tsx[2]);
srv_idx = pj_ntohl(msg.hdr->tsx[3]);
sock_idx = pj_ntohl(msg.hdr->tsx[2]);
srv_idx = pj_ntohl(msg.hdr->tsx[3]);
if (sock_idx<0 || sock_idx>=sock_cnt || sock_idx!=i ||
srv_idx<0 || srv_idx>=2)
{
status = PJLIB_UTIL_ESTUNININDEX;
continue;
}
if (sock_idx < 0 || sock_idx >= sock_cnt || sock_idx != i ||
srv_idx < 0 || srv_idx >= 2)
{
status = PJLIB_UTIL_ESTUNININDEX;
continue;
}
if (pj_ntohs(msg.hdr->type) != PJSTUN_BINDING_RESPONSE) {
status = PJLIB_UTIL_ESTUNNOBINDRES;
continue;
}
if (pj_ntohs(msg.hdr->type) != PJSTUN_BINDING_RESPONSE) {
status = PJLIB_UTIL_ESTUNNOBINDRES;
continue;
}
if (rec[sock_idx].srv[srv_idx].mapped_port != 0) {
/* Already got response */
continue;
}
if (rec[sock_idx].srv[srv_idx].mapped_port != 0) {
/* Already got response */
continue;
}
/* From this part, we consider the packet as a valid STUN
* response for our request.
*/
--wait_resp;
/* From this part, we consider the packet as a valid STUN
* response for our request.
*/
--wait_resp;
if (pjstun_msg_find_attr(&msg, PJSTUN_ATTR_ERROR_CODE) != NULL) {
status = PJLIB_UTIL_ESTUNRECVERRATTR;
continue;
}
if (pjstun_msg_find_attr(&msg, PJSTUN_ATTR_ERROR_CODE) != NULL)
{
status = PJLIB_UTIL_ESTUNRECVERRATTR;
continue;
}
attr = (pjstun_mapped_addr_attr*)
pjstun_msg_find_attr(&msg, PJSTUN_ATTR_MAPPED_ADDR);
if (!attr) {
attr = (pjstun_mapped_addr_attr*)
pjstun_msg_find_attr(&msg, PJSTUN_ATTR_XOR_MAPPED_ADDR);
if (!attr || attr->family != 1) {
status = PJLIB_UTIL_ESTUNNOMAP;
continue;
}
}
attr = (pjstun_mapped_addr_attr*)pjstun_msg_find_attr(
&msg, PJSTUN_ATTR_MAPPED_ADDR);
if (!attr) {
attr = (pjstun_mapped_addr_attr*)pjstun_msg_find_attr(
&msg, PJSTUN_ATTR_XOR_MAPPED_ADDR);
if (!attr || attr->family != 1) {
status = PJLIB_UTIL_ESTUNNOMAP;
continue;
}
}
rec[sock_idx].srv[srv_idx].mapped_addr = attr->addr;
rec[sock_idx].srv[srv_idx].mapped_port = attr->port;
if (pj_ntohs(attr->hdr.type) == PJSTUN_ATTR_XOR_MAPPED_ADDR) {
rec[sock_idx].srv[srv_idx].mapped_addr ^= pj_htonl(STUN_MAGIC);
rec[sock_idx].srv[srv_idx].mapped_port ^= pj_htons(STUN_MAGIC >> 16);
}
}
}
rec[sock_idx].srv[srv_idx].mapped_addr = attr->addr;
rec[sock_idx].srv[srv_idx].mapped_port = attr->port;
if (pj_ntohs(attr->hdr.type) == PJSTUN_ATTR_XOR_MAPPED_ADDR) {
rec[sock_idx].srv[srv_idx].mapped_addr ^=
pj_htonl(STUN_MAGIC);
rec[sock_idx].srv[srv_idx].mapped_port ^=
pj_htons(STUN_MAGIC >> 16);
}
}
}
/* The best scenario is if all requests have been replied.
* Then we don't need to go to the next retransmission iteration.
*/
if (wait_resp <= 0)
break;
/* The best scenario is if all requests have been replied.
* Then we don't need to go to the next retransmission iteration.
*/
if (wait_resp <= 0)
break;
}
TRACE_((THIS_FILE, " All responses received, calculating result.."));
for (i=0; i<sock_cnt && status==PJ_SUCCESS; ++i) {
if (srv_cnt == 1) {
mapped_addr[i].sin_family = pj_AF_INET();
mapped_addr[i].sin_addr.s_addr = rec[i].srv[0].mapped_addr;
mapped_addr[i].sin_port = (pj_uint16_t)rec[i].srv[0].mapped_port;
for (i = 0; i < sock_cnt && status == PJ_SUCCESS; ++i) {
if (srv_cnt == 1) {
mapped_addr[i].sin_family = pj_AF_INET();
mapped_addr[i].sin_addr.s_addr = rec[i].srv[0].mapped_addr;
mapped_addr[i].sin_port = (pj_uint16_t)rec[i].srv[0].mapped_port;
if (rec[i].srv[0].mapped_addr == 0 || rec[i].srv[0].mapped_port == 0) {
status = PJLIB_UTIL_ESTUNNOTRESPOND;
break;
}
} else if (rec[i].srv[0].mapped_addr == rec[i].srv[1].mapped_addr &&
rec[i].srv[0].mapped_port == rec[i].srv[1].mapped_port)
{
mapped_addr[i].sin_family = pj_AF_INET();
mapped_addr[i].sin_addr.s_addr = rec[i].srv[0].mapped_addr;
mapped_addr[i].sin_port = (pj_uint16_t)rec[i].srv[0].mapped_port;
if (rec[i].srv[0].mapped_addr == 0 ||
rec[i].srv[0].mapped_port == 0) {
status = PJLIB_UTIL_ESTUNNOTRESPOND;
break;
}
} else if (rec[i].srv[0].mapped_addr == rec[i].srv[1].mapped_addr &&
rec[i].srv[0].mapped_port == rec[i].srv[1].mapped_port)
{
mapped_addr[i].sin_family = pj_AF_INET();
mapped_addr[i].sin_addr.s_addr = rec[i].srv[0].mapped_addr;
mapped_addr[i].sin_port = (pj_uint16_t)rec[i].srv[0].mapped_port;
if (rec[i].srv[0].mapped_addr == 0 || rec[i].srv[0].mapped_port == 0) {
status = PJLIB_UTIL_ESTUNNOTRESPOND;
break;
}
} else {
status = PJLIB_UTIL_ESTUNSYMMETRIC;
break;
}
if (rec[i].srv[0].mapped_addr == 0 ||
rec[i].srv[0].mapped_port == 0) {
status = PJLIB_UTIL_ESTUNNOTRESPOND;
break;
}
} else {
status = PJLIB_UTIL_ESTUNSYMMETRIC;
break;
}
}
TRACE_((THIS_FILE, " Pool usage=%d of %d", pj_pool_get_used_size(pool),
pj_pool_get_capacity(pool)));
pj_pool_get_capacity(pool)));
pj_pool_release(pool);
@ -355,7 +358,7 @@ PJ_DEF(pj_status_t) pjstun_get_mapped_addr2(pj_pool_factory *pf,
return status;
on_error:
if (pool) pj_pool_release(pool);
if (pool)
pj_pool_release(pool);
return status;
}

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib.h>
#include <pjlib-util.h>
@ -79,5 +78,3 @@ PJ_EXPORT_SYMBOL(pj_xml_find_node)
PJ_EXPORT_SYMBOL(pj_xml_find_next_node)
PJ_EXPORT_SYMBOL(pj_xml_find_attr)
PJ_EXPORT_SYMBOL(pj_xml_find)

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjlib-util/xml.h>
#include <pjlib-util/scanner.h>
@ -25,72 +24,72 @@
#include <pj/log.h>
#include <pj/os.h>
#define EX_SYNTAX_ERROR 12
#define THIS_FILE "xml.c"
#define EX_SYNTAX_ERROR 12
#define THIS_FILE "xml.c"
static void on_syntax_error(struct pj_scanner *scanner)
static void on_syntax_error(struct pj_scanner* scanner)
{
PJ_UNUSED_ARG(scanner);
PJ_THROW(EX_SYNTAX_ERROR);
}
static pj_xml_node *alloc_node( pj_pool_t *pool )
static pj_xml_node* alloc_node(pj_pool_t* pool)
{
pj_xml_node *node;
pj_xml_node* node;
node = PJ_POOL_ZALLOC_T(pool, pj_xml_node);
pj_list_init( &node->attr_head );
pj_list_init( &node->node_head );
pj_list_init(&node->attr_head);
pj_list_init(&node->node_head);
return node;
}
static pj_xml_attr *alloc_attr( pj_pool_t *pool )
static pj_xml_attr* alloc_attr(pj_pool_t* pool)
{
return PJ_POOL_ZALLOC_T(pool, pj_xml_attr);
}
/* This is a recursive function! */
static pj_xml_node *xml_parse_node( pj_pool_t *pool, pj_scanner *scanner)
static pj_xml_node* xml_parse_node(pj_pool_t* pool, pj_scanner* scanner)
{
pj_xml_node *node;
pj_xml_node* node;
pj_str_t end_name;
PJ_CHECK_STACK();
if (*scanner->curptr != '<')
on_syntax_error(scanner);
on_syntax_error(scanner);
/* Handle Processing Instructino (PI) construct (i.e. "<?") */
if (*scanner->curptr == '<' && *(scanner->curptr+1) == '?') {
pj_scan_advance_n(scanner, 2, PJ_FALSE);
for (;;) {
pj_str_t dummy;
pj_scan_get_until_ch(scanner, '?', &dummy);
if (*scanner->curptr=='?' && *(scanner->curptr+1)=='>') {
pj_scan_advance_n(scanner, 2, PJ_TRUE);
break;
} else {
pj_scan_advance_n(scanner, 1, PJ_FALSE);
}
}
return xml_parse_node(pool, scanner);
if (*scanner->curptr == '<' && *(scanner->curptr + 1) == '?') {
pj_scan_advance_n(scanner, 2, PJ_FALSE);
for (;;) {
pj_str_t dummy;
pj_scan_get_until_ch(scanner, '?', &dummy);
if (*scanner->curptr == '?' && *(scanner->curptr + 1) == '>') {
pj_scan_advance_n(scanner, 2, PJ_TRUE);
break;
} else {
pj_scan_advance_n(scanner, 1, PJ_FALSE);
}
}
return xml_parse_node(pool, scanner);
}
/* Handle comments construct (i.e. "<!") */
if (pj_scan_strcmp(scanner, "<!", 2) == 0) {
pj_scan_advance_n(scanner, 2, PJ_FALSE);
for (;;) {
pj_str_t dummy;
pj_scan_get_until_ch(scanner, '>', &dummy);
if (pj_scan_strcmp(scanner, ">", 1) == 0) {
pj_scan_advance_n(scanner, 1, PJ_TRUE);
break;
} else {
pj_scan_advance_n(scanner, 1, PJ_FALSE);
}
}
return xml_parse_node(pool, scanner);
pj_scan_advance_n(scanner, 2, PJ_FALSE);
for (;;) {
pj_str_t dummy;
pj_scan_get_until_ch(scanner, '>', &dummy);
if (pj_scan_strcmp(scanner, ">", 1) == 0) {
pj_scan_advance_n(scanner, 1, PJ_TRUE);
break;
} else {
pj_scan_advance_n(scanner, 1, PJ_FALSE);
}
}
return xml_parse_node(pool, scanner);
}
/* Alloc node. */
@ -100,123 +99,125 @@ static pj_xml_node *xml_parse_node( pj_pool_t *pool, pj_scanner *scanner)
pj_scan_get_char(scanner);
/* Get node name. */
pj_scan_get_until_chr( scanner, " />\t\r\n", &node->name);
pj_scan_get_until_chr(scanner, " />\t\r\n", &node->name);
/* Get attributes. */
while (*scanner->curptr != '>' && *scanner->curptr != '/') {
pj_xml_attr *attr = alloc_attr(pool);
pj_scan_get_until_chr( scanner, "=> \t\r\n", &attr->name);
if (*scanner->curptr == '=') {
pj_scan_get_char( scanner );
pj_xml_attr* attr = alloc_attr(pool);
pj_scan_get_until_chr(scanner, "=> \t\r\n", &attr->name);
if (*scanner->curptr == '=') {
pj_scan_get_char(scanner);
pj_scan_get_quotes(scanner, "\"'", "\"'", 2, &attr->value);
/* remove quote characters */
++attr->value.ptr;
attr->value.slen -= 2;
}
pj_list_push_back( &node->attr_head, attr );
/* remove quote characters */
++attr->value.ptr;
attr->value.slen -= 2;
}
pj_list_push_back(&node->attr_head, attr);
}
if (*scanner->curptr == '/') {
pj_scan_get_char(scanner);
if (pj_scan_get_char(scanner) != '>')
on_syntax_error(scanner);
return node;
pj_scan_get_char(scanner);
if (pj_scan_get_char(scanner) != '>')
on_syntax_error(scanner);
return node;
}
/* Enclosing bracket. */
if (pj_scan_get_char(scanner) != '>')
on_syntax_error(scanner);
on_syntax_error(scanner);
/* Sub nodes. */
while (*scanner->curptr == '<' && *(scanner->curptr+1) != '/'
&& *(scanner->curptr+1) != '!')
while (*scanner->curptr == '<' && *(scanner->curptr + 1) != '/' &&
*(scanner->curptr + 1) != '!')
{
pj_xml_node *sub_node = xml_parse_node(pool, scanner);
pj_list_push_back( &node->node_head, sub_node );
pj_xml_node* sub_node = xml_parse_node(pool, scanner);
pj_list_push_back(&node->node_head, sub_node);
}
/* Content. */
if (!pj_scan_is_eof(scanner) && *scanner->curptr != '<') {
pj_scan_get_until_ch(scanner, '<', &node->content);
pj_scan_get_until_ch(scanner, '<', &node->content);
}
/* CDATA content. */
if (*scanner->curptr == '<' && *(scanner->curptr+1) == '!' &&
pj_scan_strcmp(scanner, "<![CDATA[", 9) == 0)
if (*scanner->curptr == '<' && *(scanner->curptr + 1) == '!' &&
pj_scan_strcmp(scanner, "<![CDATA[", 9) == 0)
{
pj_scan_advance_n(scanner, 9, PJ_FALSE);
pj_scan_get_until_ch(scanner, ']', &node->content);
while (pj_scan_strcmp(scanner, "]]>", 3)) {
pj_str_t dummy;
pj_scan_advance_n(scanner, 9, PJ_FALSE);
pj_scan_get_until_ch(scanner, ']', &node->content);
while (pj_scan_strcmp(scanner, "]]>", 3)) {
pj_str_t dummy;
pj_scan_advance_n(scanner, 1, PJ_FALSE);
pj_scan_get_until_ch(scanner, ']', &dummy);
}
node->content.slen = scanner->curptr - node->content.ptr;
pj_scan_advance_n(scanner, 3, PJ_TRUE);
pj_scan_advance_n(scanner, 1, PJ_FALSE);
pj_scan_get_until_ch(scanner, ']', &dummy);
}
node->content.slen = scanner->curptr - node->content.ptr;
pj_scan_advance_n(scanner, 3, PJ_TRUE);
}
/* Enclosing node. */
if (pj_scan_get_char(scanner) != '<' || pj_scan_get_char(scanner) != '/')
on_syntax_error(scanner);
on_syntax_error(scanner);
pj_scan_get_until_chr(scanner, " \t>", &end_name);
/* Compare name. */
if (pj_stricmp(&node->name, &end_name) != 0)
on_syntax_error(scanner);
on_syntax_error(scanner);
/* Enclosing '>' */
if (pj_scan_get_char(scanner) != '>')
on_syntax_error(scanner);
on_syntax_error(scanner);
return node;
}
PJ_DEF(pj_xml_node*) pj_xml_parse( pj_pool_t *pool, char *msg, pj_size_t len)
PJ_DEF(pj_xml_node*) pj_xml_parse(pj_pool_t* pool, char* msg, pj_size_t len)
{
pj_xml_node *node = NULL;
pj_xml_node* node = NULL;
pj_scanner scanner;
PJ_USE_EXCEPTION;
if (!msg || !len || !pool)
return NULL;
return NULL;
pj_scan_init( &scanner, msg, len,
PJ_SCAN_AUTOSKIP_WS|PJ_SCAN_AUTOSKIP_NEWLINE,
&on_syntax_error);
PJ_TRY {
node = xml_parse_node(pool, &scanner);
pj_scan_init(&scanner, msg, len,
PJ_SCAN_AUTOSKIP_WS | PJ_SCAN_AUTOSKIP_NEWLINE,
&on_syntax_error);
PJ_TRY
{
node = xml_parse_node(pool, &scanner);
}
PJ_CATCH_ANY {
PJ_LOG(4,(THIS_FILE, "Syntax error parsing XML in line %d column %d",
scanner.line, pj_scan_get_col(&scanner)));
PJ_CATCH_ANY
{
PJ_LOG(4, (THIS_FILE, "Syntax error parsing XML in line %d column %d",
scanner.line, pj_scan_get_col(&scanner)));
}
PJ_END;
pj_scan_fini( &scanner );
pj_scan_fini(&scanner);
return node;
}
/* This is a recursive function. */
static int xml_print_node( const pj_xml_node *node, int indent,
char *buf, pj_size_t len )
static int xml_print_node(const pj_xml_node* node, int indent, char* buf,
pj_size_t len)
{
int i;
char *p = buf;
pj_xml_attr *attr;
pj_xml_node *sub_node;
char* p = buf;
pj_xml_attr* attr;
pj_xml_node* sub_node;
#define SIZE_LEFT() ((int)(len - (p-buf)))
#define SIZE_LEFT() ((int)(len - (p - buf)))
PJ_CHECK_STACK();
/* Print name. */
if (SIZE_LEFT() < node->name.slen + indent + 5)
return -1;
for (i=0; i<indent; ++i)
*p++ = ' ';
return -1;
for (i = 0; i < indent; ++i)
*p++ = ' ';
*p++ = '<';
pj_memcpy(p, node->name.ptr, node->name.slen);
p += node->name.slen;
@ -224,79 +225,81 @@ static int xml_print_node( const pj_xml_node *node, int indent,
/* Print attributes. */
attr = node->attr_head.next;
while (attr != &node->attr_head) {
if (SIZE_LEFT() < attr->name.slen + attr->value.slen + 4)
return -1;
if (SIZE_LEFT() < attr->name.slen + attr->value.slen + 4)
return -1;
*p++ = ' ';
*p++ = ' ';
/* Attribute name. */
pj_memcpy(p, attr->name.ptr, attr->name.slen);
p += attr->name.slen;
/* Attribute name. */
pj_memcpy(p, attr->name.ptr, attr->name.slen);
p += attr->name.slen;
/* Attribute value. */
if (attr->value.slen) {
*p++ = '=';
*p++ = '"';
pj_memcpy(p, attr->value.ptr, attr->value.slen);
p += attr->value.slen;
*p++ = '"';
}
/* Attribute value. */
if (attr->value.slen) {
*p++ = '=';
*p++ = '"';
pj_memcpy(p, attr->value.ptr, attr->value.slen);
p += attr->value.slen;
*p++ = '"';
}
attr = attr->next;
attr = attr->next;
}
/* Check for empty node. */
if (node->content.slen==0 &&
node->node_head.next==(pj_xml_node*)&node->node_head)
if (node->content.slen == 0 &&
node->node_head.next == (pj_xml_node*)&node->node_head)
{
if (SIZE_LEFT() < 3) return -1;
*p++ = ' ';
*p++ = '/';
*p++ = '>';
return (int)(p-buf);
if (SIZE_LEFT() < 3)
return -1;
*p++ = ' ';
*p++ = '/';
*p++ = '>';
return (int)(p - buf);
}
/* Enclosing '>' */
if (SIZE_LEFT() < 1) return -1;
if (SIZE_LEFT() < 1)
return -1;
*p++ = '>';
/* Print sub nodes. */
sub_node = node->node_head.next;
while (sub_node != (pj_xml_node*)&node->node_head) {
int printed;
int printed;
if (SIZE_LEFT() < indent + 3)
return -1;
//*p++ = '\r';
*p++ = '\n';
if (SIZE_LEFT() < indent + 3)
return -1;
//*p++ = '\r';
*p++ = '\n';
printed = xml_print_node(sub_node, indent + 1, p, SIZE_LEFT());
if (printed < 0)
return -1;
printed = xml_print_node(sub_node, indent + 1, p, SIZE_LEFT());
if (printed < 0)
return -1;
p += printed;
sub_node = sub_node->next;
p += printed;
sub_node = sub_node->next;
}
/* Content. */
if (node->content.slen) {
if (SIZE_LEFT() < node->content.slen) return -1;
pj_memcpy(p, node->content.ptr, node->content.slen);
p += node->content.slen;
if (SIZE_LEFT() < node->content.slen)
return -1;
pj_memcpy(p, node->content.ptr, node->content.slen);
p += node->content.slen;
}
/* Enclosing node. */
if (node->node_head.next != (pj_xml_node*)&node->node_head) {
if (SIZE_LEFT() < node->name.slen + 5 + indent)
return -1;
//*p++ = '\r';
*p++ = '\n';
for (i=0; i<indent; ++i)
*p++ = ' ';
if (SIZE_LEFT() < node->name.slen + 5 + indent)
return -1;
//*p++ = '\r';
*p++ = '\n';
for (i = 0; i < indent; ++i)
*p++ = ' ';
} else {
if (SIZE_LEFT() < node->name.slen + 3)
return -1;
if (SIZE_LEFT() < node->name.slen + 3)
return -1;
}
*p++ = '<';
*p++ = '/';
@ -306,203 +309,200 @@ static int xml_print_node( const pj_xml_node *node, int indent,
#undef SIZE_LEFT
return (int)(p-buf);
return (int)(p - buf);
}
PJ_DEF(int) pj_xml_print(const pj_xml_node *node, char *buf, pj_size_t len,
pj_bool_t include_prolog)
PJ_DEF(int)
pj_xml_print(const pj_xml_node* node, char* buf, pj_size_t len,
pj_bool_t include_prolog)
{
int prolog_len = 0;
int printed;
if (!node || !buf || !len)
return 0;
return 0;
if (include_prolog) {
pj_str_t prolog = {"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", 39};
if ((int)len < prolog.slen)
return -1;
pj_memcpy(buf, prolog.ptr, prolog.slen);
prolog_len = (int)prolog.slen;
pj_str_t prolog = { "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
39 };
if ((int)len < prolog.slen)
return -1;
pj_memcpy(buf, prolog.ptr, prolog.slen);
prolog_len = (int)prolog.slen;
}
printed = xml_print_node(node, 0, buf+prolog_len, len-prolog_len) + prolog_len;
if (printed > 0 && len-printed >= 1) {
buf[printed++] = '\n';
printed =
xml_print_node(node, 0, buf + prolog_len, len - prolog_len) + prolog_len;
if (printed > 0 && len - printed >= 1) {
buf[printed++] = '\n';
}
return printed;
}
PJ_DEF(pj_xml_node*) pj_xml_node_new(pj_pool_t *pool, const pj_str_t *name)
PJ_DEF(pj_xml_node*) pj_xml_node_new(pj_pool_t* pool, const pj_str_t* name)
{
pj_xml_node *node = alloc_node(pool);
pj_xml_node* node = alloc_node(pool);
pj_strdup(pool, &node->name, name);
return node;
}
PJ_DEF(pj_xml_attr*) pj_xml_attr_new( pj_pool_t *pool, const pj_str_t *name,
const pj_str_t *value)
PJ_DEF(pj_xml_attr*)
pj_xml_attr_new(pj_pool_t* pool, const pj_str_t* name, const pj_str_t* value)
{
pj_xml_attr *attr = alloc_attr(pool);
pj_strdup( pool, &attr->name, name);
pj_strdup( pool, &attr->value, value);
pj_xml_attr* attr = alloc_attr(pool);
pj_strdup(pool, &attr->name, name);
pj_strdup(pool, &attr->value, value);
return attr;
}
PJ_DEF(void) pj_xml_add_node( pj_xml_node *parent, pj_xml_node *node )
PJ_DEF(void) pj_xml_add_node(pj_xml_node* parent, pj_xml_node* node)
{
pj_list_push_back(&parent->node_head, node);
}
PJ_DEF(void) pj_xml_add_attr( pj_xml_node *node, pj_xml_attr *attr )
PJ_DEF(void) pj_xml_add_attr(pj_xml_node* node, pj_xml_attr* attr)
{
pj_list_push_back(&node->attr_head, attr);
}
PJ_DEF(pj_xml_node*) pj_xml_find_node(const pj_xml_node *parent,
const pj_str_t *name)
PJ_DEF(pj_xml_node*)
pj_xml_find_node(const pj_xml_node* parent, const pj_str_t* name)
{
const pj_xml_node *node = parent->node_head.next;
const pj_xml_node* node = parent->node_head.next;
PJ_CHECK_STACK();
while (node != (void*)&parent->node_head) {
if (pj_stricmp(&node->name, name) == 0)
return (pj_xml_node*)node;
node = node->next;
if (pj_stricmp(&node->name, name) == 0)
return (pj_xml_node*)node;
node = node->next;
}
return NULL;
}
PJ_DEF(pj_xml_node*) pj_xml_find_node_rec(const pj_xml_node *parent,
const pj_str_t *name)
PJ_DEF(pj_xml_node*)
pj_xml_find_node_rec(const pj_xml_node* parent, const pj_str_t* name)
{
const pj_xml_node *node = parent->node_head.next;
const pj_xml_node* node = parent->node_head.next;
PJ_CHECK_STACK();
while (node != (void*)&parent->node_head) {
pj_xml_node *found;
if (pj_stricmp(&node->name, name) == 0)
return (pj_xml_node*)node;
found = pj_xml_find_node_rec(node, name);
if (found)
return (pj_xml_node*)found;
node = node->next;
pj_xml_node* found;
if (pj_stricmp(&node->name, name) == 0)
return (pj_xml_node*)node;
found = pj_xml_find_node_rec(node, name);
if (found)
return (pj_xml_node*)found;
node = node->next;
}
return NULL;
}
PJ_DEF(pj_xml_node*) pj_xml_find_next_node( const pj_xml_node *parent,
const pj_xml_node *node,
const pj_str_t *name)
PJ_DEF(pj_xml_node*)
pj_xml_find_next_node(const pj_xml_node* parent, const pj_xml_node* node,
const pj_str_t* name)
{
PJ_CHECK_STACK();
node = node->next;
while (node != (void*)&parent->node_head) {
if (pj_stricmp(&node->name, name) == 0)
return (pj_xml_node*)node;
node = node->next;
if (pj_stricmp(&node->name, name) == 0)
return (pj_xml_node*)node;
node = node->next;
}
return NULL;
}
PJ_DEF(pj_xml_attr*) pj_xml_find_attr( const pj_xml_node *node,
const pj_str_t *name,
const pj_str_t *value)
PJ_DEF(pj_xml_attr*)
pj_xml_find_attr(const pj_xml_node* node, const pj_str_t* name,
const pj_str_t* value)
{
const pj_xml_attr *attr = node->attr_head.next;
const pj_xml_attr* attr = node->attr_head.next;
while (attr != (void*)&node->attr_head) {
if (pj_stricmp(&attr->name, name)==0) {
if (value) {
if (pj_stricmp(&attr->value, value)==0)
return (pj_xml_attr*)attr;
} else {
return (pj_xml_attr*)attr;
}
}
attr = attr->next;
if (pj_stricmp(&attr->name, name) == 0) {
if (value) {
if (pj_stricmp(&attr->value, value) == 0)
return (pj_xml_attr*)attr;
} else {
return (pj_xml_attr*)attr;
}
}
attr = attr->next;
}
return NULL;
}
PJ_DEF(pj_xml_node*) pj_xml_find( const pj_xml_node *parent,
const pj_str_t *name,
const void *data,
pj_bool_t (*match)(const pj_xml_node *,
const void*))
PJ_DEF(pj_xml_node*)
pj_xml_find(const pj_xml_node* parent, const pj_str_t* name, const void* data,
pj_bool_t (*match)(const pj_xml_node*, const void*))
{
const pj_xml_node *node = (const pj_xml_node *)parent->node_head.next;
const pj_xml_node* node = (const pj_xml_node*)parent->node_head.next;
if (!name && !match)
return NULL;
return NULL;
while (node != (const pj_xml_node*) &parent->node_head) {
if (name) {
if (pj_stricmp(&node->name, name)!=0) {
node = node->next;
continue;
}
}
if (match) {
if (match(node, data))
return (pj_xml_node*)node;
} else {
return (pj_xml_node*)node;
}
while (node != (const pj_xml_node*)&parent->node_head) {
if (name) {
if (pj_stricmp(&node->name, name) != 0) {
node = node->next;
continue;
}
}
if (match) {
if (match(node, data))
return (pj_xml_node*)node;
} else {
return (pj_xml_node*)node;
}
node = node->next;
node = node->next;
}
return NULL;
}
PJ_DEF(pj_xml_node*) pj_xml_find_rec( const pj_xml_node *parent,
const pj_str_t *name,
const void *data,
pj_bool_t (*match)(const pj_xml_node*,
const void*))
PJ_DEF(pj_xml_node*)
pj_xml_find_rec(const pj_xml_node* parent, const pj_str_t* name,
const void* data,
pj_bool_t (*match)(const pj_xml_node*, const void*))
{
const pj_xml_node *node = (const pj_xml_node *)parent->node_head.next;
const pj_xml_node* node = (const pj_xml_node*)parent->node_head.next;
if (!name && !match)
return NULL;
return NULL;
while (node != (const pj_xml_node*) &parent->node_head) {
pj_xml_node *found;
while (node != (const pj_xml_node*)&parent->node_head) {
pj_xml_node* found;
if (name) {
if (pj_stricmp(&node->name, name)==0) {
if (match) {
if (match(node, data))
return (pj_xml_node*)node;
} else {
return (pj_xml_node*)node;
}
}
if (name) {
if (pj_stricmp(&node->name, name) == 0) {
if (match) {
if (match(node, data))
return (pj_xml_node*)node;
} else {
return (pj_xml_node*)node;
}
}
} else if (match) {
if (match(node, data))
return (pj_xml_node*)node;
}
} else if (match) {
if (match(node, data))
return (pj_xml_node*)node;
}
found = pj_xml_find_rec(node, name, data, match);
if (found)
return found;
found = pj_xml_find_rec(node, name, data, match);
if (found)
return found;
node = node->next;
node = node->next;
}
return NULL;
}
PJ_DEF(pj_xml_node*) pj_xml_clone( pj_pool_t *pool, const pj_xml_node *rhs)
PJ_DEF(pj_xml_node*) pj_xml_clone(pj_pool_t* pool, const pj_xml_node* rhs)
{
pj_xml_node *node;
const pj_xml_attr *r_attr;
const pj_xml_node *child;
pj_xml_node* node;
const pj_xml_attr* r_attr;
const pj_xml_node* child;
node = alloc_node(pool);
@ -512,27 +512,26 @@ PJ_DEF(pj_xml_node*) pj_xml_clone( pj_pool_t *pool, const pj_xml_node *rhs)
/* Clone all attributes */
r_attr = rhs->attr_head.next;
while (r_attr != &rhs->attr_head) {
pj_xml_attr* attr;
pj_xml_attr *attr;
attr = alloc_attr(pool);
pj_strdup(pool, &attr->name, &r_attr->name);
pj_strdup(pool, &attr->value, &r_attr->value);
attr = alloc_attr(pool);
pj_strdup(pool, &attr->name, &r_attr->name);
pj_strdup(pool, &attr->value, &r_attr->value);
pj_list_push_back(&node->attr_head, attr);
pj_list_push_back(&node->attr_head, attr);
r_attr = r_attr->next;
r_attr = r_attr->next;
}
/* Clone all child nodes. */
child = rhs->node_head.next;
while (child != (pj_xml_node*) &rhs->node_head) {
pj_xml_node *new_child;
while (child != (pj_xml_node*)&rhs->node_head) {
pj_xml_node* new_child;
new_child = pj_xml_clone(pool, child);
pj_list_push_back(&node->node_head, new_child);
new_child = pj_xml_clone(pool, child);
pj_list_push_back(&node->node_head, new_child);
child = child->next;
child = child->next;
}
return node;

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
@ -14,7 +13,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_FILE_HPP__
#define __PJPP_FILE_HPP__
@ -28,13 +27,12 @@
//
// File API.
//
class Pj_File_API
{
public:
class Pj_File_API {
public:
//
// Check file existance.
//
static bool file_exists(const char *filename)
static bool file_exists(const char* filename)
{
return pj_file_exists(filename) != 0;
}
@ -42,7 +40,7 @@ public:
//
// Get file size.
//
static pj_off_t file_size(const char *filename)
static pj_off_t file_size(const char* filename)
{
return pj_file_size(filename);
}
@ -50,7 +48,7 @@ public:
//
// Delete file.
//
static pj_status_t file_delete(const char *filename)
static pj_status_t file_delete(const char* filename)
{
return pj_file_delete(filename);
}
@ -58,7 +56,7 @@ public:
//
// Move/rename file.
//
static pj_status_t file_move(const char *oldname, const char *newname)
static pj_status_t file_move(const char* oldname, const char* newname)
{
return pj_file_move(oldname, newname);
}
@ -66,19 +64,17 @@ public:
//
// Get stat.
//
static pj_status_t file_stat(const char *filename, pj_file_stat *buf)
static pj_status_t file_stat(const char* filename, pj_file_stat* buf)
{
return pj_file_getstat(filename, buf);
}
};
//
// File.
//
class Pj_File : public Pj_Object
{
public:
class Pj_File : public Pj_Object {
public:
//
// Offset type to be used in setpos.
//
@ -92,17 +88,14 @@ public:
//
// Default constructor.
//
Pj_File()
: hnd_(0)
{
}
Pj_File() : hnd_(0)
{}
//
// Construct and open a file.
//
Pj_File(Pj_Pool *pool, const char *filename,
unsigned access = PJ_O_RDONLY)
: hnd_(NULL)
Pj_File(Pj_Pool* pool, const char* filename, unsigned access = PJ_O_RDONLY)
: hnd_(NULL)
{
open(pool, filename, access);
}
@ -118,8 +111,8 @@ public:
//
// Open a file.
//
pj_status_t open(Pj_Pool *pool, const char *filename,
unsigned access = PJ_O_RDONLY )
pj_status_t open(Pj_Pool* pool, const char* filename,
unsigned access = PJ_O_RDONLY)
{
close();
return pj_file_open(pool->pool_(), filename, access, &hnd_);
@ -139,7 +132,7 @@ public:
//
// Write data.
//
pj_ssize_t write(const void *buff, pj_size_t size)
pj_ssize_t write(const void* buff, pj_size_t size)
{
pj_ssize_t bytes = size;
if (pj_file_write(hnd_, buff, &bytes) != PJ_SUCCESS)
@ -150,7 +143,7 @@ public:
//
// Read data.
//
pj_ssize_t read(void *buf, pj_size_t size)
pj_ssize_t read(void* buf, pj_size_t size)
{
pj_ssize_t bytes = size;
if (pj_file_read(hnd_, buf, &bytes) != PJ_SUCCESS)
@ -163,8 +156,7 @@ public:
//
pj_status_t setpos(pj_off_t offset, Offset_Type whence)
{
return pj_file_setpos(hnd_, offset,
(enum pj_file_seek_type)whence);
return pj_file_setpos(hnd_, offset, (enum pj_file_seek_type)whence);
}
//
@ -178,11 +170,8 @@ public:
return pos;
}
private:
private:
pj_oshandle_t hnd_;
};
#endif /* __PJPP_FILE_HPP__ */
#endif /* __PJPP_FILE_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_HASH_HPP__
#define __PJPP_HASH_HPP__
@ -27,98 +26,90 @@
//
// Hash table.
//
class Pj_Hash_Table : public Pj_Object
{
public:
class Pj_Hash_Table : public Pj_Object {
public:
//
// Hash table iterator.
//
class iterator
{
public:
iterator()
class iterator {
public:
iterator()
{}
explicit iterator(pj_hash_table_t* h, pj_hash_iterator_t* i)
: ht_(h), it_(i)
{}
iterator(const iterator& rhs) : ht_(rhs.ht_), it_(rhs.it_)
{}
void operator++()
{
it_ = pj_hash_next(ht_, it_);
}
explicit iterator(pj_hash_table_t *h, pj_hash_iterator_t *i)
: ht_(h), it_(i)
bool operator==(const iterator& rhs)
{
return ht_ == rhs.ht_ && it_ == rhs.it_;
}
iterator(const iterator &rhs)
: ht_(rhs.ht_), it_(rhs.it_)
iterator& operator=(const iterator& rhs)
{
ht_ = rhs.ht_;
it_ = rhs.it_;
return *this;
}
void operator++()
{
it_ = pj_hash_next(ht_, it_);
}
bool operator==(const iterator &rhs)
{
return ht_ == rhs.ht_ && it_ == rhs.it_;
}
iterator & operator=(const iterator &rhs)
{
ht_=rhs.ht_; it_=rhs.it_;
return *this;
}
private:
pj_hash_table_t *ht_;
pj_hash_iterator_t it_val_;
pj_hash_iterator_t *it_;
friend class Pj_Hash_Table;
private:
pj_hash_table_t* ht_;
pj_hash_iterator_t it_val_;
pj_hash_iterator_t* it_;
friend class Pj_Hash_Table;
};
//
// Construct hash table.
//
Pj_Hash_Table(Pj_Pool *pool, unsigned size)
Pj_Hash_Table(Pj_Pool* pool, unsigned size)
{
table_ = pj_hash_create(pool->pool_(), size);
table_ = pj_hash_create(pool->pool_(), size);
}
//
// Destroy hash table.
//
~Pj_Hash_Table()
{
}
{}
//
// Calculate hash value.
//
static pj_uint32_t calc( pj_uint32_t initial_hval,
const void *key,
unsigned keylen = PJ_HASH_KEY_STRING)
static pj_uint32_t calc(pj_uint32_t initial_hval, const void* key,
unsigned keylen = PJ_HASH_KEY_STRING)
{
return pj_hash_calc(initial_hval, key, keylen);
return pj_hash_calc(initial_hval, key, keylen);
}
//
// Return pjlib compatible hash table object.
//
pj_hash_table_t *pj_hash_table_t_()
pj_hash_table_t* pj_hash_table_t_()
{
return table_;
return table_;
}
//
// Get the value associated with the specified key.
//
void *get(const void *key, unsigned keylen = PJ_HASH_KEY_STRING)
void* get(const void* key, unsigned keylen = PJ_HASH_KEY_STRING)
{
return pj_hash_get(table_, key, keylen);
return pj_hash_get(table_, key, keylen);
}
//
// Associate a value with a key.
// Set the value to NULL to delete the key from the hash table.
//
void set(Pj_Pool *pool,
const void *key,
void *value,
void set(Pj_Pool* pool, const void* key, void* value,
unsigned keylen = PJ_HASH_KEY_STRING)
{
pj_hash_set(pool->pool_(), table_, key, keylen, value);
pj_hash_set(pool->pool_(), table_, key, keylen, value);
}
//
@ -126,7 +117,7 @@ public:
//
unsigned count()
{
return pj_hash_count(table_);
return pj_hash_count(table_);
}
//
@ -134,9 +125,9 @@ public:
//
iterator begin()
{
iterator it(table_, NULL);
it.it_ = pj_hash_first(table_, &it.it_val_);
return it;
iterator it(table_, NULL);
it.it_ = pj_hash_first(table_, &it.it_val_);
return it;
}
//
@ -144,13 +135,11 @@ public:
//
iterator end()
{
return iterator(table_, NULL);
return iterator(table_, NULL);
}
private:
pj_hash_table_t *table_;
private:
pj_hash_table_t* table_;
};
#endif /* __PJPP_HASH_HPP__ */
#endif /* __PJPP_HASH_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_LIST_HPP__
#define __PJPP_LIST_HPP__
@ -23,7 +22,6 @@
#include <pj/list.h>
#include <pj++/pool.hpp>
//
// Linked-list.
//
@ -39,86 +37,81 @@
//
//
template <class List_Node>
class Pj_List : public Pj_Object
{
public:
class Pj_List : public Pj_Object {
public:
//
// List const_iterator.
//
class const_iterator
{
public:
const_iterator()
: node_(NULL)
class const_iterator {
public:
const_iterator() : node_(NULL)
{}
const_iterator(const List_Node *nd)
: node_((List_Node*)nd)
const_iterator(const List_Node* nd) : node_((List_Node*)nd)
{}
const List_Node * operator *()
{
return node_;
const List_Node* operator*()
{
return node_;
}
const List_Node * operator -> ()
{
return node_;
const List_Node* operator->()
{
return node_;
}
const_iterator operator++()
{
return const_iterator((const List_Node *)node_->next);
const_iterator operator++()
{
return const_iterator((const List_Node*)node_->next);
}
bool operator==(const const_iterator &rhs)
{
return node_ == rhs.node_;
bool operator==(const const_iterator& rhs)
{
return node_ == rhs.node_;
}
bool operator!=(const const_iterator &rhs)
{
return node_ != rhs.node_;
bool operator!=(const const_iterator& rhs)
{
return node_ != rhs.node_;
}
protected:
List_Node *node_;
protected:
List_Node* node_;
};
//
// List iterator.
//
class iterator : public const_iterator
{
public:
iterator()
class iterator : public const_iterator {
public:
iterator()
{}
iterator(List_Node *nd)
: const_iterator(nd)
iterator(List_Node* nd) : const_iterator(nd)
{}
List_Node * operator *()
{
return node_;
List_Node* operator*()
{
return node_;
}
List_Node * operator -> ()
{
return node_;
List_Node* operator->()
{
return node_;
}
iterator operator++()
{
return iterator((List_Node*)node_->next);
iterator operator++()
{
return iterator((List_Node*)node_->next);
}
bool operator==(const iterator &rhs)
{
return node_ == rhs.node_;
bool operator==(const iterator& rhs)
{
return node_ == rhs.node_;
}
bool operator!=(const iterator &rhs)
{
return node_ != rhs.node_;
bool operator!=(const iterator& rhs)
{
return node_ != rhs.node_;
}
};
//
// Default constructor.
//
Pj_List()
{
pj_list_init(&root_);
if (0) compiletest();
Pj_List()
{
pj_list_init(&root_);
if (0)
compiletest();
}
//
@ -126,11 +119,11 @@ public:
//
operator pj_list&()
{
return (pj_list&)root_;
return (pj_list&)root_;
}
operator const pj_list&()
{
return (const pj_list&)root_;
return (const pj_list&)root_;
}
//
@ -138,19 +131,19 @@ public:
//
operator pj_list*()
{
return (pj_list*)&root_;
return (pj_list*)&root_;
}
operator const pj_list*()
{
return (const pj_list*)&root_;
return (const pj_list*)&root_;
}
//
// Check if list is empty.
//
//
bool empty() const
{
return pj_list_empty(&root_);
return pj_list_empty(&root_);
}
//
@ -158,7 +151,7 @@ public:
//
iterator begin()
{
return iterator(root_.next);
return iterator(root_.next);
}
//
@ -166,7 +159,7 @@ public:
//
const_iterator begin() const
{
return const_iterator(root_.next);
return const_iterator(root_.next);
}
//
@ -174,7 +167,7 @@ public:
//
const_iterator end() const
{
return const_iterator((List_Node*)&root_);
return const_iterator((List_Node*)&root_);
}
//
@ -182,79 +175,79 @@ public:
//
iterator end()
{
return iterator((List_Node*)&root_);
return iterator((List_Node*)&root_);
}
//
// Insert node.
//
void insert_before (iterator &pos, List_Node *node)
void insert_before(iterator& pos, List_Node* node)
{
pj_list_insert_before( *pos, node );
pj_list_insert_before(*pos, node);
}
//
// Insert node.
//
void insert_after(iterator &pos, List_Node *node)
void insert_after(iterator& pos, List_Node* node)
{
pj_list_insert_after(*pos, node);
pj_list_insert_after(*pos, node);
}
//
// Merge list.
//
void merge_first(List_Node *list2)
void merge_first(List_Node* list2)
{
pj_list_merge_first(&root_, list2);
pj_list_merge_first(&root_, list2);
}
//
// Merge list.
//
void merge_last(Pj_List *list)
void merge_last(Pj_List* list)
{
pj_list_merge_last(&root_, &list->root_);
pj_list_merge_last(&root_, &list->root_);
}
//
// Insert list.
//
void insert_nodes_before(iterator &pos, Pj_List *list2)
void insert_nodes_before(iterator& pos, Pj_List* list2)
{
pj_list_insert_nodes_before(*pos, &list2->root_);
pj_list_insert_nodes_before(*pos, &list2->root_);
}
//
// Insert list.
//
void insert_nodes_after(iterator &pos, Pj_List *list2)
void insert_nodes_after(iterator& pos, Pj_List* list2)
{
pj_list_insert_nodes_after(*pos, &list2->root_);
pj_list_insert_nodes_after(*pos, &list2->root_);
}
//
// Erase an element.
//
void erase(iterator &it)
void erase(iterator& it)
{
pj_list_erase(*it);
pj_list_erase(*it);
}
//
// Get first element.
//
List_Node *front()
List_Node* front()
{
return root_.next;
return root_.next;
}
//
// Get first element.
//
const List_Node *front() const
const List_Node* front() const
{
return root_.next;
return root_.next;
}
//
@ -262,23 +255,23 @@ public:
//
void pop_front()
{
pj_list_erase(root_.next);
pj_list_erase(root_.next);
}
//
// Get last element.
//
List_Node *back()
List_Node* back()
{
return root_.prev;
return root_.prev;
}
//
// Get last element.
//
const List_Node *back() const
const List_Node* back() const
{
return root_.prev;
return root_.prev;
}
//
@ -286,41 +279,41 @@ public:
//
void pop_back()
{
pj_list_erase(root_.prev);
pj_list_erase(root_.prev);
}
//
// Find a node.
//
iterator find(List_Node *node)
iterator find(List_Node* node)
{
List_Node *n = pj_list_find_node(&root_, node);
return n ? iterator(n) : end();
List_Node* n = pj_list_find_node(&root_, node);
return n ? iterator(n) : end();
}
//
// Find a node.
//
const_iterator find(List_Node *node) const
const_iterator find(List_Node* node) const
{
List_Node *n = pj_list_find_node(&root_, node);
return n ? const_iterator(n) : end();
List_Node* n = pj_list_find_node(&root_, node);
return n ? const_iterator(n) : end();
}
//
// Insert a node in the back.
//
void push_back(List_Node *node)
void push_back(List_Node* node)
{
pj_list_insert_after(root_.prev, node);
pj_list_insert_after(root_.prev, node);
}
//
// Insert a node in the front.
//
void push_front(List_Node *node)
void push_front(List_Node* node)
{
pj_list_insert_before(root_.next, node);
pj_list_insert_before(root_.next, node);
}
//
@ -328,25 +321,24 @@ public:
//
void clear()
{
root_.next = &root_;
root_.prev = &root_;
root_.next = &root_;
root_.prev = &root_;
}
private:
private:
struct RootNode
{
PJ_DECL_LIST_MEMBER(List_Node);
PJ_DECL_LIST_MEMBER(List_Node);
} root_;
void compiletest()
{
// If you see error in this line,
// it's because List_Node is not derived from Pj_List_Node.
List_Node *n = (List_Node*)0;
n = (List_Node *)n->next; n = (List_Node *)n->prev;
// If you see error in this line,
// it's because List_Node is not derived from Pj_List_Node.
List_Node* n = (List_Node*)0;
n = (List_Node*)n->next;
n = (List_Node*)n->prev;
}
};
#endif /* __PJPP_LIST_HPP__ */
#endif /* __PJPP_LIST_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_LOCK_HPP__
#define __PJPP_LOCK_HPP__
@ -27,16 +26,13 @@
//////////////////////////////////////////////////////////////////////////////
// Lock object.
//
class Pj_Lock : public Pj_Object
{
public:
class Pj_Lock : public Pj_Object {
public:
//
// Constructor.
//
explicit Pj_Lock(pj_lock_t *lock)
: lock_(lock)
{
}
explicit Pj_Lock(pj_lock_t* lock) : lock_(lock)
{}
//
// Destructor.
@ -50,7 +46,7 @@ public:
//
// Get pjlib compatible lock object.
//
pj_lock_t *pj_lock_t_()
pj_lock_t* pj_lock_t_()
{
return lock_;
}
@ -71,21 +67,19 @@ public:
return pj_lock_release(lock_);
}
protected:
pj_lock_t *lock_;
protected:
pj_lock_t* lock_;
};
//////////////////////////////////////////////////////////////////////////////
// Null lock object.
//
class Pj_Null_Lock : public Pj_Lock
{
public:
class Pj_Null_Lock : public Pj_Lock {
public:
//
// Default constructor.
//
explicit Pj_Null_Lock(Pj_Pool *pool, const char *name = NULL)
explicit Pj_Null_Lock(Pj_Pool* pool, const char* name = NULL)
: Pj_Lock(NULL)
{
pj_lock_create_null_mutex(pool->pool_(), name, &lock_);
@ -95,13 +89,12 @@ public:
//////////////////////////////////////////////////////////////////////////////
// Simple mutex lock object.
//
class Pj_Simple_Mutex_Lock : public Pj_Lock
{
public:
class Pj_Simple_Mutex_Lock : public Pj_Lock {
public:
//
// Default constructor.
//
explicit Pj_Simple_Mutex_Lock(Pj_Pool *pool, const char *name = NULL)
explicit Pj_Simple_Mutex_Lock(Pj_Pool* pool, const char* name = NULL)
: Pj_Lock(NULL)
{
pj_lock_create_simple_mutex(pool->pool_(), name, &lock_);
@ -111,13 +104,12 @@ public:
//////////////////////////////////////////////////////////////////////////////
// Recursive mutex lock object.
//
class Pj_Recursive_Mutex_Lock : public Pj_Lock
{
public:
class Pj_Recursive_Mutex_Lock : public Pj_Lock {
public:
//
// Default constructor.
//
explicit Pj_Recursive_Mutex_Lock(Pj_Pool *pool, const char *name = NULL)
explicit Pj_Recursive_Mutex_Lock(Pj_Pool* pool, const char* name = NULL)
: Pj_Lock(NULL)
{
pj_lock_create_recursive_mutex(pool->pool_(), name, &lock_);
@ -127,23 +119,17 @@ public:
//////////////////////////////////////////////////////////////////////////////
// Semaphore lock object.
//
class Pj_Semaphore_Lock : public Pj_Lock
{
public:
class Pj_Semaphore_Lock : public Pj_Lock {
public:
//
// Default constructor.
//
explicit Pj_Semaphore_Lock(Pj_Pool *pool,
unsigned max=PJ_MAXINT32,
unsigned initial=0,
const char *name=NULL)
explicit Pj_Semaphore_Lock(Pj_Pool* pool, unsigned max = PJ_MAXINT32,
unsigned initial = 0, const char* name = NULL)
: Pj_Lock(NULL)
{
pj_lock_create_semaphore(pool->pool_(), name, initial, max, &lock_);
}
};
#endif /* __PJPP_LOCK_HPP__ */
#endif /* __PJPP_LOCK_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_OS_HPP__
#define __PJPP_OS_HPP__
@ -30,17 +29,15 @@ class Pj_Thread;
//
// Thread API.
//
class Pj_Thread_API
{
public:
class Pj_Thread_API {
public:
//
// Create a thread.
//
static pj_status_t create( Pj_Pool *pool, pj_thread_t **thread,
pj_thread_proc *proc, void *arg,
unsigned flags = 0,
const char *name = NULL,
pj_size_t stack_size = 0 )
static pj_status_t create(Pj_Pool* pool, pj_thread_t** thread,
pj_thread_proc* proc, void* arg,
unsigned flags = 0, const char* name = NULL,
pj_size_t stack_size = 0)
{
return pj_thread_create(pool->pool_(), name, proc, arg, stack_size,
flags, thread);
@ -49,18 +46,18 @@ public:
//
// Register a thread.
//
static pj_status_t register_this_thread( pj_thread_desc desc,
pj_thread_t **thread,
const char *name = NULL )
static pj_status_t register_this_thread(pj_thread_desc desc,
pj_thread_t** thread,
const char* name = NULL)
{
return pj_thread_register( name, desc, thread );
return pj_thread_register(name, desc, thread);
}
//
// Get current thread.
// Will return pj_thread_t (sorry folks, not Pj_Thread).
//
static pj_thread_t *this_thread()
static pj_thread_t* this_thread()
{
return pj_thread_this();
}
@ -68,7 +65,7 @@ public:
//
// Get thread name.
//
static const char *get_name(pj_thread_t *thread)
static const char* get_name(pj_thread_t* thread)
{
return pj_thread_get_name(thread);
}
@ -76,7 +73,7 @@ public:
//
// Resume thread.
//
static pj_status_t resume(pj_thread_t *thread)
static pj_status_t resume(pj_thread_t* thread)
{
return pj_thread_resume(thread);
}
@ -86,13 +83,13 @@ public:
//
static pj_status_t sleep(unsigned msec)
{
return pj_thread_sleep(msec);
return pj_thread_sleep(msec);
}
//
// Join the specified thread.
//
static pj_status_t join(pj_thread_t *thread)
static pj_status_t join(pj_thread_t* thread)
{
return pj_thread_join(thread);
}
@ -100,35 +97,30 @@ public:
//
// Destroy thread
//
static pj_status_t destroy(pj_thread_t *thread)
static pj_status_t destroy(pj_thread_t* thread)
{
return pj_thread_destroy(thread);
}
};
//
// Thread object.
//
// How to use:
// Derive a class from this class, then override main().
//
class Pj_Thread : public Pj_Object
{
public:
class Pj_Thread : public Pj_Object {
public:
enum Flags
{
FLAG_SUSPENDED = PJ_THREAD_SUSPENDED
FLAG_SUSPENDED = PJ_THREAD_SUSPENDED
};
//
// Default constructor.
//
Pj_Thread()
: thread_(NULL)
{
}
Pj_Thread() : thread_(NULL)
{}
//
// Destroy thread.
@ -146,28 +138,27 @@ public:
//
// Start a thread.
//
pj_status_t create( Pj_Pool *pool,
unsigned flags = 0,
const char *thread_name = NULL,
pj_size_t stack_size = PJ_THREAD_DEFAULT_STACK_SIZE)
pj_status_t create(Pj_Pool* pool, unsigned flags = 0,
const char* thread_name = NULL,
pj_size_t stack_size = PJ_THREAD_DEFAULT_STACK_SIZE)
{
destroy();
return Pj_Thread_API::create( pool, &thread_, &thread_proc, this,
flags, thread_name, stack_size);
return Pj_Thread_API::create(pool, &thread_, &thread_proc, this, flags,
thread_name, stack_size);
}
//
// Get pjlib compatible thread object.
//
pj_thread_t *pj_thread_t_()
pj_thread_t* pj_thread_t_()
{
return thread_;
return thread_;
}
//
// Get thread name.
//
const char *get_name()
const char* get_name()
{
return Pj_Thread_API::get_name(thread_);
}
@ -199,57 +190,52 @@ public:
}
}
protected:
pj_thread_t *thread_;
protected:
pj_thread_t* thread_;
static int PJ_THREAD_FUNC thread_proc(void *obj)
static int PJ_THREAD_FUNC thread_proc(void* obj)
{
Pj_Thread *thread_class = (Pj_Thread*)obj;
Pj_Thread* thread_class = (Pj_Thread*)obj;
return thread_class->main();
}
};
//
// External Thread
// (threads that were started by external means, i.e. not
// (threads that were started by external means, i.e. not
// with Pj_Thread::create).
//
// This class will normally be defined as local variable in
// external thread's stack, normally inside thread's main proc.
// But be aware that the handle will be destroyed on destructor!
//
class Pj_External_Thread : public Pj_Thread
{
public:
class Pj_External_Thread : public Pj_Thread {
public:
Pj_External_Thread()
{
}
{}
//
// Register external thread so that pjlib functions can work
// in that thread.
//
pj_status_t register_this_thread( const char *name=NULL )
pj_status_t register_this_thread(const char* name = NULL)
{
return Pj_Thread_API::register_this_thread(desc_, &thread_,name);
return Pj_Thread_API::register_this_thread(desc_, &thread_, name);
}
private:
private:
pj_thread_desc desc_;
};
//
// Thread specific data/thread local storage/TLS.
//
class Pj_Thread_Local_API
{
public:
class Pj_Thread_Local_API {
public:
//
// Allocate thread local storage (TLS) index.
//
static pj_status_t alloc(long *index)
static pj_status_t alloc(long* index)
{
return pj_thread_local_alloc(index);
}
@ -265,7 +251,7 @@ public:
//
// Set thread specific data.
//
static pj_status_t set(long index, void *value)
static pj_status_t set(long index, void* value)
{
return pj_thread_local_set(index, value);
}
@ -273,11 +259,10 @@ public:
//
// Get thread specific data.
//
static void *get(long index)
static void* get(long index)
{
return pj_thread_local_get(index);
}
};
//
@ -287,22 +272,18 @@ public:
// Pj_Atomic_Var var(pool, 0);
// var.set(..);
//
class Pj_Atomic_Var : public Pj_Object
{
public:
class Pj_Atomic_Var : public Pj_Object {
public:
//
// Default constructor, initialize variable with NULL.
//
Pj_Atomic_Var()
: var_(NULL)
{
}
Pj_Atomic_Var() : var_(NULL)
{}
//
// Construct atomic variable.
//
Pj_Atomic_Var(Pj_Pool *pool, pj_atomic_value_t value)
: var_(NULL)
Pj_Atomic_Var(Pj_Pool* pool, pj_atomic_value_t value) : var_(NULL)
{
create(pool, value);
}
@ -318,10 +299,10 @@ public:
//
// Create atomic variable.
//
pj_status_t create( Pj_Pool *pool, pj_atomic_value_t value)
pj_status_t create(Pj_Pool* pool, pj_atomic_value_t value)
{
destroy();
return pj_atomic_create(pool->pool_(), value, &var_);
return pj_atomic_create(pool->pool_(), value, &var_);
}
//
@ -338,9 +319,9 @@ public:
//
// Get pjlib compatible atomic variable.
//
pj_atomic_t *pj_atomic_t_()
pj_atomic_t* pj_atomic_t_()
{
return var_;
return var_;
}
//
@ -348,7 +329,7 @@ public:
//
void set(pj_atomic_value_t val)
{
pj_atomic_set(var_, val);
pj_atomic_set(var_, val);
}
//
@ -356,7 +337,7 @@ public:
//
pj_atomic_value_t get()
{
return pj_atomic_get(var_);
return pj_atomic_get(var_);
}
//
@ -364,7 +345,7 @@ public:
//
void inc()
{
pj_atomic_inc(var_);
pj_atomic_inc(var_);
}
//
@ -380,7 +361,7 @@ public:
//
void dec()
{
pj_atomic_dec(var_);
pj_atomic_dec(var_);
}
//
@ -404,35 +385,33 @@ public:
//
pj_atomic_value_t add_and_get(pj_atomic_value_t value)
{
return pj_atomic_add_and_get(var_, value );
return pj_atomic_add_and_get(var_, value);
}
private:
pj_atomic_t *var_;
private:
pj_atomic_t* var_;
};
//
// Mutex
//
class Pj_Mutex : public Pj_Object
{
public:
class Pj_Mutex : public Pj_Object {
public:
//
// Mutex type.
//
enum Type
{
DEFAULT = PJ_MUTEX_DEFAULT,
SIMPLE = PJ_MUTEX_SIMPLE,
RECURSE = PJ_MUTEX_RECURSE,
DEFAULT = PJ_MUTEX_DEFAULT,
SIMPLE = PJ_MUTEX_SIMPLE,
RECURSE = PJ_MUTEX_RECURSE,
};
//
// Default constructor will create default mutex.
//
explicit Pj_Mutex(Pj_Pool *pool, Type type = DEFAULT,
const char *name = NULL)
explicit Pj_Mutex(Pj_Pool* pool, Type type = DEFAULT,
const char* name = NULL)
: mutex_(NULL)
{
create(pool, type, name);
@ -449,17 +428,16 @@ public:
//
// Create mutex.
//
pj_status_t create( Pj_Pool *pool, Type type, const char *name = NULL)
pj_status_t create(Pj_Pool* pool, Type type, const char* name = NULL)
{
destroy();
return pj_mutex_create( pool->pool_(), name, type,
&mutex_ );
return pj_mutex_create(pool->pool_(), name, type, &mutex_);
}
//
// Create simple mutex.
//
pj_status_t create_simple( Pj_Pool *pool,const char *name = NULL)
pj_status_t create_simple(Pj_Pool* pool, const char* name = NULL)
{
return create(pool, SIMPLE, name);
}
@ -467,7 +445,7 @@ public:
//
// Create recursive mutex.
//
pj_status_t create_recursive( Pj_Pool *pool, const char *name = NULL )
pj_status_t create_recursive(Pj_Pool* pool, const char* name = NULL)
{
return create(pool, RECURSE, name);
}
@ -475,9 +453,9 @@ public:
//
// Get pjlib compatible mutex object.
//
pj_mutex_t *pj_mutex_t_()
pj_mutex_t* pj_mutex_t_()
{
return mutex_;
return mutex_;
}
//
@ -486,7 +464,7 @@ public:
void destroy()
{
if (mutex_) {
pj_mutex_destroy(mutex_);
pj_mutex_destroy(mutex_);
mutex_ = NULL;
}
}
@ -496,7 +474,7 @@ public:
//
pj_status_t acquire()
{
return pj_mutex_lock(mutex_);
return pj_mutex_lock(mutex_);
}
//
@ -504,7 +482,7 @@ public:
//
pj_status_t release()
{
return pj_mutex_unlock(mutex_);
return pj_mutex_unlock(mutex_);
}
//
@ -512,28 +490,26 @@ public:
//
pj_status_t tryacquire()
{
return pj_mutex_trylock(mutex_);
return pj_mutex_trylock(mutex_);
}
private:
pj_mutex_t *mutex_;
private:
pj_mutex_t* mutex_;
};
//
// Semaphore
//
class Pj_Semaphore : public Pj_Object
{
public:
class Pj_Semaphore : public Pj_Object {
public:
//
// Construct semaphore
//
Pj_Semaphore(Pj_Pool *pool, unsigned max,
unsigned initial = 0, const char *name = NULL)
: sem_(NULL)
Pj_Semaphore(Pj_Pool* pool, unsigned max, unsigned initial = 0,
const char* name = NULL)
: sem_(NULL)
{
create(pool, max, initial, name);
create(pool, max, initial, name);
}
//
@ -547,11 +523,11 @@ public:
//
// Create semaphore
//
pj_status_t create( Pj_Pool *pool, unsigned max,
unsigned initial = 0, const char *name = NULL )
pj_status_t create(Pj_Pool* pool, unsigned max, unsigned initial = 0,
const char* name = NULL)
{
destroy();
return pj_sem_create( pool->pool_(), name, initial, max, &sem_);
return pj_sem_create(pool->pool_(), name, initial, max, &sem_);
}
//
@ -568,9 +544,9 @@ public:
//
// Get pjlib compatible semaphore object.
//
pj_sem_t *pj_sem_t_()
pj_sem_t* pj_sem_t_()
{
return (pj_sem_t*)this;
return (pj_sem_t*)this;
}
//
@ -578,7 +554,7 @@ public:
//
pj_status_t wait()
{
return pj_sem_wait(this->pj_sem_t_());
return pj_sem_wait(this->pj_sem_t_());
}
//
@ -586,7 +562,7 @@ public:
//
pj_status_t acquire()
{
return wait();
return wait();
}
//
@ -594,7 +570,7 @@ public:
//
pj_status_t trywait()
{
return pj_sem_trywait(this->pj_sem_t_());
return pj_sem_trywait(this->pj_sem_t_());
}
//
@ -602,7 +578,7 @@ public:
//
pj_status_t tryacquire()
{
return trywait();
return trywait();
}
//
@ -610,7 +586,7 @@ public:
//
pj_status_t post()
{
return pj_sem_post(this->pj_sem_t_());
return pj_sem_post(this->pj_sem_t_());
}
//
@ -618,26 +594,24 @@ public:
//
pj_status_t release()
{
return post();
return post();
}
private:
pj_sem_t *sem_;
private:
pj_sem_t* sem_;
};
//
// Event object.
//
class Pj_Event
{
public:
class Pj_Event {
public:
//
// Construct event object.
//
Pj_Event( Pj_Pool *pool, bool manual_reset = false,
bool initial = false, const char *name = NULL )
: event_(NULL)
Pj_Event(Pj_Pool* pool, bool manual_reset = false, bool initial = false,
const char* name = NULL)
: event_(NULL)
{
create(pool, manual_reset, initial, name);
}
@ -653,20 +627,20 @@ public:
//
// Create event object.
//
pj_status_t create( Pj_Pool *pool, bool manual_reset = false,
bool initial = false, const char *name = NULL)
pj_status_t create(Pj_Pool* pool, bool manual_reset = false,
bool initial = false, const char* name = NULL)
{
destroy();
return pj_event_create(pool->pool_(), name, manual_reset, initial,
return pj_event_create(pool->pool_(), name, manual_reset, initial,
&event_);
}
//
// Get pjlib compatible event object.
//
pj_event_t *pj_event_t_()
pj_event_t* pj_event_t_()
{
return event_;
return event_;
}
//
@ -675,7 +649,7 @@ public:
void destroy()
{
if (event_) {
pj_event_destroy(event_);
pj_event_destroy(event_);
event_ = NULL;
}
}
@ -685,7 +659,7 @@ public:
//
pj_status_t wait()
{
return pj_event_wait(event_);
return pj_event_wait(event_);
}
//
@ -693,7 +667,7 @@ public:
//
pj_status_t trywait()
{
return pj_event_trywait(event_);
return pj_event_trywait(event_);
}
//
@ -701,7 +675,7 @@ public:
//
pj_status_t set()
{
return pj_event_set(this->pj_event_t_());
return pj_event_set(this->pj_event_t_());
}
//
@ -709,7 +683,7 @@ public:
//
pj_status_t pulse()
{
return pj_event_pulse(this->pj_event_t_());
return pj_event_pulse(this->pj_event_t_());
}
//
@ -717,122 +691,117 @@ public:
//
pj_status_t reset()
{
return pj_event_reset(this->pj_event_t_());
return pj_event_reset(this->pj_event_t_());
}
private:
pj_event_t *event_;
private:
pj_event_t* event_;
};
//
// Timestamp
//
class Pj_Timestamp
{
public:
class Pj_Timestamp {
public:
pj_status_t get_timestamp()
{
return pj_get_timestamp(&ts_);
return pj_get_timestamp(&ts_);
}
Pj_Timestamp& operator += (const Pj_Timestamp &rhs)
Pj_Timestamp& operator+=(const Pj_Timestamp& rhs)
{
pj_add_timestamp(&ts_, &rhs.ts_);
return *this;
pj_add_timestamp(&ts_, &rhs.ts_);
return *this;
}
Pj_Timestamp& operator -= (const Pj_Timestamp &rhs)
Pj_Timestamp& operator-=(const Pj_Timestamp& rhs)
{
pj_sub_timestamp(&ts_, &rhs.ts_);
return *this;
pj_sub_timestamp(&ts_, &rhs.ts_);
return *this;
}
Pj_Time_Val to_time() const
{
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return Pj_Time_Val(pj_elapsed_time(&zero.ts_, &ts_));
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return Pj_Time_Val(pj_elapsed_time(&zero.ts_, &ts_));
}
pj_uint32_t to_msec() const
{
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return pj_elapsed_msec(&zero.ts_, &ts_);
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return pj_elapsed_msec(&zero.ts_, &ts_);
}
pj_uint32_t to_usec() const
{
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return pj_elapsed_usec(&zero.ts_, &ts_);
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return pj_elapsed_usec(&zero.ts_, &ts_);
}
pj_uint32_t to_nanosec() const
{
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return pj_elapsed_nanosec(&zero.ts_, &ts_);
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return pj_elapsed_nanosec(&zero.ts_, &ts_);
}
pj_uint32_t to_cycle() const
{
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return pj_elapsed_cycle(&zero.ts_, &ts_);
Pj_Timestamp zero;
pj_memset(&zero, 0, sizeof(zero));
return pj_elapsed_cycle(&zero.ts_, &ts_);
}
private:
pj_timestamp ts_;
private:
pj_timestamp ts_;
};
//
// OS abstraction.
//
class Pj_OS_API
{
public:
class Pj_OS_API {
public:
//
// Get current time.
//
static pj_status_t gettimeofday( Pj_Time_Val *tv )
static pj_status_t gettimeofday(Pj_Time_Val* tv)
{
return pj_gettimeofday(tv);
return pj_gettimeofday(tv);
}
//
// Parse to time of day.
//
static pj_status_t time_decode( const Pj_Time_Val *tv,
pj_parsed_time *pt )
static pj_status_t time_decode(const Pj_Time_Val* tv, pj_parsed_time* pt)
{
return pj_time_decode(tv, pt);
return pj_time_decode(tv, pt);
}
//
// Parse from time of day.
//
static pj_status_t time_encode( const pj_parsed_time *pt,
Pj_Time_Val *tv)
static pj_status_t time_encode(const pj_parsed_time* pt, Pj_Time_Val* tv)
{
return pj_time_encode(pt, tv);
return pj_time_encode(pt, tv);
}
//
// Convert to GMT.
//
static pj_status_t time_local_to_gmt( Pj_Time_Val *tv )
static pj_status_t time_local_to_gmt(Pj_Time_Val* tv)
{
return pj_time_local_to_gmt( tv );
return pj_time_local_to_gmt(tv);
}
//
// Convert time to local.
//
static pj_status_t time_gmt_to_local( Pj_Time_Val *tv)
static pj_status_t time_gmt_to_local(Pj_Time_Val* tv)
{
return pj_time_gmt_to_local( tv );
return pj_time_gmt_to_local(tv);
}
};
@ -851,7 +820,7 @@ inline pj_parsed_time Pj_Time_Val::decode()
return pt;
}
inline pj_status_t Pj_Time_Val::encode(const pj_parsed_time *pt)
inline pj_status_t Pj_Time_Val::encode(const pj_parsed_time* pt)
{
return Pj_OS_API::time_encode(pt, this);
}
@ -866,5 +835,4 @@ inline pj_status_t Pj_Time_Val::to_local()
return Pj_OS_API::time_gmt_to_local(this);
}
#endif /* __PJPP_OS_HPP__ */
#endif /* __PJPP_OS_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_POOL_HPP__
#define __PJPP_POOL_HPP__
@ -28,74 +27,62 @@ class Pj_Caching_Pool;
//
// Base class for all Pjlib objects
//
class Pj_Object
{
public:
void *operator new(unsigned int class_size, Pj_Pool *pool);
void *operator new(unsigned int class_size, Pj_Pool &pool);
class Pj_Object {
public:
void* operator new(unsigned int class_size, Pj_Pool* pool);
void* operator new(unsigned int class_size, Pj_Pool& pool);
void operator delete(void*)
{
}
{}
void operator delete(void*, Pj_Pool*)
{
}
{}
void operator delete(void*, Pj_Pool&)
{
}
{}
//
// Inline implementations at the end of this file.
//
private:
private:
// Can not use normal new operator; must use pool.
// e.g.:
// obj = new(pool) Pj_The_Object(pool, ...);
//
void *operator new(unsigned int)
void* operator new(unsigned int)
{}
};
//
// Pool.
//
class Pj_Pool : public Pj_Object
{
public:
class Pj_Pool : public Pj_Object {
public:
//
// Default constructor, initializes internal pool to NULL.
// Application must call attach() some time later.
//
Pj_Pool()
: p_(NULL)
{
}
Pj_Pool() : p_(NULL)
{}
//
// Create pool.
//
Pj_Pool(Pj_Caching_Pool &caching_pool,
pj_size_t initial_size,
pj_size_t increment_size,
const char *name = NULL,
pj_pool_callback *callback = NULL);
Pj_Pool(Pj_Caching_Pool& caching_pool, pj_size_t initial_size,
pj_size_t increment_size, const char* name = NULL,
pj_pool_callback* callback = NULL);
//
// Construct from existing pool.
//
explicit Pj_Pool(pj_pool_t *pool)
: p_(pool)
{
}
explicit Pj_Pool(pj_pool_t* pool) : p_(pool)
{}
//
// Attach existing pool.
//
void attach(pj_pool_t *pool)
void attach(pj_pool_t* pool)
{
p_ = pool;
}
@ -103,7 +90,7 @@ public:
//
// Destructor.
//
// Release pool back to factory. Remember: if you delete pool, then
// Release pool back to factory. Remember: if you delete pool, then
// make sure that all objects that have been allocated from this pool
// have been properly destroyed.
//
@ -112,15 +99,15 @@ public:
~Pj_Pool()
{
if (p_)
pj_pool_release(p_);
pj_pool_release(p_);
}
//
// Get name.
//
const char *getobjname() const
const char* getobjname() const
{
return pj_pool_getobjname(p_);
return pj_pool_getobjname(p_);
}
//
@ -128,31 +115,31 @@ public:
//
operator pj_pool_t*()
{
return p_;
return p_;
}
//
// Get pjlib compatible pool object.
//
pj_pool_t *pool_()
pj_pool_t* pool_()
{
return p_;
return p_;
}
//
// Get pjlib compatible pool object.
//
const pj_pool_t *pool_() const
const pj_pool_t* pool_() const
{
return p_;
return p_;
}
//
// Get pjlib compatible pool object.
//
pj_pool_t *pj_pool_t_()
pj_pool_t* pj_pool_t_()
{
return p_;
return p_;
}
//
@ -160,7 +147,7 @@ public:
//
void reset()
{
pj_pool_reset(p_);
pj_pool_reset(p_);
}
//
@ -168,7 +155,7 @@ public:
//
pj_size_t get_capacity()
{
pj_pool_get_capacity(p_);
pj_pool_get_capacity(p_);
}
//
@ -176,51 +163,50 @@ public:
//
pj_size_t get_used_size()
{
pj_pool_get_used_size(p_);
pj_pool_get_used_size(p_);
}
//
// Allocate.
//
void *alloc(pj_size_t size)
void* alloc(pj_size_t size)
{
return pj_pool_alloc(p_, size);
return pj_pool_alloc(p_, size);
}
//
// Allocate elements and zero fill the memory.
//
void *calloc(pj_size_t count, pj_size_t elem)
void* calloc(pj_size_t count, pj_size_t elem)
{
return pj_pool_calloc(p_, count, elem);
return pj_pool_calloc(p_, count, elem);
}
//
// Allocate and zero fill memory.
//
void *zalloc(pj_size_t size)
void* zalloc(pj_size_t size)
{
return pj_pool_zalloc(p_, size);
}
private:
pj_pool_t *p_;
private:
pj_pool_t* p_;
};
//
// Caching pool.
//
class Pj_Caching_Pool
{
public:
class Pj_Caching_Pool {
public:
//
// Construct caching pool.
//
Pj_Caching_Pool( pj_size_t cache_capacity = 0,
const pj_pool_factory_policy *pol=&pj_pool_factory_default_policy)
Pj_Caching_Pool(
pj_size_t cache_capacity = 0,
const pj_pool_factory_policy* pol = &pj_pool_factory_default_policy)
{
pj_caching_pool_init(&cp_, pol, cache_capacity);
pj_caching_pool_init(&cp_, pol, cache_capacity);
}
//
@ -228,35 +214,32 @@ public:
//
~Pj_Caching_Pool()
{
pj_caching_pool_destroy(&cp_);
pj_caching_pool_destroy(&cp_);
}
//
// Create pool.
//
pj_pool_t *create_pool( pj_size_t initial_size,
pj_size_t increment_size,
const char *name = NULL,
pj_pool_callback *callback = NULL)
pj_pool_t* create_pool(pj_size_t initial_size, pj_size_t increment_size,
const char* name = NULL,
pj_pool_callback* callback = NULL)
{
return (pj_pool_t*)(*cp_.factory.create_pool)(&cp_.factory, name,
initial_size,
increment_size,
callback);
return (pj_pool_t*)(*cp_.factory.create_pool)(
&cp_.factory, name, initial_size, increment_size, callback);
}
private:
private:
pj_caching_pool cp_;
};
//
// Inlines for Pj_Object
//
inline void *Pj_Object::operator new(unsigned int class_size, Pj_Pool *pool)
inline void* Pj_Object::operator new(unsigned int class_size, Pj_Pool* pool)
{
return pool->alloc(class_size);
}
inline void *Pj_Object::operator new(unsigned int class_size, Pj_Pool &pool)
inline void* Pj_Object::operator new(unsigned int class_size, Pj_Pool& pool)
{
return pool.alloc(class_size);
}
@ -264,16 +247,11 @@ inline void *Pj_Object::operator new(unsigned int class_size, Pj_Pool &pool)
//
// Inlines for Pj_Pool
//
inline Pj_Pool::Pj_Pool( Pj_Caching_Pool &caching_pool,
pj_size_t initial_size,
pj_size_t increment_size,
const char *name,
pj_pool_callback *callback)
inline Pj_Pool::Pj_Pool(Pj_Caching_Pool& caching_pool, pj_size_t initial_size,
pj_size_t increment_size, const char* name,
pj_pool_callback* callback)
{
p_ = caching_pool.create_pool(initial_size, increment_size, name,
callback);
p_ = caching_pool.create_pool(initial_size, increment_size, name, callback);
}
#endif /* __PJPP_POOL_HPP__ */
#endif /* __PJPP_POOL_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_PROACTOR_HPP__
#define __PJPP_PROACTOR_HPP__
@ -29,39 +28,35 @@
class Pj_Proactor;
class Pj_Event_Handler;
//////////////////////////////////////////////////////////////////////////////
// Asynchronous operation key.
//
// Applications may inheric this class to put their application
// specific data.
//
class Pj_Async_Op : public pj_ioqueue_op_key_t
{
public:
class Pj_Async_Op : public pj_ioqueue_op_key_t {
public:
//
// Construct with null handler.
// App must call set_handler() before use.
//
Pj_Async_Op()
: handler_(NULL)
Pj_Async_Op() : handler_(NULL)
{
pj_ioqueue_op_key_init(this, sizeof(*this));
pj_ioqueue_op_key_init(this, sizeof(*this));
}
//
// Constructor.
//
explicit Pj_Async_Op(Pj_Event_Handler *handler)
: handler_(handler)
explicit Pj_Async_Op(Pj_Event_Handler* handler) : handler_(handler)
{
pj_ioqueue_op_key_init(this, sizeof(*this));
pj_ioqueue_op_key_init(this, sizeof(*this));
}
//
// Set handler.
//
void set_handler(Pj_Event_Handler *handler)
void set_handler(Pj_Event_Handler* handler)
{
handler_ = handler;
}
@ -74,13 +69,12 @@ public:
//
// Cancel the operation.
//
bool cancel(pj_ssize_t bytes_status=-PJ_ECANCELLED);
bool cancel(pj_ssize_t bytes_status = -PJ_ECANCELLED);
protected:
Pj_Event_Handler *handler_;
protected:
Pj_Event_Handler* handler_;
};
//////////////////////////////////////////////////////////////////////////////
// Event handler.
//
@ -89,21 +83,20 @@ protected:
//
// Applications should implement get_socket_handle().
//
class Pj_Event_Handler : public Pj_Object
{
class Pj_Event_Handler : public Pj_Object {
friend class Pj_Proactor;
public:
public:
//
// Default constructor.
//
Pj_Event_Handler()
: key_(NULL)
Pj_Event_Handler() : key_(NULL)
{
pj_memset(&timer_, 0, sizeof(timer_));
timer_.user_data = this;
timer_.cb = &timer_callback;
}
//
// Destroy.
//
@ -134,52 +127,47 @@ public:
//
// Start async receive.
//
pj_status_t recv( Pj_Async_Op *op_key,
void *buf, pj_ssize_t *len,
unsigned flags)
pj_status_t recv(Pj_Async_Op* op_key, void* buf, pj_ssize_t* len,
unsigned flags)
{
return pj_ioqueue_recv( key_, op_key,
buf, len, flags);
return pj_ioqueue_recv(key_, op_key, buf, len, flags);
}
//
// Start async recvfrom()
//
pj_status_t recvfrom( Pj_Async_Op *op_key,
void *buf, pj_ssize_t *len, unsigned flags,
Pj_Inet_Addr *addr)
pj_status_t recvfrom(Pj_Async_Op* op_key, void* buf, pj_ssize_t* len,
unsigned flags, Pj_Inet_Addr* addr)
{
addr->addrlen_ = sizeof(Pj_Inet_Addr);
return pj_ioqueue_recvfrom( key_, op_key, buf, len, flags,
addr, &addr->addrlen_ );
return pj_ioqueue_recvfrom(key_, op_key, buf, len, flags, addr,
&addr->addrlen_);
}
//
// Start async send()
//
pj_status_t send( Pj_Async_Op *op_key,
const void *data, pj_ssize_t *len,
unsigned flags)
pj_status_t send(Pj_Async_Op* op_key, const void* data, pj_ssize_t* len,
unsigned flags)
{
return pj_ioqueue_send( key_, op_key, data, len, flags);
return pj_ioqueue_send(key_, op_key, data, len, flags);
}
//
// Start async sendto()
//
pj_status_t sendto( Pj_Async_Op *op_key,
const void *data, pj_ssize_t *len, unsigned flags,
const Pj_Inet_Addr &addr)
pj_status_t sendto(Pj_Async_Op* op_key, const void* data, pj_ssize_t* len,
unsigned flags, const Pj_Inet_Addr& addr)
{
return pj_ioqueue_sendto(key_, op_key, data, len, flags,
&addr, sizeof(addr));
return pj_ioqueue_sendto(key_, op_key, data, len, flags, &addr,
sizeof(addr));
}
#if PJ_HAS_TCP
//
// Start async connect()
//
pj_status_t connect(const Pj_Inet_Addr &addr)
pj_status_t connect(const Pj_Inet_Addr& addr)
{
return pj_ioqueue_connect(key_, &addr, sizeof(addr));
}
@ -187,19 +175,17 @@ public:
//
// Start async accept().
//
pj_status_t accept( Pj_Async_Op *op_key,
Pj_Socket *sock,
Pj_Inet_Addr *local = NULL,
Pj_Inet_Addr *remote = NULL)
pj_status_t accept(Pj_Async_Op* op_key, Pj_Socket* sock,
Pj_Inet_Addr* local = NULL, Pj_Inet_Addr* remote = NULL)
{
int *addrlen = local ? &local->addrlen_ : NULL;
return pj_ioqueue_accept( key_, op_key, &sock->sock_,
local, remote, addrlen );
int* addrlen = local ? &local->addrlen_ : NULL;
return pj_ioqueue_accept(key_, op_key, &sock->sock_, local, remote,
addrlen);
}
#endif
protected:
protected:
//////////////////
// Overridables
//////////////////
@ -207,45 +193,39 @@ protected:
//
// Timeout callback.
//
virtual void on_timeout(int)
{
}
virtual void on_timeout(int)
{}
//
// On read complete callback.
//
virtual void on_read_complete( Pj_Async_Op*, pj_ssize_t)
{
}
virtual void on_read_complete(Pj_Async_Op*, pj_ssize_t)
{}
//
// On write complete callback.
//
virtual void on_write_complete( Pj_Async_Op *, pj_ssize_t)
{
}
virtual void on_write_complete(Pj_Async_Op*, pj_ssize_t)
{}
#if PJ_HAS_TCP
//
// On connect complete callback.
//
virtual void on_connect_complete(pj_status_t)
{
}
virtual void on_connect_complete(pj_status_t)
{}
//
// On new connection callback.
//
virtual void on_accept_complete( Pj_Async_Op*, pj_sock_t, pj_status_t)
{
}
virtual void on_accept_complete(Pj_Async_Op*, pj_sock_t, pj_status_t)
{}
#endif
private:
pj_ioqueue_key_t *key_;
pj_timer_entry timer_;
private:
pj_ioqueue_key_t* key_;
pj_timer_entry timer_;
friend class Pj_Proactor;
friend class Pj_Async_Op;
@ -253,11 +233,9 @@ private:
//
// Static timer callback.
//
static void timer_callback( pj_timer_heap_t*,
struct pj_timer_entry *entry)
static void timer_callback(pj_timer_heap_t*, struct pj_timer_entry* entry)
{
Pj_Event_Handler *handler =
(Pj_Event_Handler*) entry->user_data;
Pj_Event_Handler* handler = (Pj_Event_Handler*)entry->user_data;
handler->on_timeout(entry->id);
}
@ -270,38 +248,35 @@ inline bool Pj_Async_Op::is_pending()
inline bool Pj_Async_Op::cancel(pj_ssize_t bytes_status)
{
return pj_ioqueue_post_completion(handler_->key_, this,
bytes_status) == PJ_SUCCESS;
return pj_ioqueue_post_completion(handler_->key_, this, bytes_status) ==
PJ_SUCCESS;
}
//////////////////////////////////////////////////////////////////////////////
// Proactor
//
class Pj_Proactor : public Pj_Object
{
public:
class Pj_Proactor : public Pj_Object {
public:
//
// Default constructor, initializes to NULL.
//
Pj_Proactor()
: ioq_(NULL), th_(NULL)
Pj_Proactor() : ioq_(NULL), th_(NULL)
{
cb_.on_read_complete = &read_complete_cb;
cb_.on_write_complete = &write_complete_cb;
cb_.on_accept_complete = &accept_complete_cb;
cb_.on_read_complete = &read_complete_cb;
cb_.on_write_complete = &write_complete_cb;
cb_.on_accept_complete = &accept_complete_cb;
cb_.on_connect_complete = &connect_complete_cb;
}
//
// Construct proactor.
//
Pj_Proactor( Pj_Pool *pool, pj_size_t max_fd,
pj_size_t max_timer_entries )
: ioq_(NULL), th_(NULL)
Pj_Proactor(Pj_Pool* pool, pj_size_t max_fd, pj_size_t max_timer_entries)
: ioq_(NULL), th_(NULL)
{
cb_.on_read_complete = &read_complete_cb;
cb_.on_write_complete = &write_complete_cb;
cb_.on_accept_complete = &accept_complete_cb;
cb_.on_read_complete = &read_complete_cb;
cb_.on_write_complete = &write_complete_cb;
cb_.on_accept_complete = &accept_complete_cb;
cb_.on_connect_complete = &connect_complete_cb;
create(pool, max_fd, max_timer_entries);
@ -318,25 +293,24 @@ public:
//
// Create proactor.
//
pj_status_t create( Pj_Pool *pool, pj_size_t max_fd,
pj_size_t timer_entry_count)
pj_status_t create(Pj_Pool* pool, pj_size_t max_fd,
pj_size_t timer_entry_count)
{
pj_status_t status;
destroy();
status = pj_ioqueue_create(pool->pool_(), max_fd, &ioq_);
if (status != PJ_SUCCESS)
if (status != PJ_SUCCESS)
return status;
status = pj_timer_heap_create(pool->pool_(),
timer_entry_count, &th_);
status = pj_timer_heap_create(pool->pool_(), timer_entry_count, &th_);
if (status != PJ_SUCCESS) {
pj_ioqueue_destroy(ioq_);
ioq_ = NULL;
return NULL;
}
return status;
}
@ -359,21 +333,21 @@ public:
// Register handler.
// This will call handler->get_socket_handle()
//
pj_status_t register_socket_handler(Pj_Pool *pool,
Pj_Event_Handler *handler)
pj_status_t register_socket_handler(Pj_Pool* pool,
Pj_Event_Handler* handler)
{
return pj_ioqueue_register_sock( pool->pool_(), ioq_,
handler->get_socket_handle(),
handler, &cb_, &handler->key_ );
return pj_ioqueue_register_sock(pool->pool_(), ioq_,
handler->get_socket_handle(), handler,
&cb_, &handler->key_);
}
//
// Unregister handler.
//
static void unregister_handler(Pj_Event_Handler *handler)
static void unregister_handler(Pj_Event_Handler* handler)
{
if (handler->key_) {
pj_ioqueue_unregister( handler->key_ );
pj_ioqueue_unregister(handler->key_);
handler->key_ = NULL;
}
}
@ -381,9 +355,8 @@ public:
//
// Scheduler timer.
//
bool schedule_timer( Pj_Event_Handler *handler,
const Pj_Time_Val &delay,
int id=-1)
bool schedule_timer(Pj_Event_Handler* handler, const Pj_Time_Val& delay,
int id = -1)
{
return schedule_timer(th_, handler, delay, id);
}
@ -391,7 +364,7 @@ public:
//
// Cancel timer.
//
bool cancel_timer(Pj_Event_Handler *handler)
bool cancel_timer(Pj_Event_Handler* handler)
{
return pj_timer_heap_cancel(th_, &handler->timer_) == 1;
}
@ -399,21 +372,21 @@ public:
//
// Handle events.
//
int handle_events(Pj_Time_Val *max_timeout)
int handle_events(Pj_Time_Val* max_timeout)
{
Pj_Time_Val timeout(0, 0);
int timer_count;
timer_count = pj_timer_heap_poll( th_, &timeout );
timer_count = pj_timer_heap_poll(th_, &timeout);
if (timeout.get_sec() < 0)
if (timeout.get_sec() < 0)
timeout.sec = PJ_MAXINT32;
/* If caller specifies maximum time to wait, then compare the value
/* If caller specifies maximum time to wait, then compare the value
* with the timeout to wait from timer, and use the minimum value.
*/
if (max_timeout && timeout >= *max_timeout) {
timeout = *max_timeout;
timeout = *max_timeout;
}
/* Poll events in ioqueue. */
@ -421,7 +394,7 @@ public:
ioqueue_count = pj_ioqueue_poll(ioq_, &timeout);
if (ioqueue_count < 0)
return ioqueue_count;
return ioqueue_count;
return ioqueue_count + timer_count;
}
@ -429,7 +402,7 @@ public:
//
// Get the internal ioqueue object.
//
pj_ioqueue_t *get_io_queue()
pj_ioqueue_t* get_io_queue()
{
return ioq_;
}
@ -437,35 +410,33 @@ public:
//
// Get the internal timer heap object.
//
pj_timer_heap_t *get_timer_heap()
pj_timer_heap_t* get_timer_heap()
{
return th_;
}
private:
pj_ioqueue_t *ioq_;
pj_timer_heap_t *th_;
private:
pj_ioqueue_t* ioq_;
pj_timer_heap_t* th_;
pj_ioqueue_callback cb_;
static bool schedule_timer( pj_timer_heap_t *timer,
Pj_Event_Handler *handler,
const Pj_Time_Val &delay,
int id=-1)
static bool schedule_timer(pj_timer_heap_t* timer,
Pj_Event_Handler* handler,
const Pj_Time_Val& delay, int id = -1)
{
handler->timer_.id = id;
return pj_timer_heap_schedule(timer, &handler->timer_, &delay) == 0;
}
//
// Static read completion callback.
//
static void read_complete_cb( pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
pj_ssize_t bytes_read)
static void read_complete_cb(pj_ioqueue_key_t* key,
pj_ioqueue_op_key_t* op_key,
pj_ssize_t bytes_read)
{
Pj_Event_Handler *handler =
(Pj_Event_Handler*) pj_ioqueue_get_user_data(key);
Pj_Event_Handler* handler =
(Pj_Event_Handler*)pj_ioqueue_get_user_data(key);
handler->on_read_complete((Pj_Async_Op*)op_key, bytes_read);
}
@ -473,12 +444,12 @@ private:
//
// Static write completion callback.
//
static void write_complete_cb(pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
static void write_complete_cb(pj_ioqueue_key_t* key,
pj_ioqueue_op_key_t* op_key,
pj_ssize_t bytes_sent)
{
Pj_Event_Handler *handler =
(Pj_Event_Handler*) pj_ioqueue_get_user_data(key);
Pj_Event_Handler* handler =
(Pj_Event_Handler*)pj_ioqueue_get_user_data(key);
handler->on_write_complete((Pj_Async_Op*)op_key, bytes_sent);
}
@ -486,13 +457,12 @@ private:
//
// Static accept completion callback.
//
static void accept_complete_cb(pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
pj_sock_t new_sock,
pj_status_t status)
static void accept_complete_cb(pj_ioqueue_key_t* key,
pj_ioqueue_op_key_t* op_key,
pj_sock_t new_sock, pj_status_t status)
{
Pj_Event_Handler *handler =
(Pj_Event_Handler*) pj_ioqueue_get_user_data(key);
Pj_Event_Handler* handler =
(Pj_Event_Handler*)pj_ioqueue_get_user_data(key);
handler->on_accept_complete((Pj_Async_Op*)op_key, new_sock, status);
}
@ -500,16 +470,13 @@ private:
//
// Static connect completion callback.
//
static void connect_complete_cb(pj_ioqueue_key_t *key,
pj_status_t status)
static void connect_complete_cb(pj_ioqueue_key_t* key, pj_status_t status)
{
Pj_Event_Handler *handler =
(Pj_Event_Handler*) pj_ioqueue_get_user_data(key);
Pj_Event_Handler* handler =
(Pj_Event_Handler*)pj_ioqueue_get_user_data(key);
handler->on_connect_complete(status);
}
};
#endif /* __PJPP_PROACTOR_HPP__ */
#endif /* __PJPP_PROACTOR_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_SCANNER_HPP__
#define __PJPP_SCANNER_HPP__
@ -27,220 +26,213 @@ class Pj_Cis;
class Pj_Cis_Buffer;
class Pj_Scanner;
class Pj_Cis_Buffer
{
class Pj_Cis_Buffer {
friend class Pj_Cis;
public:
Pj_Cis_Buffer()
{
pj_cis_buf_init(&buf_);
public:
Pj_Cis_Buffer()
{
pj_cis_buf_init(&buf_);
}
private:
private:
pj_cis_buf_t buf_;
};
class Pj_Cis
{
class Pj_Cis {
friend class Pj_Scanner;
public:
Pj_Cis(Pj_Cis_Buffer *buf)
public:
Pj_Cis(Pj_Cis_Buffer* buf)
{
pj_cis_init(&buf->buf_, &cis_);
pj_cis_init(&buf->buf_, &cis_);
}
Pj_Cis(const Pj_Cis &rhs)
Pj_Cis(const Pj_Cis& rhs)
{
pj_cis_dup(&cis_, (pj_cis_t*)&rhs.cis_);
pj_cis_dup(&cis_, (pj_cis_t*)&rhs.cis_);
}
void add_range(int start, int end)
{
pj_cis_add_range(&cis_, start, end);
pj_cis_add_range(&cis_, start, end);
}
void add_alpha()
{
pj_cis_add_alpha(&cis_);
pj_cis_add_alpha(&cis_);
}
void add_num()
{
pj_cis_add_num(&cis_);
pj_cis_add_num(&cis_);
}
void add_str(const char *str)
void add_str(const char* str)
{
pj_cis_add_str(&cis_, str);
pj_cis_add_str(&cis_, str);
}
void add_cis(const Pj_Cis &rhs)
void add_cis(const Pj_Cis& rhs)
{
pj_cis_add_cis(&cis_, &rhs.cis_);
pj_cis_add_cis(&cis_, &rhs.cis_);
}
void del_range(int start, int end)
{
pj_cis_del_range(&cis_, start, end);
pj_cis_del_range(&cis_, start, end);
}
void del_str(const char *str)
void del_str(const char* str)
{
pj_cis_del_str(&cis_, str);
pj_cis_del_str(&cis_, str);
}
void invert()
{
pj_cis_invert(&cis_);
pj_cis_invert(&cis_);
}
bool match(int c) const
{
return pj_cis_match(&cis_, c) != 0;
return pj_cis_match(&cis_, c) != 0;
}
private:
private:
pj_cis_t cis_;
};
class Pj_Scanner
{
public:
Pj_Scanner() {}
class Pj_Scanner {
public:
Pj_Scanner()
{}
enum
{
SYNTAX_ERROR = 101
SYNTAX_ERROR = 101
};
static void syntax_error_handler_throw_pj(pj_scanner *);
static void syntax_error_handler_throw_pj(pj_scanner*);
typedef pj_scan_state State;
void init(char *buf, int len, unsigned options=PJ_SCAN_AUTOSKIP_WS,
pj_syn_err_func_ptr callback = &syntax_error_handler_throw_pj)
void init(char* buf, int len, unsigned options = PJ_SCAN_AUTOSKIP_WS,
pj_syn_err_func_ptr callback = &syntax_error_handler_throw_pj)
{
pj_scan_init(&scanner_, buf, len, options, callback);
pj_scan_init(&scanner_, buf, len, options, callback);
}
void fini()
{
pj_scan_fini(&scanner_);
pj_scan_fini(&scanner_);
}
int eof() const
{
return pj_scan_is_eof(&scanner_);
return pj_scan_is_eof(&scanner_);
}
int peek_char() const
{
return *scanner_.curptr;
return *scanner_.curptr;
}
int peek(const Pj_Cis *cis, Pj_String *out)
int peek(const Pj_Cis* cis, Pj_String* out)
{
return pj_scan_peek(&scanner_, &cis->cis_, out);
return pj_scan_peek(&scanner_, &cis->cis_, out);
}
int peek_n(pj_size_t len, Pj_String *out)
int peek_n(pj_size_t len, Pj_String* out)
{
return pj_scan_peek_n(&scanner_, len, out);
return pj_scan_peek_n(&scanner_, len, out);
}
int peek_until(const Pj_Cis *cis, Pj_String *out)
int peek_until(const Pj_Cis* cis, Pj_String* out)
{
return pj_scan_peek_until(&scanner_, &cis->cis_, out);
return pj_scan_peek_until(&scanner_, &cis->cis_, out);
}
void get(const Pj_Cis *cis, Pj_String *out)
void get(const Pj_Cis* cis, Pj_String* out)
{
pj_scan_get(&scanner_, &cis->cis_, out);
pj_scan_get(&scanner_, &cis->cis_, out);
}
void get_n(unsigned N, Pj_String *out)
void get_n(unsigned N, Pj_String* out)
{
pj_scan_get_n(&scanner_, N, out);
pj_scan_get_n(&scanner_, N, out);
}
int get_char()
{
return pj_scan_get_char(&scanner_);
return pj_scan_get_char(&scanner_);
}
void get_quote(int begin_quote, int end_quote, Pj_String *out)
void get_quote(int begin_quote, int end_quote, Pj_String* out)
{
pj_scan_get_quote(&scanner_, begin_quote, end_quote, out);
pj_scan_get_quote(&scanner_, begin_quote, end_quote, out);
}
void get_newline()
{
pj_scan_get_newline(&scanner_);
pj_scan_get_newline(&scanner_);
}
void get_until(const Pj_Cis *cis, Pj_String *out)
void get_until(const Pj_Cis* cis, Pj_String* out)
{
pj_scan_get_until(&scanner_, &cis->cis_, out);
pj_scan_get_until(&scanner_, &cis->cis_, out);
}
void get_until_ch(int until_ch, Pj_String *out)
void get_until_ch(int until_ch, Pj_String* out)
{
pj_scan_get_until_ch(&scanner_, until_ch, out);
pj_scan_get_until_ch(&scanner_, until_ch, out);
}
void get_until_chr(const char *spec, Pj_String *out)
void get_until_chr(const char* spec, Pj_String* out)
{
pj_scan_get_until_chr(&scanner_, spec, out);
pj_scan_get_until_chr(&scanner_, spec, out);
}
void advance_n(unsigned N, bool skip_ws=true)
void advance_n(unsigned N, bool skip_ws = true)
{
pj_scan_advance_n(&scanner_, N, skip_ws);
pj_scan_advance_n(&scanner_, N, skip_ws);
}
int strcmp(const char *s, int len)
int strcmp(const char* s, int len)
{
return pj_scan_strcmp(&scanner_, s, len);
return pj_scan_strcmp(&scanner_, s, len);
}
int stricmp(const char *s, int len)
int stricmp(const char* s, int len)
{
return pj_scan_stricmp(&scanner_, s, len);
return pj_scan_stricmp(&scanner_, s, len);
}
void skip_ws()
{
pj_scan_skip_whitespace(&scanner_);
pj_scan_skip_whitespace(&scanner_);
}
void save_state(State *state) const
void save_state(State* state) const
{
pj_scan_save_state(&scanner_, state);
pj_scan_save_state(&scanner_, state);
}
void restore_state(State *state)
void restore_state(State* state)
{
pj_scan_restore_state(&scanner_, state);
pj_scan_restore_state(&scanner_, state);
}
int get_pos_line() const
{
return scanner_.line;
return scanner_.line;
}
int get_pos_col() const
{
return pj_scan_get_col(&scanner_);
return pj_scan_get_col(&scanner_);
}
private:
private:
pj_scanner scanner_;
};
#endif /* __PJPP_SCANNER_HPP__ */
#endif /* __PJPP_SCANNER_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_SOCK_HPP__
#define __PJPP_SOCK_HPP__
@ -28,22 +27,19 @@ class Pj_Event_Handler;
//
// Base class for address.
//
class Pj_Addr
{
};
class Pj_Addr {};
//
// Internet address.
//
class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr
{
public:
class Pj_Inet_Addr : public pj_sockaddr_in, public Pj_Addr {
public:
//
// Get port number.
//
pj_uint16_t get_port_number() const
{
return pj_sockaddr_in_get_port(this);
return pj_sockaddr_in_get_port(this);
}
//
@ -51,8 +47,8 @@ public:
//
void set_port_number(pj_uint16_t port)
{
sin_family = PJ_AF_INET;
pj_sockaddr_in_set_port(this, port);
sin_family = PJ_AF_INET;
pj_sockaddr_in_set_port(this, port);
}
//
@ -60,15 +56,15 @@ public:
//
pj_uint32_t get_ip_address() const
{
return pj_sockaddr_in_get_addr(this).s_addr;
return pj_sockaddr_in_get_addr(this).s_addr;
}
//
// Get address string.
//
const char *get_address() const
const char* get_address() const
{
return pj_inet_ntoa(sin_addr);
return pj_inet_ntoa(sin_addr);
}
//
@ -76,38 +72,38 @@ public:
//
void set_ip_address(pj_uint32_t addr)
{
sin_family = PJ_AF_INET;
pj_sockaddr_in_set_addr(this, addr);
sin_family = PJ_AF_INET;
pj_sockaddr_in_set_addr(this, addr);
}
//
// Set address.
//
pj_status_t set_address(const pj_str_t *addr)
pj_status_t set_address(const pj_str_t* addr)
{
return pj_sockaddr_in_set_str_addr(this, addr);
return pj_sockaddr_in_set_str_addr(this, addr);
}
//
// Set address.
//
pj_status_t set_address(const char *addr)
pj_status_t set_address(const char* addr)
{
pj_str_t s;
return pj_sockaddr_in_set_str_addr(this, pj_cstr(&s, addr));
return pj_sockaddr_in_set_str_addr(this, pj_cstr(&s, addr));
}
//
// Compare for equality.
//
bool operator==(const Pj_Inet_Addr &rhs) const
bool operator==(const Pj_Inet_Addr& rhs) const
{
return sin_family == rhs.sin_family &&
return sin_family == rhs.sin_family &&
sin_addr.s_addr == rhs.sin_addr.s_addr &&
sin_port == rhs.sin_port;
}
private:
private:
//
// Dummy length used in pj_ioqueue_recvfrom() etc
//
@ -119,54 +115,45 @@ private:
int addrlen_;
};
//
// Socket base class.
//
// Note:
// socket will not automatically be closed on destructor.
//
class Pj_Socket
{
public:
class Pj_Socket {
public:
//
// Default constructor.
//
Pj_Socket()
: sock_(PJ_INVALID_SOCKET)
{
}
Pj_Socket() : sock_(PJ_INVALID_SOCKET)
{}
//
// Initialize from a socket handle.
//
explicit Pj_Socket(pj_sock_t sock)
: sock_(sock)
{
}
explicit Pj_Socket(pj_sock_t sock) : sock_(sock)
{}
//
// Copy constructor.
//
Pj_Socket(const Pj_Socket &rhs)
: sock_(rhs.sock_)
{
}
Pj_Socket(const Pj_Socket& rhs) : sock_(rhs.sock_)
{}
//
// Destructor will not close the socket.
// You must call close() explicitly.
//
~Pj_Socket()
{
}
{}
//
// Set socket handle.
//
void set_handle(pj_sock_t sock)
{
sock_ = sock;
sock_ = sock;
}
//
@ -174,7 +161,7 @@ public:
//
pj_sock_t get_handle() const
{
return sock_;
return sock_;
}
//
@ -182,7 +169,7 @@ public:
//
pj_sock_t& get_handle()
{
return sock_;
return sock_;
}
//
@ -198,15 +185,15 @@ public:
//
pj_status_t create(int af, int type, int proto)
{
return pj_sock_socket(af, type, proto, &sock_);
return pj_sock_socket(af, type, proto, &sock_);
}
//
// Bind socket.
//
pj_status_t bind(const Pj_Inet_Addr &addr)
pj_status_t bind(const Pj_Inet_Addr& addr)
{
return pj_sock_bind(sock_, &addr, sizeof(Pj_Inet_Addr));
return pj_sock_bind(sock_, &addr, sizeof(Pj_Inet_Addr));
}
//
@ -214,50 +201,50 @@ public:
//
pj_status_t close()
{
pj_sock_close(sock_);
pj_sock_close(sock_);
}
//
// Get peer socket name.
//
pj_status_t getpeername(Pj_Inet_Addr *addr)
pj_status_t getpeername(Pj_Inet_Addr* addr)
{
return pj_sock_getpeername(sock_, addr, &addr->addrlen_);
return pj_sock_getpeername(sock_, addr, &addr->addrlen_);
}
//
// getsockname
//
pj_status_t getsockname(Pj_Inet_Addr *addr)
pj_status_t getsockname(Pj_Inet_Addr* addr)
{
return pj_sock_getsockname(sock_, addr, &addr->addrlen_);
return pj_sock_getsockname(sock_, addr, &addr->addrlen_);
}
//
// getsockopt.
//
pj_status_t getsockopt(pj_uint16_t level, pj_uint16_t optname,
void *optval, int *optlen)
pj_status_t getsockopt(pj_uint16_t level, pj_uint16_t optname, void* optval,
int* optlen)
{
return pj_sock_getsockopt(sock_, level, optname, optval, optlen);
return pj_sock_getsockopt(sock_, level, optname, optval, optlen);
}
//
// setsockopt
//
pj_status_t setsockopt(pj_uint16_t level, pj_uint16_t optname,
const void *optval, int optlen)
//
pj_status_t setsockopt(pj_uint16_t level, pj_uint16_t optname,
const void* optval, int optlen)
{
return pj_sock_setsockopt(sock_, level, optname, optval, optlen);
return pj_sock_setsockopt(sock_, level, optname, optval, optlen);
}
//
// receive data.
//
pj_ssize_t recv(void *buf, pj_size_t len, int flag = 0)
pj_ssize_t recv(void* buf, pj_size_t len, int flag = 0)
{
pj_ssize_t bytes = len;
if (pj_sock_recv(sock_, buf, &bytes, flag) != PJ_SUCCESS)
if (pj_sock_recv(sock_, buf, &bytes, flag) != PJ_SUCCESS)
return -1;
return bytes;
}
@ -265,10 +252,10 @@ public:
//
// send data.
//
pj_ssize_t send(const void *buf, pj_ssize_t len, int flag = 0)
pj_ssize_t send(const void* buf, pj_ssize_t len, int flag = 0)
{
pj_ssize_t bytes = len;
if (pj_sock_send(sock_, buf, &bytes, flag) != PJ_SUCCESS)
if (pj_sock_send(sock_, buf, &bytes, flag) != PJ_SUCCESS)
return -1;
return bytes;
}
@ -276,62 +263,56 @@ public:
//
// connect.
//
pj_status_t connect(const Pj_Inet_Addr &addr)
pj_status_t connect(const Pj_Inet_Addr& addr)
{
return pj_sock_connect(sock_, &addr, sizeof(Pj_Inet_Addr));
return pj_sock_connect(sock_, &addr, sizeof(Pj_Inet_Addr));
}
//
// assignment.
//
Pj_Socket &operator=(const Pj_Socket &rhs)
Pj_Socket& operator=(const Pj_Socket& rhs)
{
sock_ = rhs.sock_;
return *this;
}
protected:
protected:
friend class Pj_Event_Handler;
pj_sock_t sock_;
};
#if PJ_HAS_TCP
//
// Stream socket.
//
class Pj_Sock_Stream : public Pj_Socket
{
public:
class Pj_Sock_Stream : public Pj_Socket {
public:
//
// Default constructor.
//
Pj_Sock_Stream()
{
}
Pj_Sock_Stream()
{}
//
// Initialize from a socket handle.
//
explicit Pj_Sock_Stream(pj_sock_t sock)
: Pj_Socket(sock)
{
}
explicit Pj_Sock_Stream(pj_sock_t sock) : Pj_Socket(sock)
{}
//
// Copy constructor.
//
Pj_Sock_Stream(const Pj_Sock_Stream &rhs) : Pj_Socket(rhs)
{
}
Pj_Sock_Stream(const Pj_Sock_Stream& rhs) : Pj_Socket(rhs)
{}
//
// Assignment.
//
Pj_Sock_Stream &operator=(const Pj_Sock_Stream &rhs)
{
sock_ = rhs.sock_;
return *this;
Pj_Sock_Stream& operator=(const Pj_Sock_Stream& rhs)
{
sock_ = rhs.sock_;
return *this;
}
//
@ -339,18 +320,18 @@ public:
//
pj_status_t listen(int backlog = 5)
{
return pj_sock_listen(sock_, backlog);
return pj_sock_listen(sock_, backlog);
}
//
// blocking accept()
//
Pj_Sock_Stream accept(Pj_Inet_Addr *remote_addr = NULL)
Pj_Sock_Stream accept(Pj_Inet_Addr* remote_addr = NULL)
{
pj_sock_t newsock;
int *addrlen = remote_addr ? &remote_addr->addrlen_ : NULL;
int* addrlen = remote_addr ? &remote_addr->addrlen_ : NULL;
pj_status_t status;
status = pj_sock_accept(sock_, &newsock, remote_addr, addrlen);
if (status != PJ_SUCCESS)
return Pj_Sock_Stream(-1);
@ -363,61 +344,53 @@ public:
//
pj_status_t shutdown(int how = PJ_SHUT_RDWR)
{
return pj_sock_shutdown(sock_, how);
return pj_sock_shutdown(sock_, how);
}
};
#endif
//
// Datagram socket.
//
class Pj_Sock_Dgram : public Pj_Socket
{
public:
class Pj_Sock_Dgram : public Pj_Socket {
public:
//
// Default constructor.
//
Pj_Sock_Dgram()
{
}
Pj_Sock_Dgram()
{}
//
// Initialize from a socket handle.
//
explicit Pj_Sock_Dgram(pj_sock_t sock)
: Pj_Socket(sock)
{
}
explicit Pj_Sock_Dgram(pj_sock_t sock) : Pj_Socket(sock)
{}
//
// Copy constructor.
//
Pj_Sock_Dgram(const Pj_Sock_Dgram &rhs)
: Pj_Socket(rhs)
{
}
Pj_Sock_Dgram(const Pj_Sock_Dgram& rhs) : Pj_Socket(rhs)
{}
//
// Assignment.
//
Pj_Sock_Dgram &operator=(const Pj_Sock_Dgram &rhs)
{
Pj_Socket::operator =(rhs);
return *this;
Pj_Sock_Dgram& operator=(const Pj_Sock_Dgram& rhs)
{
Pj_Socket::operator=(rhs);
return *this;
}
//
// recvfrom()
//
pj_ssize_t recvfrom( void *buf, pj_size_t len, int flag = 0,
Pj_Inet_Addr *fromaddr = NULL)
pj_ssize_t recvfrom(void* buf, pj_size_t len, int flag = 0,
Pj_Inet_Addr* fromaddr = NULL)
{
pj_ssize_t bytes = len;
int *addrlen = fromaddr ? &fromaddr->addrlen_ : NULL;
if (pj_sock_recvfrom( sock_, buf, &bytes, flag,
fromaddr, addrlen) != PJ_SUCCESS)
{
int* addrlen = fromaddr ? &fromaddr->addrlen_ : NULL;
if (pj_sock_recvfrom(sock_, buf, &bytes, flag, fromaddr, addrlen) !=
PJ_SUCCESS) {
return -1;
}
return bytes;
@ -426,12 +399,12 @@ public:
//
// sendto()
//
pj_ssize_t sendto( const void *buf, pj_size_t len, int flag,
const Pj_Inet_Addr &addr)
pj_ssize_t sendto(const void* buf, pj_size_t len, int flag,
const Pj_Inet_Addr& addr)
{
pj_ssize_t bytes = len;
if (pj_sock_sendto( sock_, buf, &bytes, flag,
&addr, sizeof(pj_sockaddr_in)) != PJ_SUCCESS)
if (pj_sock_sendto(sock_, buf, &bytes, flag, &addr,
sizeof(pj_sockaddr_in)) != PJ_SUCCESS)
{
return -1;
}
@ -439,6 +412,4 @@ public:
}
};
#endif /* __PJPP_SOCK_HPP__ */
#endif /* __PJPP_SOCK_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_STRING_HPP__
#define __PJPP_STRING_HPP__
@ -27,92 +26,91 @@
//
// String wrapper class for pj_str_t.
//
class Pj_String : public pj_str_t
{
public:
class Pj_String : public pj_str_t {
public:
//
// Default constructor.
//
Pj_String()
{
pj_assert(sizeof(Pj_String) == sizeof(pj_str_t));
ptr=NULL;
slen=0;
Pj_String()
{
pj_assert(sizeof(Pj_String) == sizeof(pj_str_t));
ptr = NULL;
slen = 0;
}
//
// Construct the buffer from a char* (use with care)
//
Pj_String(char *str)
{
set(str);
Pj_String(char* str)
{
set(str);
}
//
// Construct from a const char*.
//
Pj_String(Pj_Pool &pool, const char *src)
Pj_String(Pj_Pool& pool, const char* src)
{
set(pool, src);
set(pool, src);
}
//
// Construct from pj_str_t&.
//
explicit Pj_String(pj_str_t &s)
explicit Pj_String(pj_str_t& s)
{
ptr = s.ptr;
slen = s.slen;
ptr = s.ptr;
slen = s.slen;
}
//
// Construct from const pj_str_t& (use with care!).
//
explicit Pj_String(const pj_str_t &s)
explicit Pj_String(const pj_str_t& s)
{
ptr = (char*)s.ptr;
slen = s.slen;
ptr = (char*)s.ptr;
slen = s.slen;
}
//
// Construct by copying from const pj_str_t*.
//
Pj_String(Pj_Pool &pool, const pj_str_t *s)
Pj_String(Pj_Pool& pool, const pj_str_t* s)
{
set(pool, s);
set(pool, s);
}
//
// Construct by copying from Pj_String
//
Pj_String(Pj_Pool &pool, const Pj_String &rhs)
Pj_String(Pj_Pool& pool, const Pj_String& rhs)
{
set(pool, rhs);
set(pool, rhs);
}
//
// Construct from another Pj_String, use with care!
//
explicit Pj_String(const Pj_String &rhs)
explicit Pj_String(const Pj_String& rhs)
{
ptr = rhs.ptr;
slen = rhs.slen;
ptr = rhs.ptr;
slen = rhs.slen;
}
//
// Construct from a char* and a length.
//
Pj_String(char *str, pj_size_t len)
Pj_String(char* str, pj_size_t len)
{
set(str, len);
set(str, len);
}
//
// Construct from pair of pointer.
//
Pj_String(char *begin, char *end)
Pj_String(char* begin, char* end)
{
pj_strset3(this, begin, end);
pj_strset3(this, begin, end);
}
//
@ -120,7 +118,7 @@ public:
//
operator pj_str_t*()
{
return this;
return this;
}
//
@ -128,7 +126,7 @@ public:
//
operator const pj_str_t*() const
{
return this;
return this;
}
//
@ -136,7 +134,7 @@ public:
//
pj_size_t length() const
{
return pj_strlen(this);
return pj_strlen(this);
}
//
@ -144,274 +142,274 @@ public:
//
pj_size_t size() const
{
return length();
return length();
}
//
// Get the string buffer.
//
const char *buf() const
const char* buf() const
{
return ptr;
return ptr;
}
//
// Initialize buffer from char*.
//
void set(char *str)
void set(char* str)
{
pj_strset2(this, str);
pj_strset2(this, str);
}
//
// Initialize by copying from a const char*.
//
void set(Pj_Pool &pool, const char *s)
void set(Pj_Pool& pool, const char* s)
{
pj_strdup2(pool, this, s);
pj_strdup2(pool, this, s);
}
//
// Initialize from pj_str_t*.
//
void set(pj_str_t *s)
void set(pj_str_t* s)
{
pj_strassign(this, s);
pj_strassign(this, s);
}
//
// Initialize by copying from const pj_str_t*.
//
void set(Pj_Pool &pool, const pj_str_t *s)
void set(Pj_Pool& pool, const pj_str_t* s)
{
pj_strdup(pool, this, s);
pj_strdup(pool, this, s);
}
//
// Initialize from char* and length.
//
void set(char *str, pj_size_t len)
void set(char* str, pj_size_t len)
{
pj_strset(this, str, len);
pj_strset(this, str, len);
}
//
// Initialize from pair of pointers.
//
void set(char *begin, char *end)
void set(char* begin, char* end)
{
pj_strset3(this, begin, end);
pj_strset3(this, begin, end);
}
//
// Initialize from other Pj_String.
//
void set(Pj_String &rhs)
void set(Pj_String& rhs)
{
pj_strassign(this, &rhs);
pj_strassign(this, &rhs);
}
//
// Initialize by copying from a Pj_String*.
//
void set(Pj_Pool &pool, const Pj_String *s)
void set(Pj_Pool& pool, const Pj_String* s)
{
pj_strdup(pool, this, s);
pj_strdup(pool, this, s);
}
//
// Initialize by copying from other Pj_String.
//
void set(Pj_Pool &pool, const Pj_String &s)
void set(Pj_Pool& pool, const Pj_String& s)
{
pj_strdup(pool, this, &s);
pj_strdup(pool, this, &s);
}
//
// Copy the contents of other string.
//
void strcpy(const pj_str_t *s)
void strcpy(const pj_str_t* s)
{
pj_strcpy(this, s);
pj_strcpy(this, s);
}
//
// Copy the contents of other string.
//
void strcpy(const Pj_String &rhs)
void strcpy(const Pj_String& rhs)
{
pj_strcpy(this, &rhs);
pj_strcpy(this, &rhs);
}
//
// Copy the contents of other string.
//
void strcpy(const char *s)
void strcpy(const char* s)
{
pj_strcpy2(this, s);
pj_strcpy2(this, s);
}
//
// Compare string.
//
int strcmp(const char *s) const
int strcmp(const char* s) const
{
return pj_strcmp2(this, s);
return pj_strcmp2(this, s);
}
//
// Compare string.
//
int strcmp(const pj_str_t *s) const
int strcmp(const pj_str_t* s) const
{
return pj_strcmp(this, s);
return pj_strcmp(this, s);
}
//
// Compare string.
//
int strcmp(const Pj_String &rhs) const
int strcmp(const Pj_String& rhs) const
{
return pj_strcmp(this, &rhs);
return pj_strcmp(this, &rhs);
}
//
// Compare string.
//
int strncmp(const char *s, pj_size_t len) const
int strncmp(const char* s, pj_size_t len) const
{
return pj_strncmp2(this, s, len);
return pj_strncmp2(this, s, len);
}
//
// Compare string.
//
int strncmp(const pj_str_t *s, pj_size_t len) const
int strncmp(const pj_str_t* s, pj_size_t len) const
{
return pj_strncmp(this, s, len);
return pj_strncmp(this, s, len);
}
//
// Compare string.
//
int strncmp(const Pj_String &rhs, pj_size_t len) const
int strncmp(const Pj_String& rhs, pj_size_t len) const
{
return pj_strncmp(this, &rhs, len);
return pj_strncmp(this, &rhs, len);
}
//
// Compare string.
//
int stricmp(const char *s) const
int stricmp(const char* s) const
{
return pj_stricmp2(this, s);
return pj_stricmp2(this, s);
}
//
// Compare string.
//
int stricmp(const pj_str_t *s) const
int stricmp(const pj_str_t* s) const
{
return pj_stricmp(this, s);
return pj_stricmp(this, s);
}
//
// Compare string.
//
int stricmp(const Pj_String &rhs) const
int stricmp(const Pj_String& rhs) const
{
return stricmp(&rhs);
return stricmp(&rhs);
}
//
// Compare string.
//
int strnicmp(const char *s, pj_size_t len) const
int strnicmp(const char* s, pj_size_t len) const
{
return pj_strnicmp2(this, s, len);
return pj_strnicmp2(this, s, len);
}
//
// Compare string.
//
int strnicmp(const pj_str_t *s, pj_size_t len) const
int strnicmp(const pj_str_t* s, pj_size_t len) const
{
return pj_strnicmp(this, s, len);
return pj_strnicmp(this, s, len);
}
//
// Compare string.
//
int strnicmp(const Pj_String &rhs, pj_size_t len) const
int strnicmp(const Pj_String& rhs, pj_size_t len) const
{
return strnicmp(&rhs, len);
return strnicmp(&rhs, len);
}
//
// Compare contents for equality.
//
bool operator==(const char *s) const
bool operator==(const char* s) const
{
return strcmp(s) == 0;
return strcmp(s) == 0;
}
//
// Compare contents for equality.
//
bool operator==(const pj_str_t *s) const
bool operator==(const pj_str_t* s) const
{
return strcmp(s) == 0;
return strcmp(s) == 0;
}
//
// Compare contents for equality.
//
bool operator==(const Pj_String &rhs) const
bool operator==(const Pj_String& rhs) const
{
return pj_strcmp(this, &rhs) == 0;
return pj_strcmp(this, &rhs) == 0;
}
//
// Assign from char*
//
Pj_String& operator=(char *s)
Pj_String& operator=(char* s)
{
set(s);
return *this;
set(s);
return *this;
}
///
// Assign from another Pj_String, use with care!
//
Pj_String& operator=(const Pj_String &rhs)
Pj_String& operator=(const Pj_String& rhs)
{
ptr = rhs.ptr;
slen = rhs.slen;
return *this;
ptr = rhs.ptr;
slen = rhs.slen;
return *this;
}
//
// Find a character in the string.
//
char *strchr(int chr)
char* strchr(int chr)
{
return pj_strchr(this, chr);
return pj_strchr(this, chr);
}
//
// Find a character in the string.
//
char *find(int chr)
char* find(int chr)
{
return strchr(chr);
return strchr(chr);
}
//
// Concatenate string.
//
void strcat(const Pj_String &rhs)
void strcat(const Pj_String& rhs)
{
pj_strcat(this, &rhs);
pj_strcat(this, &rhs);
}
//
@ -419,7 +417,7 @@ public:
//
void ltrim()
{
pj_strltrim(this);
pj_strltrim(this);
}
//
@ -427,7 +425,7 @@ public:
//
void rtrim()
{
pj_strrtrim(this);
pj_strrtrim(this);
}
//
@ -435,7 +433,7 @@ public:
//
void trim()
{
pj_strtrim(this);
pj_strtrim(this);
}
//
@ -443,7 +441,7 @@ public:
//
unsigned long to_ulong() const
{
return pj_strtoul(this);
return pj_strtoul(this);
}
//
@ -457,12 +455,11 @@ public:
//
// Convert from unsigned long with padding.
//
void from_ulong_with_pad(unsigned long value, int min_dig=0, int pad=' ')
void from_ulong_with_pad(unsigned long value, int min_dig = 0,
int pad = ' ')
{
slen = pj_utoa_pad(value, ptr, min_dig, pad);
}
};
#endif /* __PJPP_STRING_HPP__ */
#endif /* __PJPP_STRING_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_TIMER_HPP__
#define __PJPP_TIMER_HPP__
@ -34,62 +33,55 @@ class Pj_Timer_Heap;
// Derive class from Pj_Timer_Entry and override on_timeout().
// Scheduler timer in Pj_Timer_Heap.
//
class Pj_Timer_Entry : public Pj_Object
{
class Pj_Timer_Entry : public Pj_Object {
friend class Pj_Timer_Heap;
public:
public:
//
// Default constructor.
//
Pj_Timer_Entry()
{
Pj_Timer_Entry()
{
entry_.user_data = this;
entry_.cb = &timer_heap_callback;
entry_.cb = &timer_heap_callback;
}
//
// Destructor, do nothing.
//
~Pj_Timer_Entry()
{
}
{}
//
// Override this to get the timeout notification.
//
virtual void on_timeout(int id) = 0;
private:
private:
pj_timer_entry entry_;
static void timer_heap_callback(pj_timer_heap_t*, pj_timer_entry *e)
static void timer_heap_callback(pj_timer_heap_t*, pj_timer_entry* e)
{
Pj_Timer_Entry *entry = (Pj_Timer_Entry*) e->user_data;
Pj_Timer_Entry* entry = (Pj_Timer_Entry*)e->user_data;
entry->on_timeout(e->id);
}
};
//////////////////////////////////////////////////////////////////////////////
// Timer heap.
//
class Pj_Timer_Heap : public Pj_Object
{
public:
class Pj_Timer_Heap : public Pj_Object {
public:
//
// Default constructor.
//
Pj_Timer_Heap()
: ht_(NULL)
{
}
Pj_Timer_Heap() : ht_(NULL)
{}
//
// Construct timer heap.
//
Pj_Timer_Heap(Pj_Pool *pool, pj_size_t initial_count)
: ht_(NULL)
Pj_Timer_Heap(Pj_Pool* pool, pj_size_t initial_count) : ht_(NULL)
{
create(pool, initial_count);
}
@ -104,11 +96,11 @@ public:
//
// Create
//
pj_status_t create(Pj_Pool *pool, pj_size_t initial_count)
//
pj_status_t create(Pj_Pool* pool, pj_size_t initial_count)
{
destroy();
return pj_timer_heap_create(pool->pool_(), initial_count, &ht_);
return pj_timer_heap_create(pool->pool_(), initial_count, &ht_);
}
//
@ -125,17 +117,17 @@ public:
//
// Get pjlib compatible timer heap object.
//
pj_timer_heap_t *get_timer_heap()
pj_timer_heap_t* get_timer_heap()
{
return ht_;
return ht_;
}
//
// Set the lock object.
//
void set_lock( Pj_Lock *lock, bool auto_delete )
void set_lock(Pj_Lock* lock, bool auto_delete)
{
pj_timer_heap_set_lock( ht_, lock->pj_lock_t_(), auto_delete);
pj_timer_heap_set_lock(ht_, lock->pj_lock_t_(), auto_delete);
}
//
@ -149,19 +141,18 @@ public:
//
// Schedule a timer.
//
bool schedule( Pj_Timer_Entry *ent, const Pj_Time_Val &delay,
int id)
bool schedule(Pj_Timer_Entry* ent, const Pj_Time_Val& delay, int id)
{
ent->entry_.id = id;
return pj_timer_heap_schedule(ht_, &ent->entry_, &delay) == 0;
return pj_timer_heap_schedule(ht_, &ent->entry_, &delay) == 0;
}
//
// Cancel a timer.
//
bool cancel(Pj_Timer_Entry *ent)
bool cancel(Pj_Timer_Entry* ent)
{
return pj_timer_heap_cancel(ht_, &ent->entry_) == 1;
return pj_timer_heap_cancel(ht_, &ent->entry_) == 1;
}
//
@ -169,30 +160,29 @@ public:
//
pj_size_t count()
{
return pj_timer_heap_count(ht_);
return pj_timer_heap_count(ht_);
}
//
// Get the earliest time.
// Return false if no timer is found.
//
bool earliest_time(Pj_Time_Val *t)
bool earliest_time(Pj_Time_Val* t)
{
return pj_timer_heap_earliest_time(ht_, t) == PJ_SUCCESS;
return pj_timer_heap_earliest_time(ht_, t) == PJ_SUCCESS;
}
//
// Poll the timer.
// Return number of timed out entries has been called.
//
unsigned poll(Pj_Time_Val *next_delay = NULL)
unsigned poll(Pj_Time_Val* next_delay = NULL)
{
return pj_timer_heap_poll(ht_, next_delay);
return pj_timer_heap_poll(ht_, next_delay);
}
private:
pj_timer_heap_t *ht_;
private:
pj_timer_heap_t* ht_;
};
#endif /* __PJPP_TIMER_HPP__ */
#endif /* __PJPP_TIMER_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_TREE_HPP__
#define __PJPP_TREE_HPP__
@ -25,105 +24,153 @@
//
// Tree.
//
class PJ_Tree
{
public:
class PJ_Tree {
public:
typedef pj_rbtree_comp Comp;
class iterator;
class reverse_iterator;
class Node : private pj_rbtree_node
{
friend class PJ_Tree;
friend class iterator;
friend class reverse_iterator;
class Node : private pj_rbtree_node {
friend class PJ_Tree;
friend class iterator;
friend class reverse_iterator;
public:
Node() {}
explicit Node(void *data) { user_data = data; }
void set_user_data(void *data) { user_data = data; }
void *get_user_data() const { return user_data; }
public:
Node()
{}
explicit Node(void* data)
{
user_data = data;
}
void set_user_data(void* data)
{
user_data = data;
}
void* get_user_data() const
{
return user_data;
}
};
class iterator
{
public:
iterator() {}
iterator(const iterator &rhs) : tr_(rhs.tr_), nd_(rhs.nd_) {}
iterator(pj_rbtree *tr, pj_rbtree_node *nd) : tr_(tr), nd_(nd) {}
Node *operator*() { return (Node*)nd_; }
bool operator==(const iterator &rhs) const { return tr_==rhs.tr_ && nd_==rhs.nd_; }
iterator &operator=(const iterator &rhs) { tr_=rhs.tr_; nd_=rhs.nd_; return *this; }
void operator++() { nd_=pj_rbtree_next(tr_, nd_); }
void operator--() { nd_=pj_rbtree_prev(tr_, nd_); }
protected:
pj_rbtree *tr_;
pj_rbtree_node *nd_;
class iterator {
public:
iterator()
{}
iterator(const iterator& rhs) : tr_(rhs.tr_), nd_(rhs.nd_)
{}
iterator(pj_rbtree* tr, pj_rbtree_node* nd) : tr_(tr), nd_(nd)
{}
Node* operator*()
{
return (Node*)nd_;
}
bool operator==(const iterator& rhs) const
{
return tr_ == rhs.tr_ && nd_ == rhs.nd_;
}
iterator& operator=(const iterator& rhs)
{
tr_ = rhs.tr_;
nd_ = rhs.nd_;
return *this;
}
void operator++()
{
nd_ = pj_rbtree_next(tr_, nd_);
}
void operator--()
{
nd_ = pj_rbtree_prev(tr_, nd_);
}
protected:
pj_rbtree* tr_;
pj_rbtree_node* nd_;
};
class reverse_iterator : public iterator
{
public:
reverse_iterator() {}
reverse_iterator(const reverse_iterator &it) : iterator(it) {}
reverse_iterator(pj_rbtree *t, pj_rbtree_node *n) : iterator(t, n) {}
reverse_iterator &operator=(const reverse_iterator &rhs) { iterator::operator=(rhs); return *this; }
Node *operator*() { return (Node*)nd_; }
bool operator==(const reverse_iterator &rhs) const { return iterator::operator==(rhs); }
void operator++() { nd_=pj_rbtree_prev(tr_, nd_); }
void operator--() { nd_=pj_rbtree_next(tr_, nd_); }
class reverse_iterator : public iterator {
public:
reverse_iterator()
{}
reverse_iterator(const reverse_iterator& it) : iterator(it)
{}
reverse_iterator(pj_rbtree* t, pj_rbtree_node* n) : iterator(t, n)
{}
reverse_iterator& operator=(const reverse_iterator& rhs)
{
iterator::operator=(rhs);
return *this;
}
Node* operator*()
{
return (Node*)nd_;
}
bool operator==(const reverse_iterator& rhs) const
{
return iterator::operator==(rhs);
}
void operator++()
{
nd_ = pj_rbtree_prev(tr_, nd_);
}
void operator--()
{
nd_ = pj_rbtree_next(tr_, nd_);
}
};
explicit PJ_Tree(Comp *comp) { pj_rbtree_init(&t_, comp); }
explicit PJ_Tree(Comp* comp)
{
pj_rbtree_init(&t_, comp);
}
iterator begin()
{
return iterator(&t_, pj_rbtree_first(&t_));
return iterator(&t_, pj_rbtree_first(&t_));
}
iterator end()
{
return iterator(&t_, NULL);
return iterator(&t_, NULL);
}
reverse_iterator rbegin()
{
return reverse_iterator(&t_, pj_rbtree_last(&t_));
return reverse_iterator(&t_, pj_rbtree_last(&t_));
}
reverse_iterator rend()
{
return reverse_iterator(&t_, NULL);
return reverse_iterator(&t_, NULL);
}
bool insert(Node *node)
bool insert(Node* node)
{
return pj_rbtree_insert(&t_, node)==0 ? true : false;
return pj_rbtree_insert(&t_, node) == 0 ? true : false;
}
Node *find(const void *key)
Node* find(const void* key)
{
return (Node*)pj_rbtree_find(&t_, key);
return (Node*)pj_rbtree_find(&t_, key);
}
Node *erase(Node *node)
Node* erase(Node* node)
{
return (Node*)pj_rbtree_erase(&t_, node);
return (Node*)pj_rbtree_erase(&t_, node);
}
unsigned max_height(Node *node=NULL)
unsigned max_height(Node* node = NULL)
{
return pj_rbtree_max_height(&t_, node);
return pj_rbtree_max_height(&t_, node);
}
unsigned min_height(Node *node=NULL)
unsigned min_height(Node* node = NULL)
{
return pj_rbtree_min_height(&t_, node);
return pj_rbtree_min_height(&t_, node);
}
private:
private:
pj_rbtree t_;
};
#endif /* __PJPP_TREE_HPP__ */
#endif /* __PJPP_TREE_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJPP_TYPES_HPP__
#define __PJPP_TYPES_HPP__
@ -23,16 +22,14 @@
#include <pj/types.h>
class Pj_Pool;
class Pj_Socket ;
class Pj_Socket;
class Pj_Lock;
//
// PJLIB initializer.
//
class Pjlib
{
public:
class Pjlib {
public:
Pjlib()
{
pj_init();
@ -46,12 +43,10 @@ public:
//
// Time value wrapper.
//
class Pj_Time_Val : public pj_time_val
{
public:
class Pj_Time_Val : public pj_time_val {
public:
Pj_Time_Val()
{
}
{}
Pj_Time_Val(long init_sec, long init_msec)
{
@ -59,117 +54,121 @@ public:
msec = init_msec;
}
Pj_Time_Val(const Pj_Time_Val &rhs)
{
sec=rhs.sec;
msec=rhs.msec;
}
explicit Pj_Time_Val(const pj_time_val &tv)
{
sec = tv.sec;
msec = tv.msec;
}
long get_sec() const
{
return sec;
}
long get_msec() const
{
return msec;
}
void set_sec (long s)
{
sec = s;
}
void set_msec(long ms)
{
msec = ms;
normalize();
}
long to_msec() const
{
return PJ_TIME_VAL_MSEC((*this));
}
bool operator == (const Pj_Time_Val &rhs) const
{
return PJ_TIME_VAL_EQ((*this), rhs);
}
bool operator > (const Pj_Time_Val &rhs) const
{
return PJ_TIME_VAL_GT((*this), rhs);
}
bool operator >= (const Pj_Time_Val &rhs) const
{
return PJ_TIME_VAL_GTE((*this), rhs);
}
bool operator < (const Pj_Time_Val &rhs) const
{
return PJ_TIME_VAL_LT((*this), rhs);
}
bool operator <= (const Pj_Time_Val &rhs) const
{
return PJ_TIME_VAL_LTE((*this), rhs);
}
Pj_Time_Val & operator = (const Pj_Time_Val &rhs)
Pj_Time_Val(const Pj_Time_Val& rhs)
{
sec = rhs.sec;
msec = rhs.msec;
return *this;
}
Pj_Time_Val & operator += (const Pj_Time_Val &rhs)
{
PJ_TIME_VAL_ADD((*this), rhs);
return *this;
sec = rhs.sec;
msec = rhs.msec;
}
Pj_Time_Val & operator -= (const Pj_Time_Val &rhs)
explicit Pj_Time_Val(const pj_time_val& tv)
{
PJ_TIME_VAL_SUB((*this), rhs);
return *this;
sec = tv.sec;
msec = tv.msec;
}
long get_sec() const
{
return sec;
}
long get_msec() const
{
return msec;
}
void set_sec(long s)
{
sec = s;
}
void set_msec(long ms)
{
msec = ms;
normalize();
}
long to_msec() const
{
return PJ_TIME_VAL_MSEC((*this));
}
bool operator==(const Pj_Time_Val& rhs) const
{
return PJ_TIME_VAL_EQ((*this), rhs);
}
bool operator>(const Pj_Time_Val& rhs) const
{
return PJ_TIME_VAL_GT((*this), rhs);
}
bool operator>=(const Pj_Time_Val& rhs) const
{
return PJ_TIME_VAL_GTE((*this), rhs);
}
bool operator<(const Pj_Time_Val& rhs) const
{
return PJ_TIME_VAL_LT((*this), rhs);
}
bool operator<=(const Pj_Time_Val& rhs) const
{
return PJ_TIME_VAL_LTE((*this), rhs);
}
Pj_Time_Val& operator=(const Pj_Time_Val& rhs)
{
sec = rhs.sec;
msec = rhs.msec;
return *this;
}
Pj_Time_Val& operator+=(const Pj_Time_Val& rhs)
{
PJ_TIME_VAL_ADD((*this), rhs);
return *this;
}
Pj_Time_Val& operator-=(const Pj_Time_Val& rhs)
{
PJ_TIME_VAL_SUB((*this), rhs);
return *this;
}
/* Must include os.hpp to use these, otherwise unresolved in linking */
inline pj_status_t gettimeofday();
inline pj_parsed_time decode();
inline pj_status_t encode(const pj_parsed_time *pt);
inline pj_status_t to_gmt();
inline pj_status_t to_local();
inline pj_status_t gettimeofday();
inline pj_parsed_time decode();
inline pj_status_t encode(const pj_parsed_time* pt);
inline pj_status_t to_gmt();
inline pj_status_t to_local();
private:
void normalize()
{
pj_time_val_normalize(this);
private:
void normalize()
{
pj_time_val_normalize(this);
}
};
//
// Macro to declare common object comparison operators.
//
#define PJ_DECLARE_OPERATORS(rhs_type) \
bool operator!=(rhs_type rhs) const { \
return !operator==(rhs); } \
bool operator<=(rhs_type rhs) const { \
return operator<(rhs) || operator==(rhs); } \
bool operator>(rhs_type rhs) const { \
return !operator<=(rhs); } \
bool operator>=(rhs_type rhs) const { \
return !operator<(rhs); }
#endif /* __PJPP_TYPES_HPP__ */
#define PJ_DECLARE_OPERATORS(rhs_type) \
bool operator!=(rhs_type rhs) const \
{ \
return !operator==(rhs); \
} \
bool operator<=(rhs_type rhs) const \
{ \
return operator<(rhs) || operator==(rhs); \
} \
bool operator>(rhs_type rhs) const \
{ \
return !operator<=(rhs); \
} \
bool operator>=(rhs_type rhs) const \
{ \
return !operator<(rhs); \
}
#endif /* __PJPP_TYPES_HPP__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_ASYNCSOCK_H__
#define __PJ_ASYNCSOCK_H__
@ -28,7 +27,6 @@
#include <pj/ioqueue.h>
#include <pj/sock.h>
PJ_BEGIN_DECL
/**
@ -60,8 +58,8 @@ typedef struct pj_activesock_cb
* pj_activesock_start_read().
*
* @param asock The active socket.
* @param data The buffer containing the new data, if any. If
* the status argument is non-PJ_SUCCESS, this
* @param data The buffer containing the new data, if any. If
* the status argument is non-PJ_SUCCESS, this
* argument may be NULL.
* @param size The length of data in the buffer.
* @param status The status of the read operation. This may contain
@ -69,49 +67,44 @@ typedef struct pj_activesock_cb
* has been closed. In this case, the buffer may
* contain left over data from previous callback which
* the application may want to process.
* @param remainder If application wishes to leave some data in the
* buffer (common for TCP applications), it should
* move the remainder data to the front part of the
* @param remainder If application wishes to leave some data in the
* buffer (common for TCP applications), it should
* move the remainder data to the front part of the
* buffer and set the remainder length here. The value
* of this parameter will be ignored for datagram
* sockets.
*
* @return PJ_TRUE if further read is desired, and PJ_FALSE
* @return PJ_TRUE if further read is desired, and PJ_FALSE
* when application no longer wants to receive data.
* Application may destroy the active socket in the
* callback and return PJ_FALSE here.
*/
pj_bool_t (*on_data_read)(pj_activesock_t *asock,
void *data,
pj_size_t size,
pj_status_t status,
pj_size_t *remainder);
pj_bool_t (*on_data_read)(pj_activesock_t* asock, void* data,
pj_size_t size, pj_status_t status,
pj_size_t* remainder);
/**
* This callback is called when a packet arrives as the result of
* pj_activesock_start_recvfrom().
*
* @param asock The active socket.
* @param data The buffer containing the packet, if any. If
* the status argument is non-PJ_SUCCESS, this
* @param data The buffer containing the packet, if any. If
* the status argument is non-PJ_SUCCESS, this
* argument will be set to NULL.
* @param size The length of packet in the buffer. If
* the status argument is non-PJ_SUCCESS, this
* @param size The length of packet in the buffer. If
* the status argument is non-PJ_SUCCESS, this
* argument will be set to zero.
* @param src_addr Source address of the packet.
* @param addr_len Length of the source address.
* @param status This contains
*
* @return PJ_TRUE if further read is desired, and PJ_FALSE
* @return PJ_TRUE if further read is desired, and PJ_FALSE
* when application no longer wants to receive data.
* Application may destroy the active socket in the
* callback and return PJ_FALSE here.
*/
pj_bool_t (*on_data_recvfrom)(pj_activesock_t *asock,
void *data,
pj_size_t size,
const pj_sockaddr_t *src_addr,
int addr_len,
pj_status_t status);
pj_bool_t (*on_data_recvfrom)(pj_activesock_t* asock, void* data,
pj_size_t size, const pj_sockaddr_t* src_addr,
int addr_len, pj_status_t status);
/**
* This callback is called when data has been sent.
@ -126,9 +119,8 @@ typedef struct pj_activesock_cb
* @return Application may destroy the active socket in the
* callback and return PJ_FALSE here.
*/
pj_bool_t (*on_data_sent)(pj_activesock_t *asock,
pj_ioqueue_op_key_t *send_key,
pj_ssize_t sent);
pj_bool_t (*on_data_sent)(pj_activesock_t* asock,
pj_ioqueue_op_key_t* send_key, pj_ssize_t sent);
/**
* This callback is called when new connection arrives as the result
@ -145,10 +137,9 @@ typedef struct pj_activesock_cb
* connection. Application may destroy the active socket
* in the callback and return PJ_FALSE here.
*/
pj_bool_t (*on_accept_complete)(pj_activesock_t *asock,
pj_sock_t newsock,
const pj_sockaddr_t *src_addr,
int src_addr_len);
pj_bool_t (*on_accept_complete)(pj_activesock_t* asock, pj_sock_t newsock,
const pj_sockaddr_t* src_addr,
int src_addr_len);
/**
* This callback is called when new connection arrives as the result
@ -168,11 +159,9 @@ typedef struct pj_activesock_cb
* connection. Application may destroy the active socket
* in the callback and return PJ_FALSE here.
*/
pj_bool_t (*on_accept_complete2)(pj_activesock_t *asock,
pj_sock_t newsock,
const pj_sockaddr_t *src_addr,
int src_addr_len,
pj_status_t status);
pj_bool_t (*on_accept_complete2)(pj_activesock_t* asock, pj_sock_t newsock,
const pj_sockaddr_t* src_addr,
int src_addr_len, pj_status_t status);
/**
* This callback is called when pending connect operation has been
@ -184,14 +173,13 @@ typedef struct pj_activesock_cb
* PJ_SUCCESS.
*
* @return Application may destroy the active socket in the
* callback and return PJ_FALSE here.
* callback and return PJ_FALSE here.
*/
pj_bool_t (*on_connect_complete)(pj_activesock_t *asock,
pj_status_t status);
pj_bool_t (*on_connect_complete)(pj_activesock_t* asock,
pj_status_t status);
} pj_activesock_cb;
/**
* Settings that can be given during active socket creation. Application
* must initialize this structure with #pj_activesock_cfg_default().
@ -201,12 +189,12 @@ typedef struct pj_activesock_cfg
/**
* Optional group lock to be assigned to the ioqueue key.
*/
pj_grp_lock_t *grp_lock;
pj_grp_lock_t* grp_lock;
/**
* Number of concurrent asynchronous operations that is to be supported
* by the active socket. This value only affects socket receive and
* accept operations -- the active socket will issue one or more
* accept operations -- the active socket will issue one or more
* asynchronous read and accept operations based on the value of this
* field. Setting this field to more than one will allow more than one
* incoming data or incoming connections to be processed simultaneously
@ -218,12 +206,12 @@ typedef struct pj_activesock_cfg
unsigned async_cnt;
/**
* The ioqueue concurrency to be forced on the socket when it is
* The ioqueue concurrency to be forced on the socket when it is
* registered to the ioqueue. See #pj_ioqueue_set_concurrency() for more
* info about ioqueue concurrency.
*
* When this value is -1, the concurrency setting will not be forced for
* this socket, and the socket will inherit the concurrency setting of
* this socket, and the socket will inherit the concurrency setting of
* the ioqueue. When this value is zero, the active socket will disable
* concurrency for the socket. When this value is +1, the active socket
* will enable concurrency for the socket.
@ -249,18 +237,16 @@ typedef struct pj_activesock_cfg
} pj_activesock_cfg;
/**
* Initialize the active socket configuration with the default values.
*
* @param cfg The configuration to be initialized.
*/
PJ_DECL(void) pj_activesock_cfg_default(pj_activesock_cfg *cfg);
PJ_DECL(void) pj_activesock_cfg_default(pj_activesock_cfg* cfg);
/**
* Create the active socket for the specified socket. This will register
* the socket to the specified ioqueue.
* the socket to the specified ioqueue.
*
* @param pool Pool to allocate memory from.
* @param sock The socket handle.
@ -280,17 +266,14 @@ PJ_DECL(void) pj_activesock_cfg_default(pj_activesock_cfg *cfg);
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_create(pj_pool_t *pool,
pj_sock_t sock,
int sock_type,
const pj_activesock_cfg *opt,
pj_ioqueue_t *ioqueue,
const pj_activesock_cb *cb,
void *user_data,
pj_activesock_t **p_asock);
PJ_DECL(pj_status_t)
pj_activesock_create(pj_pool_t* pool, pj_sock_t sock, int sock_type,
const pj_activesock_cfg* opt, pj_ioqueue_t* ioqueue,
const pj_activesock_cb* cb, void* user_data,
pj_activesock_t** p_asock);
/**
* Create UDP socket descriptor, bind it to the specified address, and
* Create UDP socket descriptor, bind it to the specified address, and
* create the active socket for the socket descriptor.
*
* @param pool Pool to allocate memory from.
@ -311,14 +294,11 @@ PJ_DECL(pj_status_t) pj_activesock_create(pj_pool_t *pool,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_create_udp(pj_pool_t *pool,
const pj_sockaddr *addr,
const pj_activesock_cfg *opt,
pj_ioqueue_t *ioqueue,
const pj_activesock_cb *cb,
void *user_data,
pj_activesock_t **p_asock,
pj_sockaddr *bound_addr);
PJ_DECL(pj_status_t)
pj_activesock_create_udp(pj_pool_t* pool, const pj_sockaddr* addr,
const pj_activesock_cfg* opt, pj_ioqueue_t* ioqueue,
const pj_activesock_cb* cb, void* user_data,
pj_activesock_t** p_asock, pj_sockaddr* bound_addr);
/**
* Close the active socket. This will unregister the socket from the
@ -329,11 +309,11 @@ PJ_DECL(pj_status_t) pj_activesock_create_udp(pj_pool_t *pool,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_close(pj_activesock_t *asock);
PJ_DECL(pj_status_t) pj_activesock_close(pj_activesock_t* asock);
#if (defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \
PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0) || \
defined(DOXYGEN)
PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT != 0) || \
defined(DOXYGEN)
/**
* Set iPhone OS background mode setting. Setting to 1 will enable TCP
* active socket to receive incoming data when application is in the
@ -347,8 +327,7 @@ PJ_DECL(pj_status_t) pj_activesock_close(pj_activesock_t *asock);
* @param val The value of background mode setting.
*
*/
PJ_DECL(void) pj_activesock_set_iphone_os_bg(pj_activesock_t *asock,
int val);
PJ_DECL(void) pj_activesock_set_iphone_os_bg(pj_activesock_t* asock, int val);
/**
* Enable/disable support for iPhone OS background mode. This setting
@ -378,8 +357,8 @@ PJ_DECL(void) pj_activesock_enable_iphone_os_bg(pj_bool_t val);
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_set_user_data(pj_activesock_t *asock,
void *user_data);
PJ_DECL(pj_status_t)
pj_activesock_set_user_data(pj_activesock_t* asock, void* user_data);
/**
* Retrieve the user data previously associated with this active
@ -389,22 +368,21 @@ PJ_DECL(pj_status_t) pj_activesock_set_user_data(pj_activesock_t *asock,
*
* @return The user data.
*/
PJ_DECL(void*) pj_activesock_get_user_data(pj_activesock_t *asock);
PJ_DECL(void*) pj_activesock_get_user_data(pj_activesock_t* asock);
/**
* Starts read operation on this active socket. This function will create
* \a async_cnt number of buffers (the \a async_cnt parameter was given
* in \a pj_activesock_create() function) where each buffer is \a buff_size
* long. The buffers are allocated from the specified \a pool. Once the
* long. The buffers are allocated from the specified \a pool. Once the
* buffers are created, it then issues \a async_cnt number of asynchronous
* \a recv() operations to the socket and returns back to caller. Incoming
* data on the socket will be reported back to application via the
* data on the socket will be reported back to application via the
* \a on_data_read() callback.
*
* Application only needs to call this function once to initiate read
* operations. Further read operations will be done automatically by the
* active socket when \a on_data_read() callback returns non-zero.
* active socket when \a on_data_read() callback returns non-zero.
*
* @param asock The active socket.
* @param pool Pool used to allocate buffers for incoming data.
@ -414,10 +392,9 @@ PJ_DECL(void*) pj_activesock_get_user_data(pj_activesock_t *asock);
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_start_read(pj_activesock_t *asock,
pj_pool_t *pool,
unsigned buff_size,
pj_uint32_t flags);
PJ_DECL(pj_status_t)
pj_activesock_start_read(pj_activesock_t* asock, pj_pool_t* pool,
unsigned buff_size, pj_uint32_t flags);
/**
* Same as #pj_activesock_start_read(), except that the application
@ -433,11 +410,10 @@ PJ_DECL(pj_status_t) pj_activesock_start_read(pj_activesock_t *asock,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_start_read2(pj_activesock_t *asock,
pj_pool_t *pool,
unsigned buff_size,
void *readbuf[],
pj_uint32_t flags);
PJ_DECL(pj_status_t)
pj_activesock_start_read2(pj_activesock_t* asock, pj_pool_t* pool,
unsigned buff_size, void* readbuf[],
pj_uint32_t flags);
/**
* Same as pj_activesock_start_read(), except that this function is used
@ -452,13 +428,12 @@ PJ_DECL(pj_status_t) pj_activesock_start_read2(pj_activesock_t *asock,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_start_recvfrom(pj_activesock_t *asock,
pj_pool_t *pool,
unsigned buff_size,
pj_uint32_t flags);
PJ_DECL(pj_status_t)
pj_activesock_start_recvfrom(pj_activesock_t* asock, pj_pool_t* pool,
unsigned buff_size, pj_uint32_t flags);
/**
* Same as #pj_activesock_start_recvfrom() except that the recvfrom()
* Same as #pj_activesock_start_recvfrom() except that the recvfrom()
* operation takes the buffer from the argument rather than creating
* new ones.
*
@ -471,11 +446,10 @@ PJ_DECL(pj_status_t) pj_activesock_start_recvfrom(pj_activesock_t *asock,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_start_recvfrom2(pj_activesock_t *asock,
pj_pool_t *pool,
unsigned buff_size,
void *readbuf[],
pj_uint32_t flags);
PJ_DECL(pj_status_t)
pj_activesock_start_recvfrom2(pj_activesock_t* asock, pj_pool_t* pool,
unsigned buff_size, void* readbuf[],
pj_uint32_t flags);
/**
* Send data using the socket.
@ -483,7 +457,7 @@ PJ_DECL(pj_status_t) pj_activesock_start_recvfrom2(pj_activesock_t *asock,
* @param asock The active socket.
* @param send_key The operation key to send the data, which is useful
* if application wants to submit multiple pending
* send operations and want to track which exact data
* send operations and want to track which exact data
* has been sent in the \a on_data_sent() callback.
* @param data The data to be sent. This data must remain valid
* until the data has been sent.
@ -497,11 +471,9 @@ PJ_DECL(pj_status_t) pj_activesock_start_recvfrom2(pj_activesock_t *asock,
* called when data is actually sent. Any other return
* value indicates error condition.
*/
PJ_DECL(pj_status_t) pj_activesock_send(pj_activesock_t *asock,
pj_ioqueue_op_key_t *send_key,
const void *data,
pj_ssize_t *size,
unsigned flags);
PJ_DECL(pj_status_t)
pj_activesock_send(pj_activesock_t* asock, pj_ioqueue_op_key_t* send_key,
const void* data, pj_ssize_t* size, unsigned flags);
/**
* Send datagram using the socket.
@ -509,7 +481,7 @@ PJ_DECL(pj_status_t) pj_activesock_send(pj_activesock_t *asock,
* @param asock The active socket.
* @param send_key The operation key to send the data, which is useful
* if application wants to submit multiple pending
* send operations and want to track which exact data
* send operations and want to track which exact data
* has been sent in the \a on_data_sent() callback.
* @param data The data to be sent. This data must remain valid
* until the data has been sent.
@ -524,25 +496,22 @@ PJ_DECL(pj_status_t) pj_activesock_send(pj_activesock_t *asock,
* called when data is actually sent. Any other return
* value indicates error condition.
*/
PJ_DECL(pj_status_t) pj_activesock_sendto(pj_activesock_t *asock,
pj_ioqueue_op_key_t *send_key,
const void *data,
pj_ssize_t *size,
unsigned flags,
const pj_sockaddr_t *addr,
int addr_len);
PJ_DECL(pj_status_t)
pj_activesock_sendto(pj_activesock_t* asock, pj_ioqueue_op_key_t* send_key,
const void* data, pj_ssize_t* size, unsigned flags,
const pj_sockaddr_t* addr, int addr_len);
#if PJ_HAS_TCP
/**
* Starts asynchronous socket accept() operations on this active socket.
* Application must bind the socket before calling this function. This
* function will issue \a async_cnt number of asynchronous \a accept()
* Starts asynchronous socket accept() operations on this active socket.
* Application must bind the socket before calling this function. This
* function will issue \a async_cnt number of asynchronous \a accept()
* operations to the socket and returns back to caller. Incoming
* connection on the socket will be reported back to application via the
* \a on_accept_complete() callback.
*
* Application only needs to call this function once to initiate accept()
* operations. Further accept() operations will be done automatically by
* operations. Further accept() operations will be done automatically by
* the active socket when \a on_accept_complete() callback returns non-zero.
*
* @param asock The active socket.
@ -552,12 +521,12 @@ PJ_DECL(pj_status_t) pj_activesock_sendto(pj_activesock_t *asock,
* @return PJ_SUCCESS if the operation has been successful,
* or the appropriate error code on failure.
*/
PJ_DECL(pj_status_t) pj_activesock_start_accept(pj_activesock_t *asock,
pj_pool_t *pool);
PJ_DECL(pj_status_t)
pj_activesock_start_accept(pj_activesock_t* asock, pj_pool_t* pool);
/**
* Starts asynchronous socket connect() operation for this socket. Once
* the connection is done (either successfully or not), the
* the connection is done (either successfully or not), the
* \a on_connect_complete() callback will be called.
*
* @param asock The active socket.
@ -567,18 +536,16 @@ PJ_DECL(pj_status_t) pj_activesock_start_accept(pj_activesock_t *asock,
* @param addr_len Length of the remote address.
*
* @return PJ_SUCCESS if connection can be established immediately,
* or PJ_EPENDING if connection cannot be established
* or PJ_EPENDING if connection cannot be established
* immediately. In this case the \a on_connect_complete()
* callback will be called when connection is complete.
* callback will be called when connection is complete.
* Any other return value indicates error condition.
*/
PJ_DECL(pj_status_t) pj_activesock_start_connect(pj_activesock_t *asock,
pj_pool_t *pool,
const pj_sockaddr_t *remaddr,
int addr_len);
PJ_DECL(pj_status_t)
pj_activesock_start_connect(pj_activesock_t* asock, pj_pool_t* pool,
const pj_sockaddr_t* remaddr, int addr_len);
#endif /* PJ_HAS_TCP */
#endif /* PJ_HAS_TCP */
/**
* @}
@ -586,5 +553,4 @@ PJ_DECL(pj_status_t) pj_activesock_start_connect(pj_activesock_t *asock,
PJ_END_DECL
#endif /* __PJ_ASYNCSOCK_H__ */
#endif /* __PJ_ASYNCSOCK_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_ADDR_RESOLV_H__
#define __PJ_ADDR_RESOLV_H__
@ -44,7 +43,7 @@ PJ_BEGIN_DECL
* pj_hostent he;
* pj_status_t rc;
* pj_str_t host = pj_str("host.example.com");
*
*
* rc = pj_gethostbyname( &host, &he);
* if (rc != PJ_SUCCESS) {
* char errbuf[80];
@ -64,26 +63,25 @@ PJ_BEGIN_DECL
/** This structure describes an Internet host address. */
typedef struct pj_hostent
{
char *h_name; /**< The official name of the host. */
char **h_aliases; /**< Aliases list. */
int h_addrtype; /**< Host address type. */
int h_length; /**< Length of address. */
char **h_addr_list; /**< List of addresses. */
char* h_name; /**< The official name of the host. */
char** h_aliases; /**< Aliases list. */
int h_addrtype; /**< Host address type. */
int h_length; /**< Length of address. */
char** h_addr_list; /**< List of addresses. */
} pj_hostent;
/** Shortcut to h_addr_list[0] */
#define h_addr h_addr_list[0]
/**
/**
* This structure describes address information pj_getaddrinfo().
*/
typedef struct pj_addrinfo
{
char ai_canonname[PJ_MAX_HOSTNAME]; /**< Canonical name for host*/
pj_sockaddr ai_addr; /**< Binary address. */
char ai_canonname[PJ_MAX_HOSTNAME]; /**< Canonical name for host*/
pj_sockaddr ai_addr; /**< Binary address. */
} pj_addrinfo;
/**
* This function fills the structure of type pj_hostent for a given host name.
* For host resolution function that also works with IPv6, please see
@ -97,12 +95,11 @@ typedef struct pj_addrinfo
* invocation.
*
* @return PJ_SUCCESS, or the appropriate error codes.
*/
PJ_DECL(pj_status_t) pj_gethostbyname(const pj_str_t *name, pj_hostent *he);
*/
PJ_DECL(pj_status_t) pj_gethostbyname(const pj_str_t* name, pj_hostent* he);
/**
* Resolve the primary IP address of local host.
* Resolve the primary IP address of local host.
*
* @param af The desired address family to query. Valid values
* are pj_AF_INET() or pj_AF_INET6().
@ -113,8 +110,7 @@ PJ_DECL(pj_status_t) pj_gethostbyname(const pj_str_t *name, pj_hostent *he);
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_gethostip(int af, pj_sockaddr *addr);
PJ_DECL(pj_status_t) pj_gethostip(int af, pj_sockaddr* addr);
/**
* Get the interface IP address to send data to the specified destination.
@ -135,11 +131,9 @@ PJ_DECL(pj_status_t) pj_gethostip(int af, pj_sockaddr *addr);
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_getipinterface(int af,
const pj_str_t *dst,
pj_sockaddr *itf_addr,
pj_bool_t allow_resolve,
pj_sockaddr *p_dst_addr);
PJ_DECL(pj_status_t)
pj_getipinterface(int af, const pj_str_t* dst, pj_sockaddr* itf_addr,
pj_bool_t allow_resolve, pj_sockaddr* p_dst_addr);
/**
* Get the IP address of the default interface. Default interface is the
@ -154,14 +148,12 @@ PJ_DECL(pj_status_t) pj_getipinterface(int af,
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_getdefaultipinterface(int af,
pj_sockaddr *addr);
PJ_DECL(pj_status_t) pj_getdefaultipinterface(int af, pj_sockaddr* addr);
/**
* This function translates the name of a service location (for example,
* This function translates the name of a service location (for example,
* a host name) and returns a set of addresses and associated information
* to be used in creating a socket with which to address the specified
* to be used in creating a socket with which to address the specified
* service.
*
* @param af The desired address family to query. Valid values
@ -177,14 +169,11 @@ PJ_DECL(pj_status_t) pj_getdefaultipinterface(int af,
*
* @return PJ_SUCCESS on success, or the appropriate error code.
*/
PJ_DECL(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *name,
unsigned *count, pj_addrinfo ai[]);
PJ_DECL(pj_status_t)
pj_getaddrinfo(int af, const pj_str_t* name, unsigned* count, pj_addrinfo ai[]);
/** @} */
PJ_END_DECL
#endif /* __PJ_ADDR_RESOLV_H__ */
#endif /* __PJ_ADDR_RESOLV_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_ARRAY_H__
#define __PJ_ARRAY_H__
@ -47,11 +46,9 @@ PJ_BEGIN_DECL
* @param pos the position where the new element is put.
* @param value the value to copy to the new element.
*/
PJ_DECL(void) pj_array_insert( void *array,
unsigned elem_size,
unsigned count,
unsigned pos,
const void *value);
PJ_DECL(void)
pj_array_insert(void* array, unsigned elem_size, unsigned count, unsigned pos,
const void* value);
/**
* Erase a value from the array at given position, and rearrange the remaining
@ -62,10 +59,8 @@ PJ_DECL(void) pj_array_insert( void *array,
* @param count the current number of elements in the array.
* @param pos the index/position to delete.
*/
PJ_DECL(void) pj_array_erase( void *array,
unsigned elem_size,
unsigned count,
unsigned pos);
PJ_DECL(void)
pj_array_erase(void* array, unsigned elem_size, unsigned count, unsigned pos);
/**
* Search the first value in the array according to matching function.
@ -73,17 +68,15 @@ PJ_DECL(void) pj_array_erase( void *array,
* @param array the array.
* @param elem_size the individual size of the element.
* @param count the number of elements.
* @param matching the matching function, which MUST return PJ_SUCCESS if
* @param matching the matching function, which MUST return PJ_SUCCESS if
* the specified element match.
* @param result the pointer to the value found.
*
* @return PJ_SUCCESS if value is found, otherwise the error code.
*/
PJ_DECL(pj_status_t) pj_array_find( const void *array,
unsigned elem_size,
unsigned count,
pj_status_t (*matching)(const void *value),
void **result);
PJ_DECL(pj_status_t)
pj_array_find(const void* array, unsigned elem_size, unsigned count,
pj_status_t (*matching)(const void* value), void** result);
/**
* @}
@ -91,6 +84,4 @@ PJ_DECL(pj_status_t) pj_array_find( const void *array,
PJ_END_DECL
#endif /* __PJ_ARRAY_H__ */
#endif /* __PJ_ARRAY_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_ASSERT_H__
#define __PJ_ASSERT_H__
@ -46,20 +45,22 @@
* @param expr The expression to be evaluated.
*/
#ifndef pj_assert
# define pj_assert(expr) assert(expr)
# define pj_assert(expr) assert(expr)
#endif
/**
* @hideinitializer
* If the expression yields false, assertion will be triggered
* and the current function will return with the specified return value.
*/
// #if defined(PJ_ENABLE_EXTRA_CHECK) && PJ_ENABLE_EXTRA_CHECK != 0
#define PJ_ASSERT_RETURN(expr,retval) \
do { \
if (!(expr)) { pj_assert(expr); return retval; } \
} while (0)
#define PJ_ASSERT_RETURN(expr, retval) \
do { \
if (!(expr)) { \
pj_assert(expr); \
return retval; \
} \
} while (0)
//#else
//# define PJ_ASSERT_RETURN(expr,retval) pj_assert(expr)
//#endif
@ -70,16 +71,16 @@
* and @a exec_on_fail will be executed.
*/
//#if defined(PJ_ENABLE_EXTRA_CHECK) && PJ_ENABLE_EXTRA_CHECK != 0
#define PJ_ASSERT_ON_FAIL(expr,exec_on_fail) \
do { \
pj_assert(expr); \
if (!(expr)) exec_on_fail; \
} while (0)
#define PJ_ASSERT_ON_FAIL(expr, exec_on_fail) \
do { \
pj_assert(expr); \
if (!(expr)) \
exec_on_fail; \
} while (0)
//#else
//# define PJ_ASSERT_ON_FAIL(expr,exec_on_fail) pj_assert(expr)
//#endif
/** @} */
#endif /* __PJ_ASSERT_H__ */
#endif /* __PJ_ASSERT_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_ASSERT_H__
#define __PJ_COMPAT_ASSERT_H__
@ -26,12 +25,11 @@
*/
#if defined(PJ_HAS_ASSERT_H) && PJ_HAS_ASSERT_H != 0
# include <assert.h>
# include <assert.h>
#else
# warning "assert() is not implemented"
# define assert(expr)
# warning "assert() is not implemented"
# define assert(expr)
#endif
#endif /* __PJ_COMPAT_ASSERT_H__ */
#endif /* __PJ_COMPAT_ASSERT_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_CC_ARMCC_H__
#define __PJ_COMPAT_CC_ARMCC_H__
@ -26,33 +25,32 @@
*/
#ifndef __ARMCC__
# error "This file is only for armcc!"
# error "This file is only for armcc!"
#endif
#define PJ_CC_NAME "armcc"
#define PJ_CC_VER_1 (__ARMCC_VERSION/100000)
#define PJ_CC_VER_2 ((__ARMCC_VERSION%100000)/10000)
#define PJ_CC_VER_3 (__ARMCC_VERSION%10000)
#define PJ_CC_NAME "armcc"
#define PJ_CC_VER_1 (__ARMCC_VERSION / 100000)
#define PJ_CC_VER_2 ((__ARMCC_VERSION % 100000) / 10000)
#define PJ_CC_VER_3 (__ARMCC_VERSION % 10000)
#ifdef __cplusplus
# define PJ_INLINE_SPECIFIER inline
# define PJ_INLINE_SPECIFIER inline
#else
# define PJ_INLINE_SPECIFIER static __inline
# define PJ_INLINE_SPECIFIER static __inline
#endif
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_ATTR_NORETURN __attribute__ ((noreturn))
#define PJ_ATTR_MAY_ALIAS __attribute__ ((__may_alias__))
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_ATTR_NORETURN __attribute__((noreturn))
#define PJ_ATTR_MAY_ALIAS __attribute__((__may_alias__))
#define PJ_HAS_INT64 1
#define PJ_HAS_INT64 1
typedef long long pj_int64_t;
typedef unsigned long long pj_uint64_t;
#define PJ_INT64_FMT "L"
#define PJ_INT64_FMT "L"
#define PJ_UNREACHED(x)
#endif /* __PJ_COMPAT_CC_ARMCC_H__ */
#define PJ_UNREACHED(x)
#endif /* __PJ_COMPAT_CC_ARMCC_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_CC_CODEW_H__
#define __PJ_COMPAT_CC_CODEW_H__
@ -26,31 +25,29 @@
*/
#ifndef __MWERKS__
# error "This file is only for Code Warrior!"
# error "This file is only for Code Warrior!"
#endif
#define PJ_CC_NAME "codewarrior"
#define PJ_CC_VER_1 ((__MWERKS__ & 0xF000) >> 12)
#define PJ_CC_VER_2 ((__MWERKS__ & 0x0F00) >> 8)
#define PJ_CC_VER_3 ((__MWERKS__ & 0xFF))
#define PJ_CC_NAME "codewarrior"
#define PJ_CC_VER_1 ((__MWERKS__ & 0xF000) >> 12)
#define PJ_CC_VER_2 ((__MWERKS__ & 0x0F00) >> 8)
#define PJ_CC_VER_3 ((__MWERKS__ & 0xFF))
#define PJ_INLINE_SPECIFIER static inline
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_ATTR_NORETURN
#define PJ_ATTR_MAY_ALIAS
#define PJ_INLINE_SPECIFIER static inline
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_ATTR_NORETURN
#define PJ_ATTR_MAY_ALIAS
#define PJ_HAS_INT64 1
#define PJ_HAS_INT64 1
typedef long long pj_int64_t;
typedef unsigned long long pj_uint64_t;
#define PJ_INT64(val) val##LL
#define PJ_UINT64(val) val##LLU
#define PJ_INT64_FMT "L"
#define PJ_INT64(val) val##LL
#define PJ_UINT64(val) val##LLU
#define PJ_INT64_FMT "L"
#define PJ_UNREACHED(x)
#endif /* __PJ_COMPAT_CC_CODEW_H__ */
#define PJ_UNREACHED(x)
#endif /* __PJ_COMPAT_CC_CODEW_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_CC_GCC_H__
#define __PJ_COMPAT_CC_GCC_H__
@ -26,55 +25,51 @@
*/
#ifndef __GNUC__
# error "This file is only for gcc!"
# error "This file is only for gcc!"
#endif
#define PJ_CC_NAME "gcc"
#define PJ_CC_VER_1 __GNUC__
#define PJ_CC_VER_2 __GNUC_MINOR__
#define PJ_CC_NAME "gcc"
#define PJ_CC_VER_1 __GNUC__
#define PJ_CC_VER_2 __GNUC_MINOR__
/* __GNUC_PATCHLEVEL__ doesn't exist in gcc-2.9x.x */
#ifdef __GNUC_PATCHLEVEL__
# define PJ_CC_VER_3 __GNUC_PATCHLEVEL__
# define PJ_CC_VER_3 __GNUC_PATCHLEVEL__
#else
# define PJ_CC_VER_3 0
# define PJ_CC_VER_3 0
#endif
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_HAS_INT64 1
#define PJ_HAS_INT64 1
#ifdef __STRICT_ANSI__
#include <inttypes.h>
typedef int64_t pj_int64_t;
typedef uint64_t pj_uint64_t;
#define PJ_INLINE_SPECIFIER static __inline
#define PJ_ATTR_NORETURN
#define PJ_ATTR_MAY_ALIAS
# include <inttypes.h>
typedef int64_t pj_int64_t;
typedef uint64_t pj_uint64_t;
# define PJ_INLINE_SPECIFIER static __inline
# define PJ_ATTR_NORETURN
# define PJ_ATTR_MAY_ALIAS
#else
typedef long long pj_int64_t;
typedef unsigned long long pj_uint64_t;
#define PJ_INLINE_SPECIFIER static inline
#define PJ_ATTR_NORETURN __attribute__ ((noreturn))
#define PJ_ATTR_MAY_ALIAS __attribute__((__may_alias__))
typedef long long pj_int64_t;
typedef unsigned long long pj_uint64_t;
# define PJ_INLINE_SPECIFIER static inline
# define PJ_ATTR_NORETURN __attribute__((noreturn))
# define PJ_ATTR_MAY_ALIAS __attribute__((__may_alias__))
#endif
#define PJ_INT64(val) val##LL
#define PJ_UINT64(val) val##ULL
#define PJ_INT64_FMT "L"
#define PJ_INT64(val) val##LL
#define PJ_UINT64(val) val##ULL
#define PJ_INT64_FMT "L"
#ifdef __GLIBC__
# define PJ_HAS_BZERO 1
# define PJ_HAS_BZERO 1
#endif
#define PJ_UNREACHED(x)
#define PJ_UNREACHED(x)
#define PJ_ALIGN_DATA(declaration, alignment) declaration __attribute__((aligned (alignment)))
#endif /* __PJ_COMPAT_CC_GCC_H__ */
#define PJ_ALIGN_DATA(declaration, alignment) \
declaration __attribute__((aligned(alignment)))
#endif /* __PJ_COMPAT_CC_GCC_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_CC_GCCE_H__
#define __PJ_COMPAT_CC_GCCE_H__
@ -26,30 +25,27 @@
*/
#ifndef __GCCE__
# error "This file is only for gcce!"
# error "This file is only for gcce!"
#endif
#define PJ_CC_NAME "gcce"
#define PJ_CC_VER_1 __GCCE__
#define PJ_CC_VER_2 __GCCE_MINOR__
#define PJ_CC_VER_3 __GCCE_PATCHLEVEL__
#define PJ_CC_NAME "gcce"
#define PJ_CC_VER_1 __GCCE__
#define PJ_CC_VER_2 __GCCE_MINOR__
#define PJ_CC_VER_3 __GCCE_PATCHLEVEL__
#define PJ_INLINE_SPECIFIER static inline
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_ATTR_NORETURN __attribute__((noreturn))
#define PJ_ATTR_MAY_ALIAS __attribute__((__may_alias__))
#define PJ_INLINE_SPECIFIER static inline
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_ATTR_NORETURN __attribute__ ((noreturn))
#define PJ_ATTR_MAY_ALIAS __attribute__ ((__may_alias__))
#define PJ_HAS_INT64 1
#define PJ_HAS_INT64 1
typedef long long pj_int64_t;
typedef unsigned long long pj_uint64_t;
#define PJ_INT64(val) val##LL
#define PJ_UINT64(val) val##LLU
#define PJ_INT64_FMT "L"
#endif /* __PJ_COMPAT_CC_GCCE_H__ */
#define PJ_INT64(val) val##LL
#define PJ_UINT64(val) val##LLU
#define PJ_INT64_FMT "L"
#endif /* __PJ_COMPAT_CC_GCCE_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_CC_MSVC_H__
#define __PJ_COMPAT_CC_MSVC_H__
@ -26,63 +25,63 @@
*/
#ifndef _MSC_VER
# error "This header file is only for Visual C compiler!"
# error "This header file is only for Visual C compiler!"
#endif
#define PJ_CC_NAME "msvc"
#define PJ_CC_VER_1 (_MSC_VER/100)
#define PJ_CC_VER_2 (_MSC_VER%100)
#define PJ_CC_VER_3 0
#define PJ_CC_NAME "msvc"
#define PJ_CC_VER_1 (_MSC_VER / 100)
#define PJ_CC_VER_2 (_MSC_VER % 100)
#define PJ_CC_VER_3 0
/* Disable CRT deprecation warnings. */
#if PJ_CC_VER_1 >= 8 && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
# define _CRT_SECURE_NO_DEPRECATE
#endif
#if PJ_CC_VER_1 >= 8 && !defined(_CRT_SECURE_NO_WARNINGS)
# define _CRT_SECURE_NO_WARNINGS
/* The above doesn't seem to work, at least on VS2005, so lets use
* this construct as well.
*/
# pragma warning(disable: 4996)
# define _CRT_SECURE_NO_WARNINGS
/* The above doesn't seem to work, at least on VS2005, so lets use
* this construct as well.
*/
# pragma warning(disable : 4996)
#endif
#pragma warning(disable: 4127) // conditional expression is constant
#pragma warning(disable: 4611) // not wise to mix setjmp with C++
#pragma warning(disable: 4514) // unref. inline function has been removed
#pragma warning(disable : 4127) // conditional expression is constant
#pragma warning(disable : 4611) // not wise to mix setjmp with C++
#pragma warning(disable : 4514) // unref. inline function has been removed
#ifdef NDEBUG
# pragma warning(disable: 4702) // unreachable code
# pragma warning(disable: 4710) // function is not inlined.
# pragma warning(disable: 4711) // function selected for auto inline expansion
# pragma warning(disable : 4702) // unreachable code
# pragma warning(disable : 4710) // function is not inlined.
# pragma warning( \
disable : 4711) // function selected for auto inline expansion
#endif
#ifdef __cplusplus
# define PJ_INLINE_SPECIFIER inline
# define PJ_INLINE_SPECIFIER inline
#else
# define PJ_INLINE_SPECIFIER static __inline
# define PJ_INLINE_SPECIFIER static __inline
#endif
#define PJ_EXPORT_DECL_SPECIFIER __declspec(dllexport)
#define PJ_EXPORT_DEF_SPECIFIER __declspec(dllexport)
#define PJ_IMPORT_DECL_SPECIFIER __declspec(dllimport)
#define PJ_EXPORT_DECL_SPECIFIER __declspec(dllexport)
#define PJ_EXPORT_DEF_SPECIFIER __declspec(dllexport)
#define PJ_IMPORT_DECL_SPECIFIER __declspec(dllimport)
#define PJ_THREAD_FUNC
#define PJ_NORETURN __declspec(noreturn)
#define PJ_ATTR_NORETURN
#define PJ_ATTR_MAY_ALIAS
#define PJ_THREAD_FUNC
#define PJ_NORETURN __declspec(noreturn)
#define PJ_ATTR_NORETURN
#define PJ_ATTR_MAY_ALIAS
#define PJ_HAS_INT64 1
#define PJ_HAS_INT64 1
typedef __int64 pj_int64_t;
typedef unsigned __int64 pj_uint64_t;
#define PJ_INT64(val) val##i64
#define PJ_UINT64(val) val##ui64
#define PJ_INT64_FMT "I64"
#define PJ_INT64(val) val##i64
#define PJ_UINT64(val) val##ui64
#define PJ_INT64_FMT "I64"
#define PJ_UNREACHED(x)
#define PJ_UNREACHED(x)
#define PJ_ALIGN_DATA(declaration, alignment) __declspec(align(alignment)) declaration
#endif /* __PJ_COMPAT_CC_MSVC_H__ */
#define PJ_ALIGN_DATA(declaration, alignment) \
__declspec(align(alignment)) declaration
#endif /* __PJ_COMPAT_CC_MSVC_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_CC_MWCC_H__
#define __PJ_COMPAT_CC_MWCC_H__
@ -26,31 +25,29 @@
*/
#ifndef __CW32__
# error "This file is only for mwcc!"
# error "This file is only for mwcc!"
#endif
#define PJ_CC_NAME "mwcc32sym"
#define PJ_CC_VER_1 1
#define PJ_CC_VER_2 0
#define PJ_CC_VER_3 0
#define PJ_CC_NAME "mwcc32sym"
#define PJ_CC_VER_1 1
#define PJ_CC_VER_2 0
#define PJ_CC_VER_3 0
#define PJ_INLINE_SPECIFIER static inline
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_ATTR_NORETURN __attribute__((noreturn))
#define PJ_ATTR_MAY_ALIAS
#define PJ_INLINE_SPECIFIER static inline
#define PJ_THREAD_FUNC
#define PJ_NORETURN
#define PJ_ATTR_NORETURN __attribute__ ((noreturn))
#define PJ_ATTR_MAY_ALIAS
#define PJ_HAS_INT64 1
#define PJ_HAS_INT64 1
typedef long long pj_int64_t;
typedef unsigned long long pj_uint64_t;
#define PJ_INT64(val) val##LL
#define PJ_UINT64(val) val##LLU
#define PJ_INT64_FMT "L"
#define PJ_INT64(val) val##LL
#define PJ_UINT64(val) val##LLU
#define PJ_INT64_FMT "L"
#define PJ_UNREACHED(x)
#endif /* __PJ_COMPAT_CC_MWCC_H__ */
#define PJ_UNREACHED(x)
#endif /* __PJ_COMPAT_CC_MWCC_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_CTYPE_H__
#define __PJ_COMPAT_CTYPE_H__
@ -26,20 +25,19 @@
*/
#if defined(PJ_HAS_CTYPE_H) && PJ_HAS_CTYPE_H != 0
# include <ctype.h>
# include <ctype.h>
#else
# define isalnum(c) (isalpha(c) || isdigit(c))
# define isalpha(c) (islower(c) || isupper(c))
# define isascii(c) (((unsigned char)(c))<=0x7f)
# define isdigit(c) ((c)>='0' && (c)<='9')
# define isspace(c) ((c)==' ' || (c)=='\t' ||\
(c)=='\n' || (c)=='\r' || (c)=='\v')
# define islower(c) ((c)>='a' && (c)<='z')
# define isupper(c) ((c)>='A' && (c)<='Z')
# define isxdigit(c) (isdigit(c) || (tolower(c)>='a'&&tolower(c)<='f'))
# define tolower(c) (((c) >= 'A' && (c) <= 'Z') ? (c)+('a'-'A') : (c))
# define toupper(c) (((c) >= 'a' && (c) <= 'z') ? (c)-('a'-'A') : (c))
# define isalnum(c) (isalpha(c) || isdigit(c))
# define isalpha(c) (islower(c) || isupper(c))
# define isascii(c) (((unsigned char)(c)) <= 0x7f)
# define isdigit(c) ((c) >= '0' && (c) <= '9')
# define isspace(c) \
((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\r' || (c) == '\v')
# define islower(c) ((c) >= 'a' && (c) <= 'z')
# define isupper(c) ((c) >= 'A' && (c) <= 'Z')
# define isxdigit(c) (isdigit(c) || (tolower(c) >= 'a' && tolower(c) <= 'f'))
# define tolower(c) (((c) >= 'A' && (c) <= 'Z') ? (c) + ('a' - 'A') : (c))
# define toupper(c) (((c) >= 'a' && (c) <= 'z') ? (c) - ('a' - 'A') : (c))
#endif
#endif /* __PJ_COMPAT_CTYPE_H__ */
#endif /* __PJ_COMPAT_CTYPE_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,31 +14,29 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_ERRNO_H__
#define __PJ_COMPAT_ERRNO_H__
#if defined(PJ_WIN32) && PJ_WIN32 != 0 || \
defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0 || \
defined(PJ_WIN64) && PJ_WIN64 != 0
defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0 || \
defined(PJ_WIN64) && PJ_WIN64 != 0
typedef unsigned long pj_os_err_type;
# define pj_get_native_os_error() GetLastError()
# define pj_get_native_netos_error() WSAGetLastError()
typedef unsigned long pj_os_err_type;
# define pj_get_native_os_error() GetLastError()
# define pj_get_native_netos_error() WSAGetLastError()
#elif defined(PJ_HAS_ERRNO_VAR) && PJ_HAS_ERRNO_VAR!= 0
#elif defined(PJ_HAS_ERRNO_VAR) && PJ_HAS_ERRNO_VAR != 0
typedef int pj_os_err_type;
# define pj_get_native_os_error() (errno)
# define pj_get_native_netos_error() (errno)
typedef int pj_os_err_type;
# define pj_get_native_os_error() (errno)
# define pj_get_native_netos_error() (errno)
#else
# error "Please define how to get errno for this platform here!"
# error "Please define how to get errno for this platform here!"
#endif
#endif /* __PJ_COMPAT_ERRNO_H__ */
#endif /* __PJ_COMPAT_ERRNO_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,35 +14,34 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_HIGH_PRECISION_H__
#define __PJ_COMPAT_HIGH_PRECISION_H__
#if defined(PJ_HAS_FLOATING_POINT) && PJ_HAS_FLOATING_POINT != 0
/*
* The first choice for high precision math is to use double.
*/
# include <math.h>
typedef double pj_highprec_t;
/*
* The first choice for high precision math is to use double.
*/
# include <math.h>
typedef double pj_highprec_t;
# define PJ_HIGHPREC_VALUE_IS_ZERO(a) (a==0)
# define pj_highprec_mod(a,b) (a=fmod(a,b))
# define PJ_HIGHPREC_VALUE_IS_ZERO(a) (a == 0)
# define pj_highprec_mod(a, b) (a = fmod(a, b))
#elif defined(PJ_HAS_INT64) && PJ_HAS_INT64 != 0
/*
* Next choice is to use 64-bit arithmatics.
*/
typedef pj_int64_t pj_highprec_t;
/*
* Next choice is to use 64-bit arithmatics.
*/
typedef pj_int64_t pj_highprec_t;
#else
# warning "High precision math is not available"
# warning "High precision math is not available"
/*
* Last, fallback to 32-bit arithmetics.
*/
typedef pj_int32_t pj_highprec_t;
/*
* Last, fallback to 32-bit arithmetics.
*/
typedef pj_int32_t pj_highprec_t;
#endif
@ -53,7 +51,7 @@
* Multiply a1 and a2, and store the result in a1.
*/
#ifndef pj_highprec_mul
# define pj_highprec_mul(a1,a2) (a1 = a1 * a2)
# define pj_highprec_mul(a1, a2) (a1 = a1 * a2)
#endif
/**
@ -62,7 +60,7 @@
* Divide a2 from a1, and store the result in a1.
*/
#ifndef pj_highprec_div
# define pj_highprec_div(a1,a2) (a1 = a1 / a2)
# define pj_highprec_div(a1, a2) (a1 = a1 / a2)
#endif
/**
@ -71,18 +69,15 @@
* Get the modulus a2 from a1, and store the result in a1.
*/
#ifndef pj_highprec_mod
# define pj_highprec_mod(a1,a2) (a1 = a1 % a2)
# define pj_highprec_mod(a1, a2) (a1 = a1 % a2)
#endif
/**
* @def PJ_HIGHPREC_VALUE_IS_ZERO(a)
* Test if the specified high precision value is zero.
*/
#ifndef PJ_HIGHPREC_VALUE_IS_ZERO
# define PJ_HIGHPREC_VALUE_IS_ZERO(a) (a==0)
# define PJ_HIGHPREC_VALUE_IS_ZERO(a) (a == 0)
#endif
#endif /* __PJ_COMPAT_HIGH_PRECISION_H__ */
#endif /* __PJ_COMPAT_HIGH_PRECISION_H__ */

View File

@ -1,4 +1,3 @@
/* $Id$ */
/*
* Copyright (C) 2017 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2017 George Joseph <gjoseph@digium.com>
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_LIMITS_H__
#define __PJ_COMPAT_LIMITS_H__
@ -28,40 +27,42 @@
#include <pj/config.h>
#if defined(PJ_HAS_LIMITS_H) && PJ_HAS_LIMITS_H != 0
# include <limits.h>
# include <limits.h>
#else
# ifdef _MSC_VER
# pragma message("limits.h is not found or not supported. LONG_MIN and "\
"LONG_MAX will be defined by the library in "\
"pj/compats/limits.h and overridable in config_site.h")
# else
# warning "limits.h is not found or not supported. LONG_MIN and LONG_MAX " \
# ifdef _MSC_VER
# pragma message( \
"limits.h is not found or not supported. LONG_MIN and " \
"LONG_MAX will be defined by the library in " \
"pj/compats/limits.h and overridable in config_site.h")
# else
# warning \
"limits.h is not found or not supported. LONG_MIN and LONG_MAX " \
"will be defined by the library in pj/compats/limits.h and "\
"overridable in config_site.h"
# endif
# endif
/* Minimum and maximum values a `signed long int' can hold. */
# ifndef LONG_MAX
# if __WORDSIZE == 64
# define LONG_MAX 9223372036854775807L
# else
# define LONG_MAX 2147483647L
# ifndef LONG_MAX
# if __WORDSIZE == 64
# define LONG_MAX 9223372036854775807L
# else
# define LONG_MAX 2147483647L
# endif
# endif
# endif
# ifndef LONG_MIN
# define LONG_MIN (-LONG_MAX - 1L)
# endif
# ifndef LONG_MIN
# define LONG_MIN (-LONG_MAX - 1L)
# endif
/* Maximum value an `unsigned long int' can hold. (Minimum is 0.) */
# ifndef ULONG_MAX
# if __WORDSIZE == 64
# define ULONG_MAX 18446744073709551615UL
# else
# define ULONG_MAX 4294967295UL
# ifndef ULONG_MAX
# if __WORDSIZE == 64
# define ULONG_MAX 18446744073709551615UL
# else
# define ULONG_MAX 4294967295UL
# endif
# endif
# endif
#endif
#endif /* __PJ_COMPAT_LIMITS_H__ */
#endif /* __PJ_COMPAT_LIMITS_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_M_ALPHA_H__
#define __PJ_COMPAT_M_ALPHA_H__
@ -25,12 +24,10 @@
* @brief Describes Alpha processor family specifics.
*/
#define PJ_M_NAME "alpha"
#define PJ_M_NAME "alpha"
#define PJ_HAS_PENTIUM 0
#define PJ_IS_LITTLE_ENDIAN 1
#define PJ_IS_BIG_ENDIAN 0
#endif /* __PJ_COMPAT_M_ALPHA_H__ */
#define PJ_HAS_PENTIUM 0
#define PJ_IS_LITTLE_ENDIAN 1
#define PJ_IS_BIG_ENDIAN 0
#endif /* __PJ_COMPAT_M_ALPHA_H__ */

View File

@ -1,5 +1,4 @@
/* $Id$ */
/*
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
@ -15,7 +14,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJ_COMPAT_M_ARMV4_H__
#define __PJ_COMPAT_M_ARMV4_H__
@ -29,11 +28,10 @@
* This file covers PJ_M_ARMV4 etc.
*/
#define PJ_M_NAME "armv4"
#define PJ_M_NAME "armv4"
#define PJ_HAS_PENTIUM 0
#define PJ_IS_LITTLE_ENDIAN 1
#define PJ_IS_BIG_ENDIAN 0
#define PJ_HAS_PENTIUM 0
#define PJ_IS_LITTLE_ENDIAN 1
#define PJ_IS_BIG_ENDIAN 0
#endif /* __PJ_COMPAT_M_ARMV4_H__ */
#endif /* __PJ_COMPAT_M_ARMV4_H__ */

Some files were not shown because too many files have changed in this diff Show More