language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
wireshark/tools/pidl/wscript | #!/usr/bin/env python
import os, Logs
from samba_utils import MODE_755
# This function checks if a perl module is installed on the system.
def check_system_perl_module(conf, module, version=None):
bundle_name = module.replace('::', '_')
module_check = module
# Create module string with version
if version:
module_check = module + ' ' + str(version)
# Check if we have to bundle it.
if conf.LIB_MUST_BE_BUNDLED(bundle_name.lower()):
return False
# Check for system perl module
if not conf.check_perl_module(module_check):
return False
conf.define('USING_SYSTEM_%s' % bundle_name.upper(), 1)
return True
def set_options(opt):
return
def configure(conf):
# Check if perl(Parse::Yapp::Driver) is available.
check_system_perl_module(conf, "Parse::Yapp::Driver", 1.05)
# we need a recent version of MakeMaker to get the right man page names
if conf.CHECK_PERL_MANPAGE():
conf.env.PERLMAN1EXT = conf.CHECK_PERL_MANPAGE(section='1')
conf.env.PERLMAN3EXT = conf.CHECK_PERL_MANPAGE(section='3')
conf.DEFINE('HAVE_PERL_MAKEMAKER', 1)
# yapp is used for building the parser
conf.find_program('yapp', var='YAPP')
conf.find_program('pod2man', var='POD2MAN')
def build(bld):
bld.INSTALL_FILES('${BINDIR}', 'pidl', chmod=MODE_755, perl_fixup=True)
bld.RECURSE('lib')
if not bld.CONFIG_SET('HAVE_PERL_MAKEMAKER'):
return
pidl_manpages = {
'pidl': 'man1/pidl.${PERLMAN1EXT}',
'lib/Parse/Pidl/NDR.pm': 'man3/Parse::Pidl::NDR.${PERLMAN3EXT}',
'lib/Parse/Pidl/Wireshark/Conformance.pm': 'man3/Parse::Pidl::Wireshark::Conformance.${PERLMAN3EXT}',
'lib/Parse/Pidl/Dump.pm': 'man3/Parse::Pidl::Dump.${PERLMAN3EXT}',
'lib/Parse/Pidl/Util.pm': 'man3/Parse::Pidl::Util.${PERLMAN3EXT}',
'lib/Parse/Pidl/Wireshark/NDR.pm': 'man3/Parse::Pidl::Wireshark::NDR.${PERLMAN3EXT}'
}
for k, v in pidl_manpages.iteritems():
pidl_manpages[k] = bld.EXPAND_VARIABLES(v)
# use perl to build the manpages
bld.env.pidl_srcdir = os.path.join(bld.srcnode.abspath(), 'pidl')
bld.SET_BUILD_GROUP('final')
if 'POD2MAN' in bld.env and bld.env['POD2MAN'] != '':
for src, manpage in pidl_manpages.iteritems():
bld(rule='${POD2MAN} -c "Samba Documentation" ${SRC} ${TGT}',
shell=True,
source=src,
install_path=os.path.dirname(bld.EXPAND_VARIABLES('${MANDIR}/'+manpage)),
target=os.path.basename(manpage))
# we want to prefer the git version of the parsers if we can.
# Only if the source has changed do we want to re-run yapp
# But we force the developer to use the pidl standalone build
# to regenerate the files.
# TODO: only warn in developer mode and if 'git diff HEAD'
# shows a difference
warn_about_grammar_changes = ('PIDL_BUILD_WARNINGS' in bld.env and (
bld.IS_NEWER('idl.yp', 'lib/Parse/Pidl/IDL.pm') or
bld.IS_NEWER('expr.yp', 'lib/Parse/Pidl/Expr.pm')))
if warn_about_grammar_changes:
Logs.warn('''
Pidl grammar files have changed. Please use the pidl standalone build
to regenerate them with yapp.
$ cd ../pidl
$ perl Makefile.PL
$ make lib/Parse/Pidl/IDL.pm lib/Parse/Pidl/Expr.pm
$ git add lib/Parse/Pidl/IDL.pm lib/Parse/Pidl/Expr.pm
$ git commit
$ cd -
If your 100% sure you haven't changed idl.yp and expr.yp
try this to avoid this message:
$ touch ../pidl/lib/Parse/Pidl/IDL.pm ../pidl/lib/Parse/Pidl/Expr.pm
''') |
|
wireshark/tools/pidl/lib/wscript_build | #!/usr/bin/env python
# install the pidl modules
bld.INSTALL_FILES(bld.env.PERL_LIB_INSTALL_DIR,
'''
Parse/Pidl.pm
Parse/Pidl/Samba4.pm
Parse/Pidl/CUtil.pm
Parse/Pidl/Expr.pm
Parse/Pidl/Wireshark/Conformance.pm
Parse/Pidl/Wireshark/NDR.pm
Parse/Pidl/ODL.pm
Parse/Pidl/Dump.pm
Parse/Pidl/Util.pm
Parse/Pidl/Samba4/Header.pm
Parse/Pidl/Samba4/COM/Header.pm
Parse/Pidl/Samba4/COM/Proxy.pm
Parse/Pidl/Samba4/COM/Stub.pm
Parse/Pidl/Samba4/TDR.pm
Parse/Pidl/Samba4/NDR/Server.pm
Parse/Pidl/Samba4/NDR/Client.pm
Parse/Pidl/Samba4/NDR/Parser.pm
Parse/Pidl/Samba4/Python.pm
Parse/Pidl/Samba4/Template.pm
Parse/Pidl/IDL.pm
Parse/Pidl/Typelist.pm
Parse/Pidl/Samba3/ClientNDR.pm
Parse/Pidl/Samba3/ServerNDR.pm
Parse/Pidl/Compat.pm
Parse/Pidl/NDR.pm
''',
flat=False)
if not bld.CONFIG_SET('USING_SYSTEM_PARSE_YAPP_DRIVER'):
bld.INSTALL_FILES(bld.env.PERL_LIB_INSTALL_DIR,
'Parse/Yapp/Driver.pm',
flat=False) |
|
wireshark/tools/pidl/lib/Parse/Pidl.pm | ###################################################
# package to parse IDL files and generate code for
# rpc functions in Samba
# Copyright [email protected] 2000-2003
# Copyright [email protected] 2005
# released under the GNU GPL
package Parse::Pidl;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(warning error fatal $VERSION);
use strict;
use vars qw ( $VERSION );
$VERSION = '0.02';
sub warning
{
my ($l,$m) = @_;
if ($l) {
print STDERR "$l->{FILE}:$l->{LINE}: ";
}
print STDERR "warning: $m\n";
}
sub error
{
my ($l,$m) = @_;
if ($l) {
print STDERR "$l->{FILE}:$l->{LINE}: ";
}
print STDERR "error: $m\n";
}
sub fatal($$)
{
my ($e,$s) = @_;
die("$e->{FILE}:$e->{LINE}: $s\n");
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Compat.pm | ###################################################
# IDL Compatibility checker
# Copyright [email protected] 2005
# released under the GNU GPL
package Parse::Pidl::Compat;
use Parse::Pidl qw(warning);
use Parse::Pidl::Util qw(has_property);
use strict;
use vars qw($VERSION);
$VERSION = '0.01';
my %supported_properties = (
# interface
"helpstring" => ["INTERFACE", "FUNCTION"],
"version" => ["INTERFACE"],
"uuid" => ["INTERFACE"],
"endpoint" => ["INTERFACE"],
"pointer_default" => ["INTERFACE"],
"no_srv_register" => ["INTERFACE"],
# dcom
"object" => ["INTERFACE"],
"local" => ["INTERFACE", "FUNCTION"],
"iid_is" => ["ELEMENT"],
"call_as" => ["FUNCTION"],
"idempotent" => ["FUNCTION"],
# function
"in" => ["ELEMENT"],
"out" => ["ELEMENT"],
# pointer
"ref" => ["ELEMENT"],
"ptr" => ["ELEMENT"],
"unique" => ["ELEMENT"],
"ignore" => ["ELEMENT"],
"value" => ["ELEMENT"],
# generic
"public" => ["FUNCTION", "TYPEDEF"],
"nopush" => ["FUNCTION", "TYPEDEF"],
"nopull" => ["FUNCTION", "TYPEDEF"],
"noprint" => ["FUNCTION", "TYPEDEF"],
"nopython" => ["FUNCTION", "TYPEDEF"],
# union
"switch_is" => ["ELEMENT"],
"switch_type" => ["ELEMENT", "TYPEDEF"],
"case" => ["ELEMENT"],
"default" => ["ELEMENT"],
# subcontext
"subcontext" => ["ELEMENT"],
"subcontext_size" => ["ELEMENT"],
# enum
"enum16bit" => ["TYPEDEF"],
"v1_enum" => ["TYPEDEF"],
# bitmap
"bitmap8bit" => ["TYPEDEF"],
"bitmap16bit" => ["TYPEDEF"],
"bitmap32bit" => ["TYPEDEF"],
"bitmap64bit" => ["TYPEDEF"],
# array
"range" => ["ELEMENT"],
"size_is" => ["ELEMENT"],
"string" => ["ELEMENT"],
"noheader" => ["ELEMENT"],
"charset" => ["ELEMENT"],
"length_is" => ["ELEMENT"],
);
sub CheckTypedef($)
{
my ($td) = @_;
if (has_property($td, "nodiscriminant")) {
warning($td, "nodiscriminant property not supported");
}
if ($td->{TYPE} eq "BITMAP") {
warning($td, "converting bitmap to scalar");
#FIXME
}
if (has_property($td, "gensize")) {
warning($td, "ignoring gensize() property. ");
}
if (has_property($td, "enum8bit") and has_property($td, "enum16bit")) {
warning($td, "8 and 16 bit enums not supported, converting to scalar");
#FIXME
}
StripProperties($td);
}
sub CheckElement($)
{
my $e = shift;
if (has_property($e, "noheader")) {
warning($e, "noheader property not supported");
return;
}
if (has_property($e, "subcontext")) {
warning($e, "converting subcontext to byte array");
#FIXME
}
if (has_property($e, "compression")) {
warning($e, "compression() property not supported");
}
if (has_property($e, "sptr")) {
warning($e, "sptr() pointer property not supported");
}
if (has_property($e, "relative")) {
warning($e, "relative() pointer property not supported");
}
if (has_property($e, "relative_short")) {
warning($e, "relative_short() pointer property not supported");
}
if (has_property($e, "flag")) {
warning($e, "ignoring flag() property");
}
if (has_property($e, "value")) {
warning($e, "ignoring value() property");
}
}
sub CheckFunction($)
{
my $fn = shift;
if (has_property($fn, "noopnum")) {
warning($fn, "noopnum not converted. Opcodes will be out of sync.");
}
}
sub CheckInterface($)
{
my $if = shift;
}
sub Check($)
{
my $pidl = shift;
my $nidl = [];
foreach (@{$pidl}) {
push (@$nidl, CheckInterface($_)) if ($_->{TYPE} eq "INTERFACE");
}
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/CUtil.pm | ###################################################
# C utility functions for pidl
# Copyright [email protected] 2005-2007
# released under the GNU GPL
package Parse::Pidl::CUtil;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(get_pointer_to get_value_of get_array_element);
use vars qw($VERSION);
$VERSION = '0.01';
use strict;
sub get_pointer_to($)
{
my $var_name = shift;
if ($var_name =~ /^\*(.*)$/) {
return $1;
} elsif ($var_name =~ /^\&(.*)$/) {
return "&($var_name)";
} else {
return "&$var_name";
}
}
sub get_value_of($)
{
my $var_name = shift;
if ($var_name =~ /^\&(.*)$/) {
return $1;
} else {
return "*$var_name";
}
}
sub get_array_element($$)
{
my ($var_name, $idx) = @_;
if ($var_name =~ /^\*.*$/) {
$var_name = "($var_name)";
} elsif ($var_name =~ /^\&.*$/) {
$var_name = "($var_name)";
}
return "$var_name"."[$idx]";
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Dump.pm | ###################################################
# dump function for IDL structures
# Copyright [email protected] 2000
# Copyright [email protected] 2005
# released under the GNU GPL
=pod
=head1 NAME
Parse::Pidl::Dump - Dump support
=head1 DESCRIPTION
This module provides functions that can generate IDL code from
internal pidl data structures.
=cut
package Parse::Pidl::Dump;
use Exporter;
use vars qw($VERSION);
$VERSION = '0.01';
@ISA = qw(Exporter);
@EXPORT_OK = qw(DumpType DumpTypedef DumpStruct DumpEnum DumpBitmap DumpUnion DumpFunction);
use strict;
use Parse::Pidl::Util qw(has_property);
my($res);
#####################################################################
# dump a properties list
sub DumpProperties($)
{
my($props) = shift;
my $res = "";
foreach my $d ($props) {
foreach my $k (sort(keys %{$d})) {
if ($k eq "in") {
$res .= "[in] ";
next;
}
if ($k eq "out") {
$res .= "[out] ";
next;
}
if ($k eq "ref") {
$res .= "[ref] ";
next;
}
$res .= "[$k($d->{$k})] ";
}
}
return $res;
}
#####################################################################
# dump a structure element
sub DumpElement($)
{
my($element) = shift;
my $res = "";
(defined $element->{PROPERTIES}) &&
($res .= DumpProperties($element->{PROPERTIES}));
$res .= DumpType($element->{TYPE});
$res .= " ";
for my $i (1..$element->{POINTERS}) {
$res .= "*";
}
$res .= "$element->{NAME}";
foreach (@{$element->{ARRAY_LEN}}) {
$res .= "[$_]";
}
return $res;
}
#####################################################################
# dump a struct
sub DumpStruct($)
{
my($struct) = shift;
my($res);
$res .= "struct ";
if ($struct->{NAME}) {
$res.="$struct->{NAME} ";
}
$res.="{\n";
if (defined $struct->{ELEMENTS}) {
foreach (@{$struct->{ELEMENTS}}) {
$res .= "\t" . DumpElement($_) . ";\n";
}
}
$res .= "}";
return $res;
}
#####################################################################
# dump a struct
sub DumpEnum($)
{
my($enum) = shift;
my($res);
$res .= "enum {\n";
foreach (@{$enum->{ELEMENTS}}) {
if (/^([A-Za-z0-9_]+)[ \t]*\((.*)\)$/) {
$res .= "\t$1 = $2,\n";
} else {
$res .= "\t$_,\n";
}
}
$res.= "}";
return $res;
}
#####################################################################
# dump a struct
sub DumpBitmap($)
{
my($bitmap) = shift;
my($res);
$res .= "bitmap {\n";
foreach (@{$bitmap->{ELEMENTS}}) {
if (/^([A-Za-z0-9_]+)[ \t]*\((.*)\)$/) {
$res .= "\t$1 = $2,\n";
} else {
die ("Bitmap $bitmap->{NAME} has field $_ without proper value");
}
}
$res.= "}";
return $res;
}
#####################################################################
# dump a union element
sub DumpUnionElement($)
{
my($element) = shift;
my($res);
if (has_property($element, "default")) {
$res .= "[default] ;\n";
} else {
$res .= "[case($element->{PROPERTIES}->{case})] ";
$res .= DumpElement($element), if defined($element);
$res .= ";\n";
}
return $res;
}
#####################################################################
# dump a union
sub DumpUnion($)
{
my($union) = shift;
my($res);
(defined $union->{PROPERTIES}) &&
($res .= DumpProperties($union->{PROPERTIES}));
$res .= "union {\n";
foreach my $e (@{$union->{ELEMENTS}}) {
$res .= DumpUnionElement($e);
}
$res .= "}";
return $res;
}
#####################################################################
# dump a type
sub DumpType($)
{
my($data) = shift;
if (ref($data) eq "HASH") {
return DumpStruct($data) if ($data->{TYPE} eq "STRUCT");
return DumpUnion($data) if ($data->{TYPE} eq "UNION");
return DumpEnum($data) if ($data->{TYPE} eq "ENUM");
return DumpBitmap($data) if ($data->{TYPE} eq "BITMAP");
} else {
return $data;
}
}
#####################################################################
# dump a typedef
sub DumpTypedef($)
{
my($typedef) = shift;
my($res);
$res .= "typedef ";
$res .= DumpType($typedef->{DATA});
$res .= " $typedef->{NAME};\n\n";
return $res;
}
#####################################################################
# dump a typedef
sub DumpFunction($)
{
my($function) = shift;
my($first) = 1;
my($res);
$res .= DumpType($function->{RETURN_TYPE});
$res .= " $function->{NAME}(\n";
for my $d (@{$function->{ELEMENTS}}) {
unless ($first) { $res .= ",\n"; } $first = 0;
$res .= DumpElement($d);
}
$res .= "\n);\n\n";
return $res;
}
#####################################################################
# dump a module header
sub DumpInterfaceProperties($)
{
my($header) = shift;
my($data) = $header->{DATA};
my($first) = 1;
my($res);
$res .= "[\n";
foreach my $k (sort(keys %{$data})) {
$first || ($res .= ",\n"); $first = 0;
$res .= "$k($data->{$k})";
}
$res .= "\n]\n";
return $res;
}
#####################################################################
# dump the interface definitions
sub DumpInterface($)
{
my($interface) = shift;
my($data) = $interface->{DATA};
my($res);
$res .= DumpInterfaceProperties($interface->{PROPERTIES});
$res .= "interface $interface->{NAME}\n{\n";
foreach my $d (@{$data}) {
($d->{TYPE} eq "TYPEDEF") &&
($res .= DumpTypedef($d));
($d->{TYPE} eq "FUNCTION") &&
($res .= DumpFunction($d));
}
$res .= "}\n";
return $res;
}
#####################################################################
# dump a parsed IDL structure back into an IDL file
sub Dump($)
{
my($idl) = shift;
my($res);
$res = "/* Dumped by pidl */\n\n";
foreach my $x (@{$idl}) {
($x->{TYPE} eq "INTERFACE") &&
($res .= DumpInterface($x));
}
return $res;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Expr.pm | ####################################################################
#
# This file was generated using Parse::Yapp version 1.05.
#
# Don't edit this file, use source file instead.
#
# ANY CHANGE MADE HERE WILL BE LOST !
#
####################################################################
package Parse::Pidl::Expr;
use vars qw ( @ISA );
use strict;
@ISA= qw ( Parse::Yapp::Driver );
use Parse::Yapp::Driver;
sub new {
my($class)=shift;
ref($class)
and $class=ref($class);
my($self)=$class->SUPER::new( yyversion => '1.05',
yystates =>
[
{#State 0
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'NUM' => 5,
'TEXT' => 6,
"(" => 7,
"!" => 8,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 2,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 1
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"(" => 7,
"!" => 8,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 14,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 2
ACTIONS => {
'' => 16,
"-" => 15,
"<" => 17,
"+" => 18,
"%" => 19,
"==" => 20,
"^" => 21,
"*" => 22,
">>" => 23,
"!=" => 24,
"?" => 25,
"||" => 26,
"&&" => 27,
"&" => 28,
"/" => 29,
"|" => 30,
"<<" => 32,
"=>" => 31,
"<=" => 33,
">" => 34
}
},
{#State 3
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 35,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 4
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 36,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 5
DEFAULT => -1
},
{#State 6
DEFAULT => -2
},
{#State 7
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 38,
'var' => 37,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 8
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 39,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 9
ACTIONS => {
"*" => 9,
'VAR' => 41
},
GOTOS => {
'possible_pointer' => 40
}
},
{#State 10
ACTIONS => {
"(" => 42
},
DEFAULT => -30
},
{#State 11
ACTIONS => {
"->" => 43,
"." => 44
},
DEFAULT => -4
},
{#State 12
DEFAULT => -3
},
{#State 13
DEFAULT => -32
},
{#State 14
ACTIONS => {
"^" => 21,
"=>" => 31,
"<=" => 33
},
DEFAULT => -26
},
{#State 15
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 45,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 16
DEFAULT => 0
},
{#State 17
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 46,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 18
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 47,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 19
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 48,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 20
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 49,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 21
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 50,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 22
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 51,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 23
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 52,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 24
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 53,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 25
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 54,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 26
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 55,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 27
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 56,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 28
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 57,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 29
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 58,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 30
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 59,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 31
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 60,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 32
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 61,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 33
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 62,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 34
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 63,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 35
ACTIONS => {
"^" => 21,
"=>" => 31,
"<=" => 33
},
DEFAULT => -5
},
{#State 36
ACTIONS => {
"^" => 21,
"=>" => 31,
"<=" => 33
},
DEFAULT => -27
},
{#State 37
ACTIONS => {
")" => 64,
"->" => 43,
"." => 44
},
DEFAULT => -4
},
{#State 38
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"%" => 19,
"==" => 20,
"^" => 21,
"*" => 22,
")" => 65,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"/" => 29,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
}
},
{#State 39
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"%" => 19,
"==" => 20,
"^" => 21,
"*" => 22,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"/" => 29,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -24
},
{#State 40
DEFAULT => -31
},
{#State 41
DEFAULT => -30
},
{#State 42
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
DEFAULT => -37,
GOTOS => {
'exp' => 69,
'var' => 11,
'args' => 66,
'func' => 12,
'opt_args' => 70,
'exp_or_possible_pointer' => 67,
'possible_pointer' => 68
}
},
{#State 43
ACTIONS => {
'VAR' => 71
}
},
{#State 44
ACTIONS => {
'VAR' => 72
}
},
{#State 45
ACTIONS => {
"<" => 17,
"==" => 20,
"^" => 21,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -7
},
{#State 46
ACTIONS => {
"==" => 20,
"^" => 21,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<=" => 33
},
DEFAULT => -10
},
{#State 47
ACTIONS => {
"<" => 17,
"==" => 20,
"^" => 21,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -6
},
{#State 48
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"==" => 20,
"^" => 21,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -9
},
{#State 49
ACTIONS => {
"^" => 21,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<=" => 33
},
DEFAULT => -13
},
{#State 50
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"%" => 19,
"==" => 20,
"^" => 21,
"*" => 22,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"/" => 29,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -28
},
{#State 51
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"==" => 20,
"^" => 21,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -8
},
{#State 52
ACTIONS => {
"<" => 17,
"==" => 20,
"^" => 21,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<=" => 33,
">" => 34
},
DEFAULT => -17
},
{#State 53
ACTIONS => {
"^" => 21,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<=" => 33
},
DEFAULT => -18
},
{#State 54
ACTIONS => {
":" => 73,
"-" => 15,
"<" => 17,
"+" => 18,
"%" => 19,
"==" => 20,
"^" => 21,
"*" => 22,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"/" => 29,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
}
},
{#State 55
ACTIONS => {
"^" => 21,
"?" => 25,
"=>" => 31,
"<=" => 33
},
DEFAULT => -19
},
{#State 56
ACTIONS => {
"^" => 21,
"?" => 25,
"||" => 26,
"=>" => 31,
"<=" => 33
},
DEFAULT => -20
},
{#State 57
ACTIONS => {
"^" => 21,
"?" => 25,
"&&" => 27,
"||" => 26,
"|" => 30,
"=>" => 31,
"<=" => 33
},
DEFAULT => -21
},
{#State 58
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"==" => 20,
"^" => 21,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -25
},
{#State 59
ACTIONS => {
"^" => 21,
"?" => 25,
"&&" => 27,
"||" => 26,
"=>" => 31,
"<=" => 33
},
DEFAULT => -12
},
{#State 60
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"%" => 19,
"==" => 20,
"^" => 21,
"*" => 22,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"/" => 29,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -15
},
{#State 61
ACTIONS => {
"<" => 17,
"==" => 20,
"^" => 21,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<=" => 33,
">" => 34
},
DEFAULT => -16
},
{#State 62
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"%" => 19,
"==" => 20,
"^" => 21,
"*" => 22,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"/" => 29,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -14
},
{#State 63
ACTIONS => {
"==" => 20,
"^" => 21,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"|" => 30,
"=>" => 31,
"<=" => 33
},
DEFAULT => -11
},
{#State 64
DEFAULT => -34
},
{#State 65
DEFAULT => -29
},
{#State 66
DEFAULT => -38
},
{#State 67
ACTIONS => {
"," => 74
},
DEFAULT => -41
},
{#State 68
DEFAULT => -32
},
{#State 69
ACTIONS => {
"-" => 15,
"<" => 17,
"+" => 18,
"%" => 19,
"==" => 20,
"^" => 21,
"*" => 22,
">>" => 23,
"!=" => 24,
"?" => 25,
"&&" => 27,
"||" => 26,
"&" => 28,
"/" => 29,
"|" => 30,
"=>" => 31,
"<<" => 32,
"<=" => 33,
">" => 34
},
DEFAULT => -39
},
{#State 70
ACTIONS => {
")" => 75
}
},
{#State 71
DEFAULT => -35
},
{#State 72
DEFAULT => -33
},
{#State 73
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 76,
'var' => 11,
'func' => 12,
'possible_pointer' => 13
}
},
{#State 74
ACTIONS => {
"-" => 1,
"~" => 3,
"&" => 4,
'TEXT' => 6,
'NUM' => 5,
"!" => 8,
"(" => 7,
"*" => 9,
'VAR' => 10
},
GOTOS => {
'exp' => 69,
'var' => 11,
'args' => 77,
'func' => 12,
'exp_or_possible_pointer' => 67,
'possible_pointer' => 68
}
},
{#State 75
DEFAULT => -36
},
{#State 76
ACTIONS => {
"^" => 21,
"=>" => 31,
"<=" => 33
},
DEFAULT => -22
},
{#State 77
DEFAULT => -42
}
],
yyrules =>
[
[#Rule 0
'$start', 2, undef
],
[#Rule 1
'exp', 1, undef
],
[#Rule 2
'exp', 1,
sub
#line 24 "expr.yp"
{ "\"$_[1]\"" }
],
[#Rule 3
'exp', 1, undef
],
[#Rule 4
'exp', 1, undef
],
[#Rule 5
'exp', 2,
sub
#line 30 "expr.yp"
{ "~$_[2]" }
],
[#Rule 6
'exp', 3,
sub
#line 32 "expr.yp"
{ "$_[1] + $_[3]" }
],
[#Rule 7
'exp', 3,
sub
#line 34 "expr.yp"
{ "$_[1] - $_[3]" }
],
[#Rule 8
'exp', 3,
sub
#line 36 "expr.yp"
{ "$_[1] * $_[3]" }
],
[#Rule 9
'exp', 3,
sub
#line 38 "expr.yp"
{ "$_[1] % $_[3]" }
],
[#Rule 10
'exp', 3,
sub
#line 40 "expr.yp"
{ "$_[1] < $_[3]" }
],
[#Rule 11
'exp', 3,
sub
#line 42 "expr.yp"
{ "$_[1] > $_[3]" }
],
[#Rule 12
'exp', 3,
sub
#line 44 "expr.yp"
{ "$_[1] | $_[3]" }
],
[#Rule 13
'exp', 3,
sub
#line 46 "expr.yp"
{ "$_[1] == $_[3]" }
],
[#Rule 14
'exp', 3,
sub
#line 48 "expr.yp"
{ "$_[1] <= $_[3]" }
],
[#Rule 15
'exp', 3,
sub
#line 50 "expr.yp"
{ "$_[1] => $_[3]" }
],
[#Rule 16
'exp', 3,
sub
#line 52 "expr.yp"
{ "$_[1] << $_[3]" }
],
[#Rule 17
'exp', 3,
sub
#line 54 "expr.yp"
{ "$_[1] >> $_[3]" }
],
[#Rule 18
'exp', 3,
sub
#line 56 "expr.yp"
{ "$_[1] != $_[3]" }
],
[#Rule 19
'exp', 3,
sub
#line 58 "expr.yp"
{ "$_[1] || $_[3]" }
],
[#Rule 20
'exp', 3,
sub
#line 60 "expr.yp"
{ "$_[1] && $_[3]" }
],
[#Rule 21
'exp', 3,
sub
#line 62 "expr.yp"
{ "$_[1] & $_[3]" }
],
[#Rule 22
'exp', 5,
sub
#line 64 "expr.yp"
{ "$_[1]?$_[3]:$_[5]" }
],
[#Rule 23
'exp', 2,
sub
#line 66 "expr.yp"
{ "~$_[1]" }
],
[#Rule 24
'exp', 2,
sub
#line 68 "expr.yp"
{ "not $_[1]" }
],
[#Rule 25
'exp', 3,
sub
#line 70 "expr.yp"
{ "$_[1] / $_[3]" }
],
[#Rule 26
'exp', 2,
sub
#line 72 "expr.yp"
{ "-$_[2]" }
],
[#Rule 27
'exp', 2,
sub
#line 74 "expr.yp"
{ "&$_[2]" }
],
[#Rule 28
'exp', 3,
sub
#line 76 "expr.yp"
{ "$_[1]^$_[3]" }
],
[#Rule 29
'exp', 3,
sub
#line 78 "expr.yp"
{ "($_[2])" }
],
[#Rule 30
'possible_pointer', 1,
sub
#line 82 "expr.yp"
{ $_[0]->_Lookup($_[1]) }
],
[#Rule 31
'possible_pointer', 2,
sub
#line 84 "expr.yp"
{ $_[0]->_Dereference($_[2]); "*$_[2]" }
],
[#Rule 32
'var', 1,
sub
#line 88 "expr.yp"
{ $_[0]->_Use($_[1]) }
],
[#Rule 33
'var', 3,
sub
#line 90 "expr.yp"
{ $_[0]->_Use("$_[1].$_[3]") }
],
[#Rule 34
'var', 3,
sub
#line 92 "expr.yp"
{ "($_[2])" }
],
[#Rule 35
'var', 3,
sub
#line 94 "expr.yp"
{ $_[0]->_Use("*$_[1]"); $_[1]."->".$_[3] }
],
[#Rule 36
'func', 4,
sub
#line 99 "expr.yp"
{ "$_[1]($_[3])" }
],
[#Rule 37
'opt_args', 0,
sub
#line 104 "expr.yp"
{ "" }
],
[#Rule 38
'opt_args', 1, undef
],
[#Rule 39
'exp_or_possible_pointer', 1, undef
],
[#Rule 40
'exp_or_possible_pointer', 1, undef
],
[#Rule 41
'args', 1, undef
],
[#Rule 42
'args', 3,
sub
#line 118 "expr.yp"
{ "$_[1], $_[3]" }
]
],
@_);
bless($self,$class);
}
#line 121 "expr.yp"
package Parse::Pidl::Expr;
sub _Lexer {
my($parser)=shift;
$parser->YYData->{INPUT}=~s/^[ \t]//;
for ($parser->YYData->{INPUT}) {
if (s/^(0x[0-9A-Fa-f]+)//) {
$parser->YYData->{LAST_TOKEN} = $1;
return('NUM',$1);
}
if (s/^([0-9]+(?:\.[0-9]+)?)//) {
$parser->YYData->{LAST_TOKEN} = $1;
return('NUM',$1);
}
if (s/^([A-Za-z_][A-Za-z0-9_]*)//) {
$parser->YYData->{LAST_TOKEN} = $1;
return('VAR',$1);
}
if (s/^\"(.*?)\"//) {
$parser->YYData->{LAST_TOKEN} = $1;
return('TEXT',$1);
}
if (s/^(==|!=|<=|>=|->|\|\||<<|>>|&&)//s) {
$parser->YYData->{LAST_TOKEN} = $1;
return($1,$1);
}
if (s/^(.)//s) {
$parser->YYData->{LAST_TOKEN} = $1;
return($1,$1);
}
}
}
sub _Use($$)
{
my ($self, $x) = @_;
if (defined($self->YYData->{USE})) {
return $self->YYData->{USE}->($x);
}
return $x;
}
sub _Lookup($$)
{
my ($self, $x) = @_;
return $self->YYData->{LOOKUP}->($x);
}
sub _Dereference($$)
{
my ($self, $x) = @_;
if (defined($self->YYData->{DEREFERENCE})) {
$self->YYData->{DEREFERENCE}->($x);
}
}
sub _Error($)
{
my ($self) = @_;
if (defined($self->YYData->{LAST_TOKEN})) {
$self->YYData->{ERROR}->("Parse error in `".$self->YYData->{FULL_INPUT}."' near `". $self->YYData->{LAST_TOKEN} . "'");
} else {
$self->YYData->{ERROR}->("Parse error in `".$self->YYData->{FULL_INPUT}."'");
}
}
sub Run {
my($self, $data, $error, $lookup, $deref, $use) = @_;
$self->YYData->{FULL_INPUT} = $data;
$self->YYData->{INPUT} = $data;
$self->YYData->{LOOKUP} = $lookup;
$self->YYData->{DEREFERENCE} = $deref;
$self->YYData->{ERROR} = $error;
$self->YYData->{USE} = $use;
return $self->YYParse( yylex => \&_Lexer, yyerror => \&_Error);
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/IDL.pm | ####################################################################
#
# This file was generated using Parse::Yapp version 1.05.
#
# Don't edit this file, use source file instead.
#
# ANY CHANGE MADE HERE WILL BE LOST !
#
####################################################################
package Parse::Pidl::IDL;
use vars qw ( @ISA );
use strict;
@ISA= qw ( Parse::Yapp::Driver );
use Parse::Yapp::Driver;
sub new {
my($class)=shift;
ref($class)
and $class=ref($class);
my($self)=$class->SUPER::new( yyversion => '1.05',
yystates =>
[
{#State 0
DEFAULT => -1,
GOTOS => {
'idl' => 1
}
},
{#State 1
ACTIONS => {
'' => 2,
"cpp_quote" => 3,
"importlib" => 4,
"import" => 7,
"include" => 13
},
DEFAULT => -89,
GOTOS => {
'cpp_quote' => 11,
'importlib' => 10,
'interface' => 9,
'include' => 5,
'coclass' => 12,
'import' => 8,
'property_list' => 6
}
},
{#State 2
DEFAULT => 0
},
{#State 3
ACTIONS => {
"(" => 14
}
},
{#State 4
ACTIONS => {
'TEXT' => 16
},
GOTOS => {
'commalist' => 15,
'text' => 17
}
},
{#State 5
DEFAULT => -5
},
{#State 6
ACTIONS => {
"coclass" => 18,
"[" => 20,
"interface" => 19
}
},
{#State 7
ACTIONS => {
'TEXT' => 16
},
GOTOS => {
'commalist' => 21,
'text' => 17
}
},
{#State 8
DEFAULT => -4
},
{#State 9
DEFAULT => -2
},
{#State 10
DEFAULT => -6
},
{#State 11
DEFAULT => -7
},
{#State 12
DEFAULT => -3
},
{#State 13
ACTIONS => {
'TEXT' => 16
},
GOTOS => {
'commalist' => 22,
'text' => 17
}
},
{#State 14
ACTIONS => {
'TEXT' => 16
},
GOTOS => {
'text' => 23
}
},
{#State 15
ACTIONS => {
";" => 24,
"," => 25
}
},
{#State 16
DEFAULT => -120
},
{#State 17
DEFAULT => -11
},
{#State 18
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 27
}
},
{#State 19
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 28
}
},
{#State 20
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 30,
'property' => 31,
'properties' => 29
}
},
{#State 21
ACTIONS => {
";" => 32,
"," => 25
}
},
{#State 22
ACTIONS => {
";" => 33,
"," => 25
}
},
{#State 23
ACTIONS => {
")" => 34
}
},
{#State 24
DEFAULT => -10
},
{#State 25
ACTIONS => {
'TEXT' => 16
},
GOTOS => {
'text' => 35
}
},
{#State 26
DEFAULT => -116
},
{#State 27
ACTIONS => {
"{" => 36
}
},
{#State 28
ACTIONS => {
":" => 37
},
DEFAULT => -17,
GOTOS => {
'base_interface' => 38
}
},
{#State 29
ACTIONS => {
"," => 39,
"]" => 40
}
},
{#State 30
ACTIONS => {
"(" => 41
},
DEFAULT => -93
},
{#State 31
DEFAULT => -91
},
{#State 32
DEFAULT => -8
},
{#State 33
DEFAULT => -9
},
{#State 34
DEFAULT => -19
},
{#State 35
DEFAULT => -12
},
{#State 36
DEFAULT => -14,
GOTOS => {
'interface_names' => 42
}
},
{#State 37
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 43
}
},
{#State 38
ACTIONS => {
"{" => 44
}
},
{#State 39
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 30,
'property' => 45
}
},
{#State 40
DEFAULT => -90
},
{#State 41
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'text' => 51,
'anytext' => 46,
'constant' => 47,
'commalisttext' => 49
}
},
{#State 42
ACTIONS => {
"}" => 52,
"interface" => 53
}
},
{#State 43
DEFAULT => -18
},
{#State 44
ACTIONS => {
"const" => 64
},
DEFAULT => -89,
GOTOS => {
'typedecl' => 54,
'function' => 55,
'pipe' => 56,
'definitions' => 58,
'bitmap' => 57,
'definition' => 61,
'property_list' => 60,
'usertype' => 59,
'const' => 63,
'struct' => 62,
'typedef' => 66,
'enum' => 65,
'union' => 67
}
},
{#State 45
DEFAULT => -92
},
{#State 46
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -95
},
{#State 47
DEFAULT => -99
},
{#State 48
DEFAULT => -119
},
{#State 49
ACTIONS => {
"," => 83,
")" => 84
}
},
{#State 50
DEFAULT => -98
},
{#State 51
DEFAULT => -100
},
{#State 52
ACTIONS => {
";" => 86
},
DEFAULT => -121,
GOTOS => {
'optional_semicolon' => 85
}
},
{#State 53
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 87
}
},
{#State 54
DEFAULT => -25
},
{#State 55
DEFAULT => -22
},
{#State 56
DEFAULT => -34
},
{#State 57
DEFAULT => -33
},
{#State 58
ACTIONS => {
"}" => 88,
"const" => 64
},
DEFAULT => -89,
GOTOS => {
'typedecl' => 54,
'function' => 55,
'pipe' => 56,
'bitmap' => 57,
'definition' => 89,
'property_list' => 60,
'usertype' => 59,
'const' => 63,
'struct' => 62,
'typedef' => 66,
'enum' => 65,
'union' => 67
}
},
{#State 59
ACTIONS => {
";" => 90
}
},
{#State 60
ACTIONS => {
"typedef" => 91,
'IDENTIFIER' => 26,
"signed" => 100,
"union" => 92,
"enum" => 101,
"bitmap" => 102,
'void' => 93,
"pipe" => 103,
"unsigned" => 104,
"[" => 20,
"struct" => 98
},
GOTOS => {
'existingtype' => 99,
'pipe' => 56,
'bitmap' => 57,
'usertype' => 95,
'property_list' => 94,
'identifier' => 96,
'struct' => 62,
'enum' => 65,
'type' => 105,
'union' => 67,
'sign' => 97
}
},
{#State 61
DEFAULT => -20
},
{#State 62
DEFAULT => -30
},
{#State 63
DEFAULT => -23
},
{#State 64
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 106
}
},
{#State 65
DEFAULT => -32
},
{#State 66
DEFAULT => -24
},
{#State 67
DEFAULT => -31
},
{#State 68
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 107,
'text' => 51,
'constant' => 47
}
},
{#State 69
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 108,
'text' => 51,
'constant' => 47
}
},
{#State 70
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 109,
'text' => 51,
'constant' => 47
}
},
{#State 71
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 110,
'text' => 51,
'constant' => 47
}
},
{#State 72
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 111,
'text' => 51,
'constant' => 47
}
},
{#State 73
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 112,
'text' => 51,
'constant' => 47
}
},
{#State 74
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 46,
'text' => 51,
'constant' => 47,
'commalisttext' => 113
}
},
{#State 75
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 114,
'text' => 51,
'constant' => 47
}
},
{#State 76
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 115,
'text' => 51,
'constant' => 47
}
},
{#State 77
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 116,
'text' => 51,
'constant' => 47
}
},
{#State 78
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 46,
'text' => 51,
'constant' => 47,
'commalisttext' => 117
}
},
{#State 79
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 118,
'text' => 51,
'constant' => 47
}
},
{#State 80
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 119,
'text' => 51,
'constant' => 47
}
},
{#State 81
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 120,
'text' => 51,
'constant' => 47
}
},
{#State 82
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 121,
'text' => 51,
'constant' => 47
}
},
{#State 83
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 122,
'text' => 51,
'constant' => 47
}
},
{#State 84
DEFAULT => -94
},
{#State 85
DEFAULT => -13
},
{#State 86
DEFAULT => -122
},
{#State 87
ACTIONS => {
";" => 123
}
},
{#State 88
ACTIONS => {
";" => 86
},
DEFAULT => -121,
GOTOS => {
'optional_semicolon' => 124
}
},
{#State 89
DEFAULT => -21
},
{#State 90
DEFAULT => -35
},
{#State 91
ACTIONS => {
'IDENTIFIER' => 26,
"signed" => 100,
'void' => 93,
"unsigned" => 104
},
DEFAULT => -89,
GOTOS => {
'existingtype' => 99,
'pipe' => 56,
'bitmap' => 57,
'usertype' => 95,
'property_list' => 94,
'identifier' => 96,
'struct' => 62,
'enum' => 65,
'type' => 125,
'union' => 67,
'sign' => 97
}
},
{#State 92
ACTIONS => {
'IDENTIFIER' => 126
},
DEFAULT => -117,
GOTOS => {
'optional_identifier' => 127
}
},
{#State 93
DEFAULT => -42
},
{#State 94
ACTIONS => {
"pipe" => 103,
"union" => 92,
"enum" => 101,
"bitmap" => 102,
"[" => 20,
"struct" => 98
}
},
{#State 95
DEFAULT => -40
},
{#State 96
DEFAULT => -39
},
{#State 97
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 128
}
},
{#State 98
ACTIONS => {
'IDENTIFIER' => 126
},
DEFAULT => -117,
GOTOS => {
'optional_identifier' => 129
}
},
{#State 99
DEFAULT => -41
},
{#State 100
DEFAULT => -36
},
{#State 101
ACTIONS => {
'IDENTIFIER' => 126
},
DEFAULT => -117,
GOTOS => {
'optional_identifier' => 130
}
},
{#State 102
ACTIONS => {
'IDENTIFIER' => 126
},
DEFAULT => -117,
GOTOS => {
'optional_identifier' => 131
}
},
{#State 103
ACTIONS => {
'IDENTIFIER' => 26,
"signed" => 100,
'void' => 93,
"unsigned" => 104
},
DEFAULT => -89,
GOTOS => {
'existingtype' => 99,
'pipe' => 56,
'bitmap' => 57,
'usertype' => 95,
'property_list' => 94,
'identifier' => 96,
'struct' => 62,
'enum' => 65,
'type' => 132,
'union' => 67,
'sign' => 97
}
},
{#State 104
DEFAULT => -37
},
{#State 105
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 133
}
},
{#State 106
DEFAULT => -75,
GOTOS => {
'pointers' => 134
}
},
{#State 107
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -110
},
{#State 108
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -101
},
{#State 109
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -109
},
{#State 110
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -105
},
{#State 111
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -113
},
{#State 112
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -112
},
{#State 113
ACTIONS => {
"}" => 135,
"," => 83
}
},
{#State 114
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -107
},
{#State 115
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -108
},
{#State 116
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -111
},
{#State 117
ACTIONS => {
"," => 83,
")" => 136
}
},
{#State 118
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -106
},
{#State 119
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -103
},
{#State 120
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -102
},
{#State 121
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -104
},
{#State 122
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -96
},
{#State 123
DEFAULT => -15
},
{#State 124
DEFAULT => -16
},
{#State 125
DEFAULT => -75,
GOTOS => {
'pointers' => 137
}
},
{#State 126
DEFAULT => -118
},
{#State 127
ACTIONS => {
"{" => 139
},
DEFAULT => -71,
GOTOS => {
'union_body' => 140,
'opt_union_body' => 138
}
},
{#State 128
DEFAULT => -38
},
{#State 129
ACTIONS => {
"{" => 142
},
DEFAULT => -61,
GOTOS => {
'struct_body' => 141,
'opt_struct_body' => 143
}
},
{#State 130
ACTIONS => {
"{" => 144
},
DEFAULT => -44,
GOTOS => {
'opt_enum_body' => 146,
'enum_body' => 145
}
},
{#State 131
ACTIONS => {
"{" => 148
},
DEFAULT => -52,
GOTOS => {
'bitmap_body' => 149,
'opt_bitmap_body' => 147
}
},
{#State 132
DEFAULT => -77
},
{#State 133
ACTIONS => {
"(" => 150
}
},
{#State 134
ACTIONS => {
'IDENTIFIER' => 26,
"*" => 152
},
GOTOS => {
'identifier' => 151
}
},
{#State 135
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 153,
'text' => 51,
'constant' => 47
}
},
{#State 136
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 154,
'text' => 51,
'constant' => 47
}
},
{#State 137
ACTIONS => {
'IDENTIFIER' => 26,
"*" => 152
},
GOTOS => {
'identifier' => 155
}
},
{#State 138
DEFAULT => -73
},
{#State 139
DEFAULT => -68,
GOTOS => {
'union_elements' => 156
}
},
{#State 140
DEFAULT => -72
},
{#State 141
DEFAULT => -62
},
{#State 142
DEFAULT => -78,
GOTOS => {
'element_list1' => 157
}
},
{#State 143
DEFAULT => -63
},
{#State 144
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 158,
'enum_element' => 159,
'enum_elements' => 160
}
},
{#State 145
DEFAULT => -45
},
{#State 146
DEFAULT => -46
},
{#State 147
DEFAULT => -54
},
{#State 148
ACTIONS => {
'IDENTIFIER' => 26
},
DEFAULT => -57,
GOTOS => {
'identifier' => 163,
'bitmap_element' => 162,
'bitmap_elements' => 161,
'opt_bitmap_elements' => 164
}
},
{#State 149
DEFAULT => -53
},
{#State 150
ACTIONS => {
"," => -82,
"void" => 168,
"const" => 166,
")" => -82
},
DEFAULT => -80,
GOTOS => {
'optional_const' => 165,
'element_list2' => 167
}
},
{#State 151
ACTIONS => {
"[" => 169,
"=" => 171
},
GOTOS => {
'array_len' => 170
}
},
{#State 152
DEFAULT => -76
},
{#State 153
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -115
},
{#State 154
ACTIONS => {
":" => 68,
"<" => 71,
"~" => 72,
"?" => 70,
"{" => 74,
"=" => 77
},
DEFAULT => -114
},
{#State 155
ACTIONS => {
"[" => 169
},
DEFAULT => -86,
GOTOS => {
'array_len' => 172
}
},
{#State 156
ACTIONS => {
"}" => 173
},
DEFAULT => -89,
GOTOS => {
'optional_base_element' => 175,
'property_list' => 174
}
},
{#State 157
ACTIONS => {
"}" => 176
},
DEFAULT => -89,
GOTOS => {
'base_element' => 177,
'property_list' => 178
}
},
{#State 158
ACTIONS => {
"=" => 179
},
DEFAULT => -49
},
{#State 159
DEFAULT => -47
},
{#State 160
ACTIONS => {
"}" => 180,
"," => 181
}
},
{#State 161
ACTIONS => {
"," => 182
},
DEFAULT => -58
},
{#State 162
DEFAULT => -55
},
{#State 163
ACTIONS => {
"=" => 183
}
},
{#State 164
ACTIONS => {
"}" => 184
}
},
{#State 165
DEFAULT => -89,
GOTOS => {
'base_element' => 185,
'property_list' => 178
}
},
{#State 166
DEFAULT => -81
},
{#State 167
ACTIONS => {
"," => 186,
")" => 187
}
},
{#State 168
DEFAULT => -83
},
{#State 169
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
"]" => 188,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 189,
'text' => 51,
'constant' => 47
}
},
{#State 170
ACTIONS => {
"=" => 190
}
},
{#State 171
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 191,
'text' => 51,
'constant' => 47
}
},
{#State 172
ACTIONS => {
";" => 192
}
},
{#State 173
DEFAULT => -70
},
{#State 174
ACTIONS => {
"[" => 20
},
DEFAULT => -89,
GOTOS => {
'base_or_empty' => 193,
'base_element' => 194,
'empty_element' => 195,
'property_list' => 196
}
},
{#State 175
DEFAULT => -69
},
{#State 176
DEFAULT => -60
},
{#State 177
ACTIONS => {
";" => 197
}
},
{#State 178
ACTIONS => {
'IDENTIFIER' => 26,
"signed" => 100,
'void' => 93,
"unsigned" => 104,
"[" => 20
},
DEFAULT => -89,
GOTOS => {
'existingtype' => 99,
'pipe' => 56,
'bitmap' => 57,
'usertype' => 95,
'property_list' => 94,
'identifier' => 96,
'struct' => 62,
'enum' => 65,
'type' => 198,
'union' => 67,
'sign' => 97
}
},
{#State 179
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 199,
'text' => 51,
'constant' => 47
}
},
{#State 180
DEFAULT => -43
},
{#State 181
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 158,
'enum_element' => 200
}
},
{#State 182
ACTIONS => {
'IDENTIFIER' => 26
},
GOTOS => {
'identifier' => 163,
'bitmap_element' => 201
}
},
{#State 183
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 202,
'text' => 51,
'constant' => 47
}
},
{#State 184
DEFAULT => -51
},
{#State 185
DEFAULT => -84
},
{#State 186
ACTIONS => {
"const" => 166
},
DEFAULT => -80,
GOTOS => {
'optional_const' => 203
}
},
{#State 187
ACTIONS => {
";" => 204
}
},
{#State 188
ACTIONS => {
"[" => 169
},
DEFAULT => -86,
GOTOS => {
'array_len' => 205
}
},
{#State 189
ACTIONS => {
"-" => 69,
":" => 68,
"?" => 70,
"<" => 71,
"+" => 73,
"~" => 72,
"&" => 75,
"{" => 74,
"/" => 76,
"=" => 77,
"|" => 79,
"(" => 78,
"*" => 80,
"." => 81,
"]" => 206,
">" => 82
}
},
{#State 190
ACTIONS => {
'CONSTANT' => 48,
'TEXT' => 16,
'IDENTIFIER' => 26
},
DEFAULT => -97,
GOTOS => {
'identifier' => 50,
'anytext' => 207,
'text' => 51,
'constant' => 47
}
},
{#State 191
ACTIONS => {
"-" => 69,
":" => 68,
"?" => 70,
"<" => 71,
";" => 208,
"+" => 73,
"~" => 72,
"&" => 75,
"{" => 74,
"/" => 76,
"=" => 77,
"|" => 79,
"(" => 78,
"*" => 80,
"." => 81,
">" => 82
}
},
{#State 192
DEFAULT => -29
},
{#State 193
DEFAULT => -67
},
{#State 194
ACTIONS => {
";" => 209
}
},
{#State 195
DEFAULT => -66
},
{#State 196
ACTIONS => {
'IDENTIFIER' => 26,
"signed" => 100,
";" => 210,
'void' => 93,
"unsigned" => 104,
"[" => 20
},
DEFAULT => -89,
GOTOS => {
'existingtype' => 99,
'pipe' => 56,
'bitmap' => 57,
'usertype' => 95,
'property_list' => 94,
'identifier' => 96,
'struct' => 62,
'enum' => 65,
'type' => 198,
'union' => 67,
'sign' => 97
}
},
{#State 197
DEFAULT => -79
},
{#State 198
DEFAULT => -75,
GOTOS => {
'pointers' => 211
}
},
{#State 199
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -50
},
{#State 200
DEFAULT => -48
},
{#State 201
DEFAULT => -56
},
{#State 202
ACTIONS => {
"-" => 69,
":" => 68,
"<" => 71,
"+" => 73,
"~" => 72,
"*" => 80,
"?" => 70,
"{" => 74,
"&" => 75,
"/" => 76,
"=" => 77,
"(" => 78,
"|" => 79,
"." => 81,
">" => 82
},
DEFAULT => -59
},
{#State 203
DEFAULT => -89,
GOTOS => {
'base_element' => 212,
'property_list' => 178
}
},
{#State 204
DEFAULT => -28
},
{#State 205
DEFAULT => -87
},
{#State 206
ACTIONS => {
"[" => 169
},
DEFAULT => -86,
GOTOS => {
'array_len' => 213
}
},
{#State 207
ACTIONS => {
"-" => 69,
":" => 68,
"?" => 70,
"<" => 71,
";" => 214,
"+" => 73,
"~" => 72,
"&" => 75,
"{" => 74,
"/" => 76,
"=" => 77,
"|" => 79,
"(" => 78,
"*" => 80,
"." => 81,
">" => 82
}
},
{#State 208
DEFAULT => -26
},
{#State 209
DEFAULT => -65
},
{#State 210
DEFAULT => -64
},
{#State 211
ACTIONS => {
'IDENTIFIER' => 26,
"*" => 152
},
GOTOS => {
'identifier' => 215
}
},
{#State 212
DEFAULT => -85
},
{#State 213
DEFAULT => -88
},
{#State 214
DEFAULT => -27
},
{#State 215
ACTIONS => {
"[" => 169
},
DEFAULT => -86,
GOTOS => {
'array_len' => 216
}
},
{#State 216
DEFAULT => -74
}
],
yyrules =>
[
[#Rule 0
'$start', 2, undef
],
[#Rule 1
'idl', 0, undef
],
[#Rule 2
'idl', 2,
sub
#line 20 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 3
'idl', 2,
sub
#line 22 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 4
'idl', 2,
sub
#line 24 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 5
'idl', 2,
sub
#line 26 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 6
'idl', 2,
sub
#line 28 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 7
'idl', 2,
sub
#line 30 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 8
'import', 3,
sub
#line 35 "idl.yp"
{{
"TYPE" => "IMPORT",
"PATHS" => $_[2],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 9
'include', 3,
sub
#line 45 "idl.yp"
{{
"TYPE" => "INCLUDE",
"PATHS" => $_[2],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 10
'importlib', 3,
sub
#line 55 "idl.yp"
{{
"TYPE" => "IMPORTLIB",
"PATHS" => $_[2],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 11
'commalist', 1,
sub
#line 64 "idl.yp"
{ [ $_[1] ] }
],
[#Rule 12
'commalist', 3,
sub
#line 66 "idl.yp"
{ push(@{$_[1]}, $_[3]); $_[1] }
],
[#Rule 13
'coclass', 7,
sub
#line 71 "idl.yp"
{{
"TYPE" => "COCLASS",
"PROPERTIES" => $_[1],
"NAME" => $_[3],
"DATA" => $_[5],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 14
'interface_names', 0, undef
],
[#Rule 15
'interface_names', 4,
sub
#line 84 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 16
'interface', 8,
sub
#line 89 "idl.yp"
{{
"TYPE" => "INTERFACE",
"PROPERTIES" => $_[1],
"NAME" => $_[3],
"BASE" => $_[4],
"DATA" => $_[6],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 17
'base_interface', 0, undef
],
[#Rule 18
'base_interface', 2,
sub
#line 103 "idl.yp"
{ $_[2] }
],
[#Rule 19
'cpp_quote', 4,
sub
#line 109 "idl.yp"
{{
"TYPE" => "CPP_QUOTE",
"DATA" => $_[3],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 20
'definitions', 1,
sub
#line 118 "idl.yp"
{ [ $_[1] ] }
],
[#Rule 21
'definitions', 2,
sub
#line 120 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 22
'definition', 1, undef
],
[#Rule 23
'definition', 1, undef
],
[#Rule 24
'definition', 1, undef
],
[#Rule 25
'definition', 1, undef
],
[#Rule 26
'const', 7,
sub
#line 135 "idl.yp"
{{
"TYPE" => "CONST",
"DTYPE" => $_[2],
"POINTERS" => $_[3],
"NAME" => $_[4],
"VALUE" => $_[6],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 27
'const', 8,
sub
#line 146 "idl.yp"
{{
"TYPE" => "CONST",
"DTYPE" => $_[2],
"POINTERS" => $_[3],
"NAME" => $_[4],
"ARRAY_LEN" => $_[5],
"VALUE" => $_[7],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 28
'function', 7,
sub
#line 160 "idl.yp"
{{
"TYPE" => "FUNCTION",
"NAME" => $_[3],
"RETURN_TYPE" => $_[2],
"PROPERTIES" => $_[1],
"ELEMENTS" => $_[5],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 29
'typedef', 7,
sub
#line 173 "idl.yp"
{{
"TYPE" => "TYPEDEF",
"PROPERTIES" => $_[1],
"NAME" => $_[5],
"DATA" => $_[3],
"POINTERS" => $_[4],
"ARRAY_LEN" => $_[6],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 30
'usertype', 1, undef
],
[#Rule 31
'usertype', 1, undef
],
[#Rule 32
'usertype', 1, undef
],
[#Rule 33
'usertype', 1, undef
],
[#Rule 34
'usertype', 1, undef
],
[#Rule 35
'typedecl', 2,
sub
#line 198 "idl.yp"
{ $_[1] }
],
[#Rule 36
'sign', 1, undef
],
[#Rule 37
'sign', 1, undef
],
[#Rule 38
'existingtype', 2,
sub
#line 208 "idl.yp"
{ ($_[1]?$_[1]:"signed") ." $_[2]" }
],
[#Rule 39
'existingtype', 1, undef
],
[#Rule 40
'type', 1, undef
],
[#Rule 41
'type', 1, undef
],
[#Rule 42
'type', 1,
sub
#line 218 "idl.yp"
{ "void" }
],
[#Rule 43
'enum_body', 3,
sub
#line 222 "idl.yp"
{ $_[2] }
],
[#Rule 44
'opt_enum_body', 0, undef
],
[#Rule 45
'opt_enum_body', 1, undef
],
[#Rule 46
'enum', 4,
sub
#line 233 "idl.yp"
{{
"TYPE" => "ENUM",
"PROPERTIES" => $_[1],
"NAME" => $_[3],
"ELEMENTS" => $_[4],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 47
'enum_elements', 1,
sub
#line 244 "idl.yp"
{ [ $_[1] ] }
],
[#Rule 48
'enum_elements', 3,
sub
#line 246 "idl.yp"
{ push(@{$_[1]}, $_[3]); $_[1] }
],
[#Rule 49
'enum_element', 1, undef
],
[#Rule 50
'enum_element', 3,
sub
#line 252 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 51
'bitmap_body', 3,
sub
#line 256 "idl.yp"
{ $_[2] }
],
[#Rule 52
'opt_bitmap_body', 0, undef
],
[#Rule 53
'opt_bitmap_body', 1, undef
],
[#Rule 54
'bitmap', 4,
sub
#line 267 "idl.yp"
{{
"TYPE" => "BITMAP",
"PROPERTIES" => $_[1],
"NAME" => $_[3],
"ELEMENTS" => $_[4],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 55
'bitmap_elements', 1,
sub
#line 278 "idl.yp"
{ [ $_[1] ] }
],
[#Rule 56
'bitmap_elements', 3,
sub
#line 280 "idl.yp"
{ push(@{$_[1]}, $_[3]); $_[1] }
],
[#Rule 57
'opt_bitmap_elements', 0, undef
],
[#Rule 58
'opt_bitmap_elements', 1, undef
],
[#Rule 59
'bitmap_element', 3,
sub
#line 290 "idl.yp"
{ "$_[1] ( $_[3] )" }
],
[#Rule 60
'struct_body', 3,
sub
#line 294 "idl.yp"
{ $_[2] }
],
[#Rule 61
'opt_struct_body', 0, undef
],
[#Rule 62
'opt_struct_body', 1, undef
],
[#Rule 63
'struct', 4,
sub
#line 305 "idl.yp"
{{
"TYPE" => "STRUCT",
"PROPERTIES" => $_[1],
"NAME" => $_[3],
"ELEMENTS" => $_[4],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 64
'empty_element', 2,
sub
#line 317 "idl.yp"
{{
"NAME" => "",
"TYPE" => "EMPTY",
"PROPERTIES" => $_[1],
"POINTERS" => 0,
"ARRAY_LEN" => [],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 65
'base_or_empty', 2, undef
],
[#Rule 66
'base_or_empty', 1, undef
],
[#Rule 67
'optional_base_element', 2,
sub
#line 334 "idl.yp"
{ $_[2]->{PROPERTIES} = FlattenHash([$_[1],$_[2]->{PROPERTIES}]); $_[2] }
],
[#Rule 68
'union_elements', 0, undef
],
[#Rule 69
'union_elements', 2,
sub
#line 340 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 70
'union_body', 3,
sub
#line 344 "idl.yp"
{ $_[2] }
],
[#Rule 71
'opt_union_body', 0, undef
],
[#Rule 72
'opt_union_body', 1, undef
],
[#Rule 73
'union', 4,
sub
#line 355 "idl.yp"
{{
"TYPE" => "UNION",
"PROPERTIES" => $_[1],
"NAME" => $_[3],
"ELEMENTS" => $_[4],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 74
'base_element', 5,
sub
#line 367 "idl.yp"
{{
"NAME" => $_[4],
"TYPE" => $_[2],
"PROPERTIES" => $_[1],
"POINTERS" => $_[3],
"ARRAY_LEN" => $_[5],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 75
'pointers', 0,
sub
#line 380 "idl.yp"
{ 0 }
],
[#Rule 76
'pointers', 2,
sub
#line 382 "idl.yp"
{ $_[1]+1 }
],
[#Rule 77
'pipe', 3,
sub
#line 387 "idl.yp"
{{
"TYPE" => "PIPE",
"PROPERTIES" => $_[1],
"NAME" => undef,
"DATA" => {
"TYPE" => "STRUCT",
"PROPERTIES" => $_[1],
"NAME" => undef,
"ELEMENTS" => [{
"NAME" => "count",
"PROPERTIES" => $_[1],
"POINTERS" => 0,
"ARRAY_LEN" => [],
"TYPE" => "uint3264",
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
},{
"NAME" => "array",
"PROPERTIES" => $_[1],
"POINTERS" => 0,
"ARRAY_LEN" => [ "count" ],
"TYPE" => $_[3],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}],
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
},
"FILE" => $_[0]->YYData->{FILE},
"LINE" => $_[0]->YYData->{LINE},
}}
],
[#Rule 78
'element_list1', 0,
sub
#line 422 "idl.yp"
{ [] }
],
[#Rule 79
'element_list1', 3,
sub
#line 424 "idl.yp"
{ push(@{$_[1]}, $_[2]); $_[1] }
],
[#Rule 80
'optional_const', 0, undef
],
[#Rule 81
'optional_const', 1, undef
],
[#Rule 82
'element_list2', 0, undef
],
[#Rule 83
'element_list2', 1, undef
],
[#Rule 84
'element_list2', 2,
sub
#line 438 "idl.yp"
{ [ $_[2] ] }
],
[#Rule 85
'element_list2', 4,
sub
#line 440 "idl.yp"
{ push(@{$_[1]}, $_[4]); $_[1] }
],
[#Rule 86
'array_len', 0, undef
],
[#Rule 87
'array_len', 3,
sub
#line 446 "idl.yp"
{ push(@{$_[3]}, "*"); $_[3] }
],
[#Rule 88
'array_len', 4,
sub
#line 448 "idl.yp"
{ push(@{$_[4]}, "$_[2]"); $_[4] }
],
[#Rule 89
'property_list', 0, undef
],
[#Rule 90
'property_list', 4,
sub
#line 454 "idl.yp"
{ FlattenHash([$_[1],$_[3]]); }
],
[#Rule 91
'properties', 1,
sub
#line 458 "idl.yp"
{ $_[1] }
],
[#Rule 92
'properties', 3,
sub
#line 460 "idl.yp"
{ FlattenHash([$_[1], $_[3]]); }
],
[#Rule 93
'property', 1,
sub
#line 464 "idl.yp"
{{ "$_[1]" => "1" }}
],
[#Rule 94
'property', 4,
sub
#line 466 "idl.yp"
{{ "$_[1]" => "$_[3]" }}
],
[#Rule 95
'commalisttext', 1, undef
],
[#Rule 96
'commalisttext', 3,
sub
#line 472 "idl.yp"
{ "$_[1],$_[3]" }
],
[#Rule 97
'anytext', 0,
sub
#line 477 "idl.yp"
{ "" }
],
[#Rule 98
'anytext', 1, undef
],
[#Rule 99
'anytext', 1, undef
],
[#Rule 100
'anytext', 1, undef
],
[#Rule 101
'anytext', 3,
sub
#line 485 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 102
'anytext', 3,
sub
#line 487 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 103
'anytext', 3,
sub
#line 489 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 104
'anytext', 3,
sub
#line 491 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 105
'anytext', 3,
sub
#line 493 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 106
'anytext', 3,
sub
#line 495 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 107
'anytext', 3,
sub
#line 497 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 108
'anytext', 3,
sub
#line 499 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 109
'anytext', 3,
sub
#line 501 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 110
'anytext', 3,
sub
#line 503 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 111
'anytext', 3,
sub
#line 505 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 112
'anytext', 3,
sub
#line 507 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 113
'anytext', 3,
sub
#line 509 "idl.yp"
{ "$_[1]$_[2]$_[3]" }
],
[#Rule 114
'anytext', 5,
sub
#line 511 "idl.yp"
{ "$_[1]$_[2]$_[3]$_[4]$_[5]" }
],
[#Rule 115
'anytext', 5,
sub
#line 513 "idl.yp"
{ "$_[1]$_[2]$_[3]$_[4]$_[5]" }
],
[#Rule 116
'identifier', 1, undef
],
[#Rule 117
'optional_identifier', 0, undef
],
[#Rule 118
'optional_identifier', 1, undef
],
[#Rule 119
'constant', 1, undef
],
[#Rule 120
'text', 1,
sub
#line 531 "idl.yp"
{ "\"$_[1]\"" }
],
[#Rule 121
'optional_semicolon', 0, undef
],
[#Rule 122
'optional_semicolon', 1, undef
]
],
@_);
bless($self,$class);
}
#line 543 "idl.yp"
use Parse::Pidl qw(error);
#####################################################################
# flatten an array of hashes into a single hash
sub FlattenHash($)
{
my $a = shift;
my %b;
for my $d (@{$a}) {
for my $k (keys %{$d}) {
$b{$k} = $d->{$k};
}
}
return \%b;
}
#####################################################################
# traverse a perl data structure removing any empty arrays or
# hashes and any hash elements that map to undef
sub CleanData($)
{
sub CleanData($);
my($v) = shift;
return undef if (not defined($v));
if (ref($v) eq "ARRAY") {
foreach my $i (0 .. $#{$v}) {
CleanData($v->[$i]);
}
# this removes any undefined elements from the array
@{$v} = grep { defined $_ } @{$v};
} elsif (ref($v) eq "HASH") {
foreach my $x (keys %{$v}) {
CleanData($v->{$x});
if (!defined $v->{$x}) {
delete($v->{$x});
next;
}
}
}
return $v;
}
sub _Error {
if (exists $_[0]->YYData->{ERRMSG}) {
error($_[0]->YYData, $_[0]->YYData->{ERRMSG});
delete $_[0]->YYData->{ERRMSG};
return;
}
my $last_token = $_[0]->YYData->{LAST_TOKEN};
error($_[0]->YYData, "Syntax error near '$last_token'");
}
sub _Lexer($)
{
my($parser)=shift;
$parser->YYData->{INPUT} or return('',undef);
again:
$parser->YYData->{INPUT} =~ s/^[ \t]*//;
for ($parser->YYData->{INPUT}) {
if (/^\#/) {
# Linemarker format is described at
# http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html
if (s/^\# (\d+) \"(.*?)\"(( \d+){1,4}|)//) {
$parser->YYData->{LINE} = $1-1;
$parser->YYData->{FILE} = $2;
goto again;
}
if (s/^\#line (\d+) \"(.*?)\"( \d+|)//) {
$parser->YYData->{LINE} = $1-1;
$parser->YYData->{FILE} = $2;
goto again;
}
if (s/^(\#.*)$//m) {
goto again;
}
}
if (s/^(\n)//) {
$parser->YYData->{LINE}++;
goto again;
}
if (s/^\"(.*?)\"//) {
$parser->YYData->{LAST_TOKEN} = $1;
return('TEXT',$1);
}
if (s/^(\d+)(\W|$)/$2/) {
$parser->YYData->{LAST_TOKEN} = $1;
return('CONSTANT',$1);
}
if (s/^([\w_]+)//) {
$parser->YYData->{LAST_TOKEN} = $1;
if ($1 =~
/^(coclass|interface|import|importlib
|include|cpp_quote|typedef
|union|struct|enum|bitmap|pipe
|void|const|unsigned|signed)$/x) {
return $1;
}
return('IDENTIFIER',$1);
}
if (s/^(.)//s) {
$parser->YYData->{LAST_TOKEN} = $1;
return($1,$1);
}
}
}
sub parse_string
{
my ($data,$filename) = @_;
my $self = new Parse::Pidl::IDL;
$self->YYData->{FILE} = $filename;
$self->YYData->{INPUT} = $data;
$self->YYData->{LINE} = 0;
$self->YYData->{LAST_TOKEN} = "NONE";
my $idl = $self->YYParse( yylex => \&_Lexer, yyerror => \&_Error );
return CleanData($idl);
}
sub parse_file($$)
{
my ($filename,$incdirs) = @_;
my $saved_delim = $/;
undef $/;
my $cpp = $ENV{CPP};
my $options = "";
if (! defined $cpp) {
if (defined $ENV{CC}) {
$cpp = "$ENV{CC}";
$options = "-E";
} else {
$cpp = "cpp";
}
}
my $includes = join('',map { " -I$_" } @$incdirs);
my $data = `$cpp $options -D__PIDL__$includes -xc "$filename"`;
$/ = $saved_delim;
return parse_string($data, $filename);
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/NDR.pm | ###################################################
# Samba4 NDR info tree generator
# Copyright [email protected] 2000-2003
# Copyright [email protected] 2001
# Copyright [email protected] 2004-2006
# released under the GNU GPL
=pod
=head1 NAME
Parse::Pidl::NDR - NDR parsing information generator
=head1 DESCRIPTION
Return a table describing the order in which the parts of an element
should be parsed
Possible level types:
- POINTER
- ARRAY
- SUBCONTEXT
- SWITCH
- DATA
=head1 AUTHOR
Jelmer Vernooij <[email protected]>
=cut
package Parse::Pidl::NDR;
require Exporter;
use vars qw($VERSION);
$VERSION = '0.01';
@ISA = qw(Exporter);
@EXPORT = qw(GetPrevLevel GetNextLevel ContainsDeferred ContainsPipe ContainsString);
@EXPORT_OK = qw(GetElementLevelTable ParseElement ReturnTypeElement ValidElement align_type mapToScalar ParseType can_contain_deferred is_charset_array);
use strict;
use Parse::Pidl qw(warning fatal);
use Parse::Pidl::Typelist qw(hasType getType typeIs expandAlias mapScalarType is_fixed_size_scalar);
use Parse::Pidl::Util qw(has_property property_matches);
# Alignment of the built-in scalar types
my $scalar_alignment = {
'void' => 0,
'char' => 1,
'int8' => 1,
'uint8' => 1,
'int16' => 2,
'uint16' => 2,
'int1632' => 3,
'uint1632' => 3,
'int32' => 4,
'uint32' => 4,
'int3264' => 5,
'uint3264' => 5,
'hyper' => 8,
'double' => 8,
'pointer' => 8,
'dlong' => 4,
'udlong' => 4,
'udlongr' => 4,
'DATA_BLOB' => 4,
'string' => 4,
'string_array' => 4, #???
'time_t' => 4,
'uid_t' => 8,
'gid_t' => 8,
'NTTIME' => 4,
'NTTIME_1sec' => 4,
'NTTIME_hyper' => 8,
'WERROR' => 4,
'NTSTATUS' => 4,
'COMRESULT' => 4,
'dns_string' => 4,
'nbt_string' => 4,
'wrepl_nbt_name' => 4,
'ipv4address' => 4,
'ipv6address' => 4, #16?
'dnsp_name' => 1,
'dnsp_string' => 1
};
sub GetElementLevelTable($$$)
{
my ($e, $pointer_default, $ms_union) = @_;
my $order = [];
my $is_deferred = 0;
my @bracket_array = ();
my @length_is = ();
my @size_is = ();
my $pointer_idx = 0;
if (has_property($e, "size_is")) {
@size_is = split /,/, has_property($e, "size_is");
}
if (has_property($e, "length_is")) {
@length_is = split /,/, has_property($e, "length_is");
}
if (defined($e->{ARRAY_LEN})) {
@bracket_array = @{$e->{ARRAY_LEN}};
}
if (has_property($e, "out")) {
my $needptrs = 1;
if (has_property($e, "string") and not has_property($e, "in")) { $needptrs++; }
if ($#bracket_array >= 0) { $needptrs = 0; }
warning($e, "[out] argument `$e->{NAME}' not a pointer") if ($needptrs > $e->{POINTERS});
}
my $allow_pipe = ($e->{PARENT}->{TYPE} eq "FUNCTION");
my $is_pipe = typeIs($e->{TYPE}, "PIPE");
if ($is_pipe) {
if (not $allow_pipe) {
fatal($e, "argument `$e->{NAME}' is a pipe and not allowed on $e->{PARENT}->{TYPE}");
}
if ($e->{POINTERS} > 1) {
fatal($e, "$e->{POINTERS} are not allowed on pipe element $e->{NAME}");
}
if ($e->{POINTERS} < 0) {
fatal($e, "pipe element $e->{NAME} needs pointer");
}
if ($e->{POINTERS} == 1 and pointer_type($e) ne "ref") {
fatal($e, "pointer should be 'ref' on pipe element $e->{NAME}");
}
if (scalar(@size_is) > 0) {
fatal($e, "size_is() on pipe element");
}
if (scalar(@length_is) > 0) {
fatal($e, "length_is() on pipe element");
}
if (scalar(@bracket_array) > 0) {
fatal($e, "brackets on pipe element");
}
if (defined(has_property($e, "subcontext"))) {
fatal($e, "subcontext on pipe element");
}
if (has_property($e, "switch_is")) {
fatal($e, "switch_is on pipe element");
}
if (can_contain_deferred($e->{TYPE})) {
fatal($e, "$e->{TYPE} can_contain_deferred - not allowed on pipe element");
}
}
# Parse the [][][][] style array stuff
for my $i (0 .. $#bracket_array) {
my $d = $bracket_array[$#bracket_array - $i];
my $size = $d;
my $length = $d;
my $is_surrounding = 0;
my $is_varying = 0;
my $is_conformant = 0;
my $is_string = 0;
my $is_fixed = 0;
my $is_inline = 0;
my $is_to_null = 0;
if ($d eq "*") {
$is_conformant = 1;
if ($size = shift @size_is) {
if ($e->{POINTERS} < 1 and has_property($e, "string")) {
$is_string = 1;
delete($e->{PROPERTIES}->{string});
}
} elsif ((scalar(@size_is) == 0) and has_property($e, "string")) {
$is_string = 1;
delete($e->{PROPERTIES}->{string});
} else {
fatal($e, "Must specify size_is() for conformant array!")
}
if (($length = shift @length_is) or $is_string) {
$is_varying = 1;
} else {
$length = $size;
}
if ($e == $e->{PARENT}->{ELEMENTS}[-1]
and $e->{PARENT}->{TYPE} ne "FUNCTION") {
$is_surrounding = 1;
}
}
$is_fixed = 1 if (not $is_conformant and Parse::Pidl::Util::is_constant($size));
$is_inline = 1 if (not $is_conformant and not Parse::Pidl::Util::is_constant($size));
if ($i == 0 and $is_fixed and has_property($e, "string")) {
$is_fixed = 0;
$is_varying = 1;
$is_string = 1;
delete($e->{PROPERTIES}->{string});
}
if (has_property($e, "to_null")) {
$is_to_null = 1;
}
push (@$order, {
TYPE => "ARRAY",
SIZE_IS => $size,
LENGTH_IS => $length,
IS_DEFERRED => $is_deferred,
IS_SURROUNDING => $is_surrounding,
IS_ZERO_TERMINATED => $is_string,
IS_VARYING => $is_varying,
IS_CONFORMANT => $is_conformant,
IS_FIXED => $is_fixed,
IS_INLINE => $is_inline,
IS_TO_NULL => $is_to_null
});
}
# Next, all the pointers
foreach my $i (1..$e->{POINTERS}) {
my $level = "EMBEDDED";
# Top level "ref" pointers do not have a referrent identifier
$level = "TOP" if ($i == 1 and $e->{PARENT}->{TYPE} eq "FUNCTION");
my $pt;
#
# Only the first level gets the pointer type from the
# pointer property, the others get them from
# the pointer_default() interface property
#
# see http://msdn2.microsoft.com/en-us/library/aa378984(VS.85).aspx
# (Here they talk about the rightmost pointer, but testing shows
# they mean the leftmost pointer.)
#
# --metze
#
$pt = pointer_type($e);
if ($i > 1) {
$is_deferred = 1 if ($pt ne "ref" and $e->{PARENT}->{TYPE} eq "FUNCTION");
$pt = $pointer_default;
}
push (@$order, {
TYPE => "POINTER",
POINTER_TYPE => $pt,
POINTER_INDEX => $pointer_idx,
IS_DEFERRED => "$is_deferred",
LEVEL => $level
});
warning($e, "top-level \[out\] pointer `$e->{NAME}' is not a \[ref\] pointer")
if ($i == 1 and $pt ne "ref" and
$e->{PARENT}->{TYPE} eq "FUNCTION" and
not has_property($e, "in"));
$pointer_idx++;
# everything that follows will be deferred
$is_deferred = 1 if ($level ne "TOP");
my $array_size = shift @size_is;
my $array_length;
my $is_varying;
my $is_conformant;
my $is_string = 0;
if ($array_size) {
$is_conformant = 1;
if ($array_length = shift @length_is) {
$is_varying = 1;
} else {
$array_length = $array_size;
$is_varying =0;
}
}
if (scalar(@size_is) == 0 and has_property($e, "string") and
$i == $e->{POINTERS}) {
$is_string = 1;
$is_varying = $is_conformant = has_property($e, "noheader")?0:1;
delete($e->{PROPERTIES}->{string});
}
if ($array_size or $is_string) {
push (@$order, {
TYPE => "ARRAY",
SIZE_IS => $array_size,
LENGTH_IS => $array_length,
IS_DEFERRED => $is_deferred,
IS_SURROUNDING => 0,
IS_ZERO_TERMINATED => $is_string,
IS_VARYING => $is_varying,
IS_CONFORMANT => $is_conformant,
IS_FIXED => 0,
IS_INLINE => 0
});
$is_deferred = 0;
}
}
if ($is_pipe) {
push (@$order, {
TYPE => "PIPE",
IS_DEFERRED => 0,
CONTAINS_DEFERRED => 0,
});
my $i = 0;
foreach (@$order) { $_->{LEVEL_INDEX} = $i; $i+=1; }
return $order;
}
if (defined(has_property($e, "subcontext"))) {
my $hdr_size = has_property($e, "subcontext");
my $subsize = has_property($e, "subcontext_size");
if (not defined($subsize)) {
$subsize = -1;
}
push (@$order, {
TYPE => "SUBCONTEXT",
HEADER_SIZE => $hdr_size,
SUBCONTEXT_SIZE => $subsize,
IS_DEFERRED => $is_deferred,
COMPRESSION => has_property($e, "compression"),
});
}
if (my $switch = has_property($e, "switch_is")) {
push (@$order, {
TYPE => "SWITCH",
SWITCH_IS => $switch,
IS_DEFERRED => $is_deferred
});
}
if (scalar(@size_is) > 0) {
fatal($e, "size_is() on non-array element");
}
if (scalar(@length_is) > 0) {
fatal($e, "length_is() on non-array element");
}
if (has_property($e, "string")) {
fatal($e, "string() attribute on non-array element");
}
push (@$order, {
TYPE => "DATA",
DATA_TYPE => $e->{TYPE},
IS_DEFERRED => $is_deferred,
CONTAINS_DEFERRED => can_contain_deferred($e->{TYPE}),
IS_SURROUNDING => 0 #FIXME
});
my $i = 0;
foreach (@$order) { $_->{LEVEL_INDEX} = $i; $i+=1; }
return $order;
}
sub GetTypedefLevelTable($$$$)
{
my ($e, $data, $pointer_default, $ms_union) = @_;
my $order = [];
push (@$order, {
TYPE => "TYPEDEF"
});
my $i = 0;
foreach (@$order) { $_->{LEVEL_INDEX} = $i; $i+=1; }
return $order;
}
#####################################################################
# see if a type contains any deferred data
sub can_contain_deferred($)
{
sub can_contain_deferred($);
my ($type) = @_;
return 1 unless (hasType($type)); # assume the worst
$type = getType($type);
return 0 if (Parse::Pidl::Typelist::is_scalar($type));
return can_contain_deferred($type->{DATA}) if ($type->{TYPE} eq "TYPEDEF");
return 0 unless defined($type->{ELEMENTS});
foreach (@{$type->{ELEMENTS}}) {
return 1 if ($_->{POINTERS});
return 1 if (can_contain_deferred ($_->{TYPE}));
}
return 0;
}
sub pointer_type($)
{
my $e = shift;
return undef unless $e->{POINTERS};
return "ref" if (has_property($e, "ref"));
return "full" if (has_property($e, "ptr"));
return "sptr" if (has_property($e, "sptr"));
return "unique" if (has_property($e, "unique"));
return "relative" if (has_property($e, "relative"));
return "relative_short" if (has_property($e, "relative_short"));
return "ignore" if (has_property($e, "ignore"));
return undef;
}
#####################################################################
# work out the correct alignment for a structure or union
sub find_largest_alignment($)
{
my $s = shift;
my $align = 1;
for my $e (@{$s->{ELEMENTS}}) {
my $a = 1;
if ($e->{POINTERS}) {
# this is a hack for NDR64
# the NDR layer translates this into
# an alignment of 4 for NDR and 8 for NDR64
$a = 5;
} elsif (has_property($e, "subcontext")) {
$a = 1;
} elsif (has_property($e, "transmit_as")) {
$a = align_type($e->{PROPERTIES}->{transmit_as});
} else {
$a = align_type($e->{TYPE});
}
$align = $a if ($align < $a);
}
return $align;
}
#####################################################################
# align a type
sub align_type($)
{
sub align_type($);
my ($e) = @_;
if (ref($e) eq "HASH" and $e->{TYPE} eq "SCALAR") {
return $scalar_alignment->{$e->{NAME}};
}
return 0 if ($e eq "EMPTY");
unless (hasType($e)) {
# it must be an external type - all we can do is guess
# warning($e, "assuming alignment of unknown type '$e' is 4");
return 4;
}
my $dt = getType($e);
if ($dt->{TYPE} eq "TYPEDEF") {
return align_type($dt->{DATA});
} elsif ($dt->{TYPE} eq "CONFORMANCE") {
return $dt->{DATA}->{ALIGN};
} elsif ($dt->{TYPE} eq "ENUM") {
return align_type(Parse::Pidl::Typelist::enum_type_fn($dt));
} elsif ($dt->{TYPE} eq "BITMAP") {
return align_type(Parse::Pidl::Typelist::bitmap_type_fn($dt));
} elsif (($dt->{TYPE} eq "STRUCT") or ($dt->{TYPE} eq "UNION")) {
# Struct/union without body: assume 4
return 4 unless (defined($dt->{ELEMENTS}));
return find_largest_alignment($dt);
} elsif (($dt->{TYPE} eq "PIPE")) {
return 5;
}
die("Unknown data type type $dt->{TYPE}");
}
sub ParseElement($$$)
{
my ($e, $pointer_default, $ms_union) = @_;
$e->{TYPE} = expandAlias($e->{TYPE});
if (ref($e->{TYPE}) eq "HASH") {
$e->{TYPE} = ParseType($e->{TYPE}, $pointer_default, $ms_union);
}
return {
NAME => $e->{NAME},
TYPE => $e->{TYPE},
PROPERTIES => $e->{PROPERTIES},
LEVELS => GetElementLevelTable($e, $pointer_default, $ms_union),
REPRESENTATION_TYPE => ($e->{PROPERTIES}->{represent_as} or $e->{TYPE}),
ALIGN => align_type($e->{TYPE}),
ORIGINAL => $e
};
}
sub ParseStruct($$$)
{
my ($struct, $pointer_default, $ms_union) = @_;
my @elements = ();
my $surrounding = undef;
return {
TYPE => "STRUCT",
NAME => $struct->{NAME},
SURROUNDING_ELEMENT => undef,
ELEMENTS => undef,
PROPERTIES => $struct->{PROPERTIES},
ORIGINAL => $struct,
ALIGN => undef
} unless defined($struct->{ELEMENTS});
CheckPointerTypes($struct, $pointer_default);
foreach my $x (@{$struct->{ELEMENTS}})
{
my $e = ParseElement($x, $pointer_default, $ms_union);
if ($x != $struct->{ELEMENTS}[-1] and
$e->{LEVELS}[0]->{IS_SURROUNDING}) {
fatal($x, "conformant member not at end of struct");
}
push @elements, $e;
}
my $e = $elements[-1];
if (defined($e) and defined($e->{LEVELS}[0]->{IS_SURROUNDING}) and
$e->{LEVELS}[0]->{IS_SURROUNDING}) {
$surrounding = $e;
}
if (defined $e->{TYPE} && $e->{TYPE} eq "string"
&& property_matches($e, "flag", ".*LIBNDR_FLAG_STR_CONFORMANT.*")) {
$surrounding = $struct->{ELEMENTS}[-1];
}
my $align = undef;
if ($struct->{NAME}) {
$align = align_type($struct->{NAME});
}
return {
TYPE => "STRUCT",
NAME => $struct->{NAME},
SURROUNDING_ELEMENT => $surrounding,
ELEMENTS => \@elements,
PROPERTIES => $struct->{PROPERTIES},
ORIGINAL => $struct,
ALIGN => $align
};
}
sub ParseUnion($$)
{
my ($e, $pointer_default, $ms_union) = @_;
my @elements = ();
my $is_ms_union = $ms_union;
$is_ms_union = 1 if has_property($e, "ms_union");
my $hasdefault = 0;
my $switch_type = has_property($e, "switch_type");
unless (defined($switch_type)) { $switch_type = "uint32"; }
if (has_property($e, "nodiscriminant")) { $switch_type = undef; }
return {
TYPE => "UNION",
NAME => $e->{NAME},
SWITCH_TYPE => $switch_type,
ELEMENTS => undef,
PROPERTIES => $e->{PROPERTIES},
HAS_DEFAULT => $hasdefault,
IS_MS_UNION => $is_ms_union,
ORIGINAL => $e,
ALIGN => undef
} unless defined($e->{ELEMENTS});
CheckPointerTypes($e, $pointer_default);
foreach my $x (@{$e->{ELEMENTS}})
{
my $t;
if ($x->{TYPE} eq "EMPTY") {
$t = { TYPE => "EMPTY" };
} else {
$t = ParseElement($x, $pointer_default, $ms_union);
}
if (has_property($x, "default")) {
$t->{CASE} = "default";
$hasdefault = 1;
} elsif (defined($x->{PROPERTIES}->{case})) {
$t->{CASE} = "case $x->{PROPERTIES}->{case}";
} else {
die("Union element $x->{NAME} has neither default nor case property");
}
push @elements, $t;
}
my $align = undef;
if ($e->{NAME}) {
$align = align_type($e->{NAME});
}
return {
TYPE => "UNION",
NAME => $e->{NAME},
SWITCH_TYPE => $switch_type,
ELEMENTS => \@elements,
PROPERTIES => $e->{PROPERTIES},
HAS_DEFAULT => $hasdefault,
IS_MS_UNION => $is_ms_union,
ORIGINAL => $e,
ALIGN => $align
};
}
sub ParseEnum($$)
{
my ($e, $pointer_default, $ms_union) = @_;
return {
TYPE => "ENUM",
NAME => $e->{NAME},
BASE_TYPE => Parse::Pidl::Typelist::enum_type_fn($e),
ELEMENTS => $e->{ELEMENTS},
PROPERTIES => $e->{PROPERTIES},
ORIGINAL => $e
};
}
sub ParseBitmap($$$)
{
my ($e, $pointer_default, $ms_union) = @_;
return {
TYPE => "BITMAP",
NAME => $e->{NAME},
BASE_TYPE => Parse::Pidl::Typelist::bitmap_type_fn($e),
ELEMENTS => $e->{ELEMENTS},
PROPERTIES => $e->{PROPERTIES},
ORIGINAL => $e
};
}
sub ParsePipe($$$)
{
my ($pipe, $pointer_default, $ms_union) = @_;
my $pname = $pipe->{NAME};
$pname = $pipe->{PARENT}->{NAME} unless defined $pname;
if (not defined($pipe->{PROPERTIES})
and defined($pipe->{PARENT}->{PROPERTIES})) {
$pipe->{PROPERTIES} = $pipe->{PARENT}->{PROPERTIES};
}
if (ref($pipe->{DATA}) eq "HASH") {
if (not defined($pipe->{DATA}->{PROPERTIES})
and defined($pipe->{PROPERTIES})) {
$pipe->{DATA}->{PROPERTIES} = $pipe->{PROPERTIES};
}
}
my $struct = ParseStruct($pipe->{DATA}, $pointer_default, $ms_union);
$struct->{ALIGN} = 5;
$struct->{NAME} = "$pname\_chunk";
# 'count' is element [0] and 'array' [1]
my $e = $struct->{ELEMENTS}[1];
# level [0] is of type "ARRAY"
my $l = $e->{LEVELS}[1];
# here we check that pipe elements have a fixed size type
while (defined($l)) {
my $cl = $l;
$l = GetNextLevel($e, $cl);
if ($cl->{TYPE} ne "DATA") {
fatal($pipe, el_name($pipe) . ": pipe contains non DATA level");
}
# for now we only support scalars
next if is_fixed_size_scalar($cl->{DATA_TYPE});
fatal($pipe, el_name($pipe) . ": pipe contains non fixed size type[$cl->{DATA_TYPE}]");
}
return {
TYPE => "PIPE",
NAME => $pipe->{NAME},
DATA => $struct,
PROPERTIES => $pipe->{PROPERTIES},
ORIGINAL => $pipe,
};
}
sub ParseType($$$)
{
my ($d, $pointer_default, $ms_union) = @_;
my $data = {
STRUCT => \&ParseStruct,
UNION => \&ParseUnion,
ENUM => \&ParseEnum,
BITMAP => \&ParseBitmap,
TYPEDEF => \&ParseTypedef,
PIPE => \&ParsePipe,
}->{$d->{TYPE}}->($d, $pointer_default, $ms_union);
return $data;
}
sub ParseTypedef($$)
{
my ($d, $pointer_default, $ms_union) = @_;
my $data;
if (ref($d->{DATA}) eq "HASH") {
if (defined($d->{DATA}->{PROPERTIES})
and not defined($d->{PROPERTIES})) {
$d->{PROPERTIES} = $d->{DATA}->{PROPERTIES};
}
$data = ParseType($d->{DATA}, $pointer_default, $ms_union);
$data->{ALIGN} = align_type($d->{NAME});
} else {
$data = getType($d->{DATA});
}
return {
NAME => $d->{NAME},
TYPE => $d->{TYPE},
PROPERTIES => $d->{PROPERTIES},
LEVELS => GetTypedefLevelTable($d, $data, $pointer_default, $ms_union),
DATA => $data,
ORIGINAL => $d
};
}
sub ParseConst($$)
{
my ($ndr,$d) = @_;
return $d;
}
sub ParseFunction($$$$)
{
my ($ndr,$d,$opnum,$ms_union) = @_;
my @elements = ();
my $rettype = undef;
my $thisopnum = undef;
CheckPointerTypes($d, "ref");
if (not defined($d->{PROPERTIES}{noopnum})) {
$thisopnum = ${$opnum};
${$opnum}++;
}
foreach my $x (@{$d->{ELEMENTS}}) {
my $e = ParseElement($x, $ndr->{PROPERTIES}->{pointer_default}, $ms_union);
push (@{$e->{DIRECTION}}, "in") if (has_property($x, "in"));
push (@{$e->{DIRECTION}}, "out") if (has_property($x, "out"));
push (@elements, $e);
}
if ($d->{RETURN_TYPE} ne "void") {
$rettype = expandAlias($d->{RETURN_TYPE});
}
return {
NAME => $d->{NAME},
TYPE => "FUNCTION",
OPNUM => $thisopnum,
RETURN_TYPE => $rettype,
PROPERTIES => $d->{PROPERTIES},
ELEMENTS => \@elements,
ORIGINAL => $d
};
}
sub ReturnTypeElement($)
{
my ($fn) = @_;
return undef unless defined($fn->{RETURN_TYPE});
my $e = {
"NAME" => "result",
"TYPE" => $fn->{RETURN_TYPE},
"PROPERTIES" => undef,
"POINTERS" => 0,
"ARRAY_LEN" => [],
"FILE" => $fn->{FILE},
"LINE" => $fn->{LINE},
};
return ParseElement($e, 0, 0);
}
sub CheckPointerTypes($$)
{
my ($s,$default) = @_;
return unless defined($s->{ELEMENTS});
foreach my $e (@{$s->{ELEMENTS}}) {
if ($e->{POINTERS} and not defined(pointer_type($e))) {
$e->{PROPERTIES}->{$default} = '1';
}
}
}
sub FindNestedTypes($$)
{
sub FindNestedTypes($$);
my ($l, $t) = @_;
return unless defined($t->{ELEMENTS});
return if ($t->{TYPE} eq "ENUM");
return if ($t->{TYPE} eq "BITMAP");
foreach (@{$t->{ELEMENTS}}) {
if (ref($_->{TYPE}) eq "HASH") {
push (@$l, $_->{TYPE}) if (defined($_->{TYPE}->{NAME}));
FindNestedTypes($l, $_->{TYPE});
}
}
}
sub ParseInterface($)
{
my $idl = shift;
my @types = ();
my @consts = ();
my @functions = ();
my @endpoints;
my $opnum = 0;
my $version;
my $ms_union = 0;
$ms_union = 1 if has_property($idl, "ms_union");
if (not has_property($idl, "pointer_default")) {
# MIDL defaults to "ptr" in DCE compatible mode (/osf)
# and "unique" in Microsoft Extensions mode (default)
$idl->{PROPERTIES}->{pointer_default} = "unique";
}
foreach my $d (@{$idl->{DATA}}) {
if ($d->{TYPE} eq "FUNCTION") {
push (@functions, ParseFunction($idl, $d, \$opnum, $ms_union));
} elsif ($d->{TYPE} eq "CONST") {
push (@consts, ParseConst($idl, $d));
} else {
push (@types, ParseType($d, $idl->{PROPERTIES}->{pointer_default}, $ms_union));
FindNestedTypes(\@types, $d);
}
}
$version = "0.0";
if(defined $idl->{PROPERTIES}->{version}) {
my @if_version = split(/\./, $idl->{PROPERTIES}->{version});
if ($if_version[0] == $idl->{PROPERTIES}->{version}) {
$version = $idl->{PROPERTIES}->{version};
} else {
$version = $if_version[1] << 16 | $if_version[0];
}
}
# If no endpoint is set, default to the interface name as a named pipe
if (!defined $idl->{PROPERTIES}->{endpoint}) {
push @endpoints, "\"ncacn_np:[\\\\pipe\\\\" . $idl->{NAME} . "]\"";
} else {
@endpoints = split /,/, $idl->{PROPERTIES}->{endpoint};
}
return {
NAME => $idl->{NAME},
UUID => lc(has_property($idl, "uuid")),
VERSION => $version,
TYPE => "INTERFACE",
PROPERTIES => $idl->{PROPERTIES},
FUNCTIONS => \@functions,
CONSTS => \@consts,
TYPES => \@types,
ENDPOINTS => \@endpoints,
ORIGINAL => $idl
};
}
# Convert a IDL tree to a NDR tree
# Gives a result tree describing all that's necessary for easily generating
# NDR parsers / generators
sub Parse($)
{
my $idl = shift;
return undef unless (defined($idl));
Parse::Pidl::NDR::Validate($idl);
my @ndr = ();
foreach (@{$idl}) {
($_->{TYPE} eq "CPP_QUOTE") && push(@ndr, $_);
($_->{TYPE} eq "INTERFACE") && push(@ndr, ParseInterface($_));
($_->{TYPE} eq "IMPORT") && push(@ndr, $_);
}
return \@ndr;
}
sub GetNextLevel($$)
{
my $e = shift;
my $fl = shift;
my $seen = 0;
foreach my $l (@{$e->{LEVELS}}) {
return $l if ($seen);
($seen = 1) if ($l == $fl);
}
return undef;
}
sub GetPrevLevel($$)
{
my ($e,$fl) = @_;
my $prev = undef;
foreach my $l (@{$e->{LEVELS}}) {
(return $prev) if ($l == $fl);
$prev = $l;
}
return undef;
}
sub ContainsString($)
{
my ($e) = @_;
if (property_matches($e, "flag", ".*STR_NULLTERM.*")) {
return 1;
}
if (exists($e->{LEVELS}) and $e->{LEVELS}->[0]->{TYPE} eq "ARRAY" and
($e->{LEVELS}->[0]->{IS_FIXED} or $e->{LEVELS}->[0]->{IS_INLINE}) and
has_property($e, "charset"))
{
return 1;
}
foreach my $l (@{$e->{LEVELS}}) {
return 1 if ($l->{TYPE} eq "ARRAY" and $l->{IS_ZERO_TERMINATED});
}
if (property_matches($e, "charset", ".*DOS.*")) {
return 1;
}
return 0;
}
sub ContainsDeferred($$)
{
my ($e,$l) = @_;
return 1 if ($l->{CONTAINS_DEFERRED});
while ($l = GetNextLevel($e,$l))
{
return 1 if ($l->{IS_DEFERRED});
return 1 if ($l->{CONTAINS_DEFERRED});
}
return 0;
}
sub ContainsPipe($$)
{
my ($e,$l) = @_;
return 1 if ($l->{TYPE} eq "PIPE");
while ($l = GetNextLevel($e,$l))
{
return 1 if ($l->{TYPE} eq "PIPE");
}
return 0;
}
sub el_name($)
{
my $e = shift;
my $name = "<ANONYMOUS>";
$name = $e->{NAME} if defined($e->{NAME});
if (defined($e->{PARENT}) and defined($e->{PARENT}->{NAME})) {
return "$e->{PARENT}->{NAME}.$name";
}
if (defined($e->{PARENT}) and
defined($e->{PARENT}->{PARENT}) and
defined($e->{PARENT}->{PARENT}->{NAME})) {
return "$e->{PARENT}->{PARENT}->{NAME}.$name";
}
return $name;
}
###################################
# find a sibling var in a structure
sub find_sibling($$)
{
my($e,$name) = @_;
my($fn) = $e->{PARENT};
if ($name =~ /\*(.*)/) {
$name = $1;
}
for my $e2 (@{$fn->{ELEMENTS}}) {
return $e2 if ($e2->{NAME} eq $name);
}
return undef;
}
my %property_list = (
# interface
"helpstring" => ["INTERFACE", "FUNCTION"],
"version" => ["INTERFACE"],
"uuid" => ["INTERFACE"],
"endpoint" => ["INTERFACE"],
"pointer_default" => ["INTERFACE"],
"helper" => ["INTERFACE"],
"pyhelper" => ["INTERFACE"],
"authservice" => ["INTERFACE"],
"restricted" => ["INTERFACE"],
"no_srv_register" => ["INTERFACE"],
# dcom
"object" => ["INTERFACE"],
"local" => ["INTERFACE", "FUNCTION"],
"iid_is" => ["ELEMENT"],
"call_as" => ["FUNCTION"],
"idempotent" => ["FUNCTION"],
# function
"noopnum" => ["FUNCTION"],
"in" => ["ELEMENT"],
"out" => ["ELEMENT"],
# pointer
"ref" => ["ELEMENT", "TYPEDEF"],
"ptr" => ["ELEMENT", "TYPEDEF"],
"unique" => ["ELEMENT", "TYPEDEF"],
"ignore" => ["ELEMENT"],
"relative" => ["ELEMENT", "TYPEDEF"],
"relative_short" => ["ELEMENT", "TYPEDEF"],
"null_is_ffffffff" => ["ELEMENT"],
"relative_base" => ["TYPEDEF", "STRUCT", "UNION"],
"gensize" => ["TYPEDEF", "STRUCT", "UNION"],
"value" => ["ELEMENT"],
"flag" => ["ELEMENT", "TYPEDEF", "STRUCT", "UNION", "ENUM", "BITMAP", "PIPE"],
# generic
"public" => ["FUNCTION", "TYPEDEF", "STRUCT", "UNION", "ENUM", "BITMAP", "PIPE"],
"nopush" => ["FUNCTION", "TYPEDEF", "STRUCT", "UNION", "ENUM", "BITMAP", "PIPE"],
"nopull" => ["FUNCTION", "TYPEDEF", "STRUCT", "UNION", "ENUM", "BITMAP", "PIPE"],
"nosize" => ["FUNCTION", "TYPEDEF", "STRUCT", "UNION", "ENUM", "BITMAP"],
"noprint" => ["FUNCTION", "TYPEDEF", "STRUCT", "UNION", "ENUM", "BITMAP", "ELEMENT", "PIPE"],
"nopython" => ["FUNCTION", "TYPEDEF", "STRUCT", "UNION", "ENUM", "BITMAP"],
"todo" => ["FUNCTION"],
"skip" => ["ELEMENT"],
"skip_noinit" => ["ELEMENT"],
# union
"switch_is" => ["ELEMENT"],
"switch_type" => ["ELEMENT", "UNION"],
"nodiscriminant" => ["UNION"],
"ms_union" => ["INTERFACE", "UNION"],
"case" => ["ELEMENT"],
"default" => ["ELEMENT"],
"represent_as" => ["ELEMENT"],
"transmit_as" => ["ELEMENT"],
# subcontext
"subcontext" => ["ELEMENT"],
"subcontext_size" => ["ELEMENT"],
"compression" => ["ELEMENT"],
# enum
"enum8bit" => ["ENUM"],
"enum16bit" => ["ENUM"],
"v1_enum" => ["ENUM"],
# bitmap
"bitmap8bit" => ["BITMAP"],
"bitmap16bit" => ["BITMAP"],
"bitmap32bit" => ["BITMAP"],
"bitmap64bit" => ["BITMAP"],
# array
"range" => ["ELEMENT", "PIPE"],
"size_is" => ["ELEMENT"],
"string" => ["ELEMENT"],
"noheader" => ["ELEMENT"],
"charset" => ["ELEMENT"],
"length_is" => ["ELEMENT"],
"to_null" => ["ELEMENT"],
);
#####################################################################
# check for unknown properties
sub ValidProperties($$)
{
my ($e,$t) = @_;
return unless defined $e->{PROPERTIES};
foreach my $key (keys %{$e->{PROPERTIES}}) {
warning($e, el_name($e) . ": unknown property '$key'")
unless defined($property_list{$key});
fatal($e, el_name($e) . ": property '$key' not allowed on '$t'")
unless grep(/^$t$/, @{$property_list{$key}});
}
}
sub mapToScalar($)
{
sub mapToScalar($);
my $t = shift;
return $t->{NAME} if (ref($t) eq "HASH" and $t->{TYPE} eq "SCALAR");
my $ti = getType($t);
if (not defined ($ti)) {
return undef;
} elsif ($ti->{TYPE} eq "TYPEDEF") {
return mapToScalar($ti->{DATA});
} elsif ($ti->{TYPE} eq "ENUM") {
return Parse::Pidl::Typelist::enum_type_fn($ti);
} elsif ($ti->{TYPE} eq "BITMAP") {
return Parse::Pidl::Typelist::bitmap_type_fn($ti);
}
return undef;
}
#####################################################################
# validate an element
sub ValidElement($)
{
my $e = shift;
ValidProperties($e,"ELEMENT");
# Check whether switches are used correctly.
if (my $switch = has_property($e, "switch_is")) {
my $e2 = find_sibling($e, $switch);
my $type = getType($e->{TYPE});
if (defined($type) and $type->{DATA}->{TYPE} ne "UNION") {
fatal($e, el_name($e) . ": switch_is() used on non-union type $e->{TYPE} which is a $type->{DATA}->{TYPE}");
}
if (not has_property($type->{DATA}, "nodiscriminant") and defined($e2)) {
my $discriminator_type = has_property($type->{DATA}, "switch_type");
$discriminator_type = "uint32" unless defined ($discriminator_type);
my $t1 = mapScalarType(mapToScalar($discriminator_type));
if (not defined($t1)) {
fatal($e, el_name($e) . ": unable to map discriminator type '$discriminator_type' to scalar");
}
my $t2 = mapScalarType(mapToScalar($e2->{TYPE}));
if (not defined($t2)) {
fatal($e, el_name($e) . ": unable to map variable used for switch_is() to scalar");
}
if ($t1 ne $t2) {
warning($e, el_name($e) . ": switch_is() is of type $e2->{TYPE} ($t2), while discriminator type for union $type->{NAME} is $discriminator_type ($t1)");
}
}
}
if (has_property($e, "subcontext") and has_property($e, "represent_as")) {
fatal($e, el_name($e) . " : subcontext() and represent_as() can not be used on the same element");
}
if (has_property($e, "subcontext") and has_property($e, "transmit_as")) {
fatal($e, el_name($e) . " : subcontext() and transmit_as() can not be used on the same element");
}
if (has_property($e, "represent_as") and has_property($e, "transmit_as")) {
fatal($e, el_name($e) . " : represent_as() and transmit_as() can not be used on the same element");
}
if (has_property($e, "represent_as") and has_property($e, "value")) {
fatal($e, el_name($e) . " : represent_as() and value() can not be used on the same element");
}
if (has_property($e, "subcontext")) {
warning($e, "subcontext() is deprecated. Use represent_as() or transmit_as() instead");
}
if (defined (has_property($e, "subcontext_size")) and not defined(has_property($e, "subcontext"))) {
fatal($e, el_name($e) . " : subcontext_size() on non-subcontext element");
}
if (defined (has_property($e, "compression")) and not defined(has_property($e, "subcontext"))) {
fatal($e, el_name($e) . " : compression() on non-subcontext element");
}
if (!$e->{POINTERS} && (
has_property($e, "ptr") or
has_property($e, "unique") or
has_property($e, "relative") or
has_property($e, "relative_short") or
has_property($e, "ref"))) {
fatal($e, el_name($e) . " : pointer properties on non-pointer element\n");
}
}
#####################################################################
# validate an enum
sub ValidEnum($)
{
my ($enum) = @_;
ValidProperties($enum, "ENUM");
}
#####################################################################
# validate a bitmap
sub ValidBitmap($)
{
my ($bitmap) = @_;
ValidProperties($bitmap, "BITMAP");
}
#####################################################################
# validate a struct
sub ValidStruct($)
{
my($struct) = shift;
ValidProperties($struct, "STRUCT");
return unless defined($struct->{ELEMENTS});
foreach my $e (@{$struct->{ELEMENTS}}) {
$e->{PARENT} = $struct;
ValidElement($e);
}
}
#####################################################################
# parse a union
sub ValidUnion($)
{
my($union) = shift;
ValidProperties($union,"UNION");
if (has_property($union->{PARENT}, "nodiscriminant") and
has_property($union->{PARENT}, "switch_type")) {
fatal($union->{PARENT}, $union->{PARENT}->{NAME} . ": switch_type(" . $union->{PARENT}->{PROPERTIES}->{switch_type} . ") on union without discriminant");
}
return unless defined($union->{ELEMENTS});
foreach my $e (@{$union->{ELEMENTS}}) {
$e->{PARENT} = $union;
if (defined($e->{PROPERTIES}->{default}) and
defined($e->{PROPERTIES}->{case})) {
fatal($e, "Union member $e->{NAME} can not have both default and case properties!");
}
unless (defined ($e->{PROPERTIES}->{default}) or
defined ($e->{PROPERTIES}->{case})) {
fatal($e, "Union member $e->{NAME} must have default or case property");
}
if (has_property($e, "ref")) {
fatal($e, el_name($e) . ": embedded ref pointers are not supported yet\n");
}
ValidElement($e);
}
}
#####################################################################
# validate a pipe
sub ValidPipe($)
{
my ($pipe) = @_;
my $struct = $pipe->{DATA};
ValidProperties($pipe, "PIPE");
$struct->{PARENT} = $pipe;
$struct->{FILE} = $pipe->{FILE} unless defined($struct->{FILE});
$struct->{LINE} = $pipe->{LINE} unless defined($struct->{LINE});
ValidType($struct);
}
#####################################################################
# parse a typedef
sub ValidTypedef($)
{
my($typedef) = shift;
my $data = $typedef->{DATA};
ValidProperties($typedef, "TYPEDEF");
return unless (ref($data) eq "HASH");
$data->{PARENT} = $typedef;
$data->{FILE} = $typedef->{FILE} unless defined($data->{FILE});
$data->{LINE} = $typedef->{LINE} unless defined($data->{LINE});
ValidType($data);
}
#####################################################################
# validate a function
sub ValidFunction($)
{
my($fn) = shift;
ValidProperties($fn,"FUNCTION");
foreach my $e (@{$fn->{ELEMENTS}}) {
$e->{PARENT} = $fn;
if (has_property($e, "ref") && !$e->{POINTERS}) {
fatal($e, "[ref] variables must be pointers ($fn->{NAME}/$e->{NAME})");
}
ValidElement($e);
}
}
#####################################################################
# validate a type
sub ValidType($)
{
my ($t) = @_;
{
TYPEDEF => \&ValidTypedef,
STRUCT => \&ValidStruct,
UNION => \&ValidUnion,
ENUM => \&ValidEnum,
BITMAP => \&ValidBitmap,
PIPE => \&ValidPipe
}->{$t->{TYPE}}->($t);
}
#####################################################################
# parse the interface definitions
sub ValidInterface($)
{
my($interface) = shift;
my($data) = $interface->{DATA};
if (has_property($interface, "helper")) {
warning($interface, "helper() is pidl-specific and deprecated. Use `include' instead");
}
ValidProperties($interface,"INTERFACE");
if (has_property($interface, "pointer_default")) {
if (not grep (/$interface->{PROPERTIES}->{pointer_default}/,
("ref", "unique", "ptr"))) {
fatal($interface, "Unknown default pointer type `$interface->{PROPERTIES}->{pointer_default}'");
}
}
if (has_property($interface, "object")) {
if (has_property($interface, "version") &&
$interface->{PROPERTIES}->{version} != 0) {
fatal($interface, "Object interfaces must have version 0.0 ($interface->{NAME})");
}
if (!defined($interface->{BASE}) &&
not ($interface->{NAME} eq "IUnknown")) {
fatal($interface, "Object interfaces must all derive from IUnknown ($interface->{NAME})");
}
}
foreach my $d (@{$data}) {
($d->{TYPE} eq "FUNCTION") && ValidFunction($d);
($d->{TYPE} eq "TYPEDEF" or
$d->{TYPE} eq "STRUCT" or
$d->{TYPE} eq "UNION" or
$d->{TYPE} eq "ENUM" or
$d->{TYPE} eq "BITMAP" or
$d->{TYPE} eq "PIPE") && ValidType($d);
}
}
#####################################################################
# Validate an IDL structure
sub Validate($)
{
my($idl) = shift;
foreach my $x (@{$idl}) {
($x->{TYPE} eq "INTERFACE") &&
ValidInterface($x);
($x->{TYPE} eq "IMPORTLIB") &&
fatal($x, "importlib() not supported");
}
}
sub is_charset_array($$)
{
my ($e,$l) = @_;
return 0 if ($l->{TYPE} ne "ARRAY");
my $nl = GetNextLevel($e,$l);
return 0 unless ($nl->{TYPE} eq "DATA");
return has_property($e, "charset");
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/ODL.pm | ##########################################
# Converts ODL stuctures to IDL structures
# (C) 2004-2005, 2008 Jelmer Vernooij <[email protected]>
package Parse::Pidl::ODL;
use Parse::Pidl qw(error);
use Parse::Pidl::IDL;
use Parse::Pidl::Util qw(has_property unmake_str);
use Parse::Pidl::Typelist qw(hasType getType);
use File::Basename;
use strict;
use vars qw($VERSION);
$VERSION = '0.01';
sub FunctionAddObjArgs($)
{
my $e = shift;
unshift(@{$e->{ELEMENTS}}, {
'NAME' => 'ORPCthis',
'POINTERS' => 0,
'PROPERTIES' => { 'in' => '1' },
'TYPE' => 'ORPCTHIS',
'FILE' => $e->{FILE},
'LINE' => $e->{LINE}
});
unshift(@{$e->{ELEMENTS}}, {
'NAME' => 'ORPCthat',
'POINTERS' => 1,
'PROPERTIES' => { 'out' => '1', 'ref' => '1' },
'TYPE' => 'ORPCTHAT',
'FILE' => $e->{FILE},
'LINE' => $e->{LINE}
});
}
sub ReplaceInterfacePointers($)
{
my ($e) = @_;
foreach my $x (@{$e->{ELEMENTS}}) {
next unless (hasType($x->{TYPE}));
next unless getType($x->{TYPE})->{DATA}->{TYPE} eq "INTERFACE";
$x->{TYPE} = "MInterfacePointer";
}
}
# Add ORPC specific bits to an interface.
sub ODL2IDL
{
my ($odl, $basedir, $opt_incdirs) = (@_);
my $addedorpc = 0;
my $interfaces = {};
foreach my $x (@$odl) {
if ($x->{TYPE} eq "IMPORT") {
foreach my $idl_file (@{$x->{PATHS}}) {
$idl_file = unmake_str($idl_file);
my $idl_path = undef;
foreach ($basedir, @$opt_incdirs) {
if (-f "$_/$idl_file") {
$idl_path = "$_/$idl_file";
last;
}
}
unless ($idl_path) {
error($x, "Unable to open include file `$idl_file'");
next;
}
my $podl = Parse::Pidl::IDL::parse_file($idl_path, $opt_incdirs);
if (defined($podl)) {
require Parse::Pidl::Typelist;
my $basename = basename($idl_path, ".idl");
Parse::Pidl::Typelist::LoadIdl($podl, $basename);
my $pidl = ODL2IDL($podl, $basedir, $opt_incdirs);
foreach my $y (@$pidl) {
if ($y->{TYPE} eq "INTERFACE") {
$interfaces->{$y->{NAME}} = $y;
}
}
} else {
error($x, "Failed to parse $idl_path");
}
}
}
if ($x->{TYPE} eq "INTERFACE") {
$interfaces->{$x->{NAME}} = $x;
# Add [in] ORPCTHIS *this, [out] ORPCTHAT *that
# and replace interfacepointers with MInterfacePointer
# for 'object' interfaces
if (has_property($x, "object")) {
foreach my $e (@{$x->{DATA}}) {
($e->{TYPE} eq "FUNCTION") && FunctionAddObjArgs($e);
ReplaceInterfacePointers($e);
}
$addedorpc = 1;
}
if ($x->{BASE}) {
my $base = $interfaces->{$x->{BASE}};
unless (defined($base)) {
error($x, "Undefined base interface `$x->{BASE}'");
} else {
foreach my $fn (reverse @{$base->{DATA}}) {
next unless ($fn->{TYPE} eq "FUNCTION");
push (@{$x->{INHERITED_FUNCTIONS}}, $fn);
}
}
}
}
}
unshift (@$odl, {
TYPE => "IMPORT",
PATHS => [ "\"orpc.idl\"" ],
FILE => undef,
LINE => undef
}) if ($addedorpc);
return $odl;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4.pm | ###################################################
# Common Samba4 functions
# Copyright [email protected] 2006
# released under the GNU GPL
package Parse::Pidl::Samba4;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(is_intree choose_header NumStars ElementStars ArrayBrackets DeclLong ArrayDynamicallyAllocated);
use Parse::Pidl::Util qw(has_property is_constant);
use Parse::Pidl::NDR qw(GetNextLevel);
use Parse::Pidl::Typelist qw(mapTypeName scalar_is_reference);
use Parse::Pidl qw(fatal error);
use strict;
use vars qw($VERSION);
$VERSION = '0.01';
# return true if we are using pidl within the samba source tree. This changes
# the names of include files, as some include files (such as ntstatus.h) have
# different paths when installed to the patch in the source tree
sub is_intree()
{
my $srcdir = $ENV{srcdir};
$srcdir = $srcdir ? "$srcdir/" : "";
return 1 if (-f "${srcdir}kdc/kdc.c");
return 1 if (-d "${srcdir}source4");
return 1 if (-f "${srcdir}include/smb.h");
return 0;
}
# Return an #include line depending on whether this build is an in-tree
# build or not.
sub choose_header($$)
{
my ($in,$out) = @_;
return "#include \"$in\"" if (is_intree());
return "#include <$out>";
}
sub ArrayDynamicallyAllocated($$)
{
my ($e, $l) = @_;
die("Not an array") unless ($l->{TYPE} eq "ARRAY");
return 0 if ($l->{IS_FIXED} and not has_property($e, "charset"));
return 1;
}
sub NumStars($;$)
{
my ($e, $d) = @_;
$d = 0 unless defined($d);
my $n = 0;
foreach my $l (@{$e->{LEVELS}}) {
next unless ($l->{TYPE} eq "POINTER");
my $nl = GetNextLevel($e, $l);
next if (defined($nl) and $nl->{TYPE} eq "ARRAY");
$n++;
}
if ($n >= 1) {
$n-- if (scalar_is_reference($e->{TYPE}));
}
foreach my $l (@{$e->{LEVELS}}) {
next unless ($l->{TYPE} eq "ARRAY");
next unless (ArrayDynamicallyAllocated($e, $l));
$n++;
}
error($e->{ORIGINAL}, "Too few pointers $n < $d") if ($n < $d);
$n -= $d;
return $n;
}
sub ElementStars($;$)
{
my ($e, $d) = @_;
my $res = "";
my $n = 0;
$n = NumStars($e, $d);
$res .= "*" foreach (1..$n);
return $res;
}
sub ArrayBrackets($)
{
my ($e) = @_;
my $res = "";
foreach my $l (@{$e->{LEVELS}}) {
next unless ($l->{TYPE} eq "ARRAY");
next if ArrayDynamicallyAllocated($e, $l);
$res .= "[$l->{SIZE_IS}]";
}
return $res;
}
sub DeclLong($;$)
{
my ($e, $p) = @_;
my $res = "";
$p = "" unless defined($p);
if (has_property($e, "represent_as")) {
$res .= mapTypeName($e->{PROPERTIES}->{represent_as})." ";
} else {
if (has_property($e, "charset")) {
$res .= "const char ";
} else {
$res .= mapTypeName($e->{TYPE})." ";
}
$res .= ElementStars($e);
}
$res .= $p.$e->{NAME};
$res .= ArrayBrackets($e);
return $res;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Typelist.pm | ###################################################
# Samba4 parser generator for IDL structures
# Copyright [email protected] 2005
# released under the GNU GPL
package Parse::Pidl::Typelist;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(hasType getType resolveType mapTypeName scalar_is_reference expandAlias
mapScalarType addType typeIs is_signed is_scalar enum_type_fn
bitmap_type_fn mapType typeHasBody is_fixed_size_scalar
);
use vars qw($VERSION);
$VERSION = '0.01';
use Parse::Pidl::Util qw(has_property);
use strict;
my %types = ();
my @reference_scalars = (
"string", "string_array", "nbt_string", "dns_string",
"wrepl_nbt_name", "dnsp_name", "dnsp_string",
"ipv4address", "ipv6address"
);
my @non_fixed_size_scalars = (
"string", "string_array", "nbt_string", "dns_string",
"wrepl_nbt_name", "dnsp_name", "dnsp_string"
);
# a list of known scalar types
my %scalars = (
"void" => "void",
"char" => "char",
"int8" => "int8_t",
"uint8" => "uint8_t",
"int16" => "int16_t",
"uint16" => "uint16_t",
"int1632" => "int16_t",
"uint1632" => "uint16_t",
"int32" => "int32_t",
"uint32" => "uint32_t",
"int3264" => "int32_t",
"uint3264" => "uint32_t",
"hyper" => "uint64_t",
"dlong" => "int64_t",
"udlong" => "uint64_t",
"udlongr" => "uint64_t",
"double" => "double",
"pointer" => "void*",
"DATA_BLOB" => "DATA_BLOB",
"string" => "const char *",
"string_array" => "const char **",
"time_t" => "time_t",
"uid_t" => "uid_t",
"gid_t" => "gid_t",
"NTTIME" => "NTTIME",
"NTTIME_1sec" => "NTTIME",
"NTTIME_hyper" => "NTTIME",
"WERROR" => "WERROR",
"HRESULT" => "HRESULT",
"NTSTATUS" => "NTSTATUS",
"COMRESULT" => "COMRESULT",
"dns_string" => "const char *",
"nbt_string" => "const char *",
"wrepl_nbt_name"=> "struct nbt_name *",
"ipv4address" => "const char *",
"ipv6address" => "const char *",
"dnsp_name" => "const char *",
"dnsp_string" => "const char *",
);
my %aliases = (
"error_status_t" => "uint32",
"boolean8" => "uint8",
"boolean32" => "uint32",
"DWORD" => "uint32",
"uint" => "uint32",
"int" => "int32",
"WORD" => "uint16",
"char" => "uint8",
"long" => "int32",
"short" => "int16",
"HYPER_T" => "hyper",
"mode_t" => "uint32",
);
sub expandAlias($)
{
my $name = shift;
return $aliases{$name} if defined($aliases{$name});
return $name;
}
# map from a IDL type to a C header type
sub mapScalarType($)
{
my $name = shift;
# it's a bug when a type is not in the list
# of known scalars or has no mapping
return $scalars{$name} if defined($scalars{$name});
die("Unknown scalar type $name");
}
sub addType($)
{
my $t = shift;
$types{$t->{NAME}} = $t;
}
sub resolveType($)
{
my ($ctype) = @_;
if (not hasType($ctype)) {
# assume struct typedef
return { TYPE => "TYPEDEF", NAME => $ctype, DATA => { TYPE => "STRUCT" } };
} else {
return getType($ctype);
}
return $ctype;
}
sub getType($)
{
my $t = shift;
return ($t) if (ref($t) eq "HASH" and not defined($t->{NAME}));
return undef if not hasType($t);
return $types{$t->{NAME}} if (ref($t) eq "HASH");
return $types{$t};
}
sub typeIs($$);
sub typeIs($$)
{
my ($t,$tt) = @_;
if (ref($t) eq "HASH") {
return 1 if ($t->{TYPE} eq "TYPEDEF" and $t->{DATA}->{TYPE} eq $tt);
return 1 if ($t->{TYPE} eq $tt);
return 0;
}
if (hasType($t) and getType($t)->{TYPE} eq "TYPEDEF") {
return typeIs(getType($t)->{DATA}, $tt);
}
return 0;
}
sub hasType($)
{
my $t = shift;
if (ref($t) eq "HASH") {
return 1 if (not defined($t->{NAME}));
return 1 if (defined($types{$t->{NAME}}) and
$types{$t->{NAME}}->{TYPE} eq $t->{TYPE});
return 0;
}
return 1 if defined($types{$t});
return 0;
}
sub is_signed($)
{
my $t = shift;
return ($t eq "int8"
or $t eq "int16"
or $t eq "int32"
or $t eq "dlong"
or $t eq "int"
or $t eq "long"
or $t eq "short");
}
sub is_scalar($)
{
sub is_scalar($);
my $type = shift;
return 1 if (ref($type) eq "HASH" and
($type->{TYPE} eq "SCALAR" or $type->{TYPE} eq "ENUM" or
$type->{TYPE} eq "BITMAP"));
if (my $dt = getType($type)) {
return is_scalar($dt->{DATA}) if ($dt->{TYPE} eq "TYPEDEF");
return 1 if ($dt->{TYPE} eq "SCALAR" or $dt->{TYPE} eq "ENUM" or
$dt->{TYPE} eq "BITMAP");
}
return 0;
}
sub is_fixed_size_scalar($)
{
my $name = shift;
return 0 unless is_scalar($name);
return 0 if (grep(/^$name$/, @non_fixed_size_scalars));
return 1;
}
sub scalar_is_reference($)
{
my $name = shift;
return 1 if (grep(/^$name$/, @reference_scalars));
return 0;
}
sub RegisterScalars()
{
foreach (keys %scalars) {
addType({
NAME => $_,
TYPE => "TYPEDEF",
BASEFILE => "<builtin>",
DATA => {
TYPE => "SCALAR",
NAME => $_
}
}
);
}
}
sub enum_type_fn($)
{
my $enum = shift;
$enum->{TYPE} eq "ENUM" or die("not an enum");
# for typedef enum { } we need to check $enum->{PARENT}
if (has_property($enum, "enum8bit")) {
return "uint8";
} elsif (has_property($enum, "enum16bit")) {
return "uint16";
} elsif (has_property($enum, "v1_enum")) {
return "uint32";
} elsif (has_property($enum->{PARENT}, "enum8bit")) {
return "uint8";
} elsif (has_property($enum->{PARENT}, "enum16bit")) {
return "uint16";
} elsif (has_property($enum->{PARENT}, "v1_enum")) {
return "uint32";
}
return "uint1632";
}
sub bitmap_type_fn($)
{
my $bitmap = shift;
$bitmap->{TYPE} eq "BITMAP" or die("not a bitmap");
if (has_property($bitmap, "bitmap8bit")) {
return "uint8";
} elsif (has_property($bitmap, "bitmap16bit")) {
return "uint16";
} elsif (has_property($bitmap, "bitmap64bit")) {
return "hyper";
}
return "uint32";
}
sub typeHasBody($)
{
sub typeHasBody($);
my ($e) = @_;
if ($e->{TYPE} eq "TYPEDEF") {
return 0 unless(defined($e->{DATA}));
return typeHasBody($e->{DATA});
}
return defined($e->{ELEMENTS});
}
sub mapType($$)
{
sub mapType($$);
my ($t, $n) = @_;
return mapType($t->{DATA}, $n) if ($t->{TYPE} eq "TYPEDEF");
return mapScalarType($n) if ($t->{TYPE} eq "SCALAR");
return "enum $n" if ($t->{TYPE} eq "ENUM");
return "struct $n" if ($t->{TYPE} eq "STRUCT" or $t->{TYPE} eq "INTERFACE");
return "union $n" if ($t->{TYPE} eq "UNION");
return mapScalarType(bitmap_type_fn($t)) if ($t->{TYPE} eq "BITMAP");
return "struct $n" if ($t->{TYPE} eq "PIPE");
die("Unknown type $t->{TYPE}");
}
sub mapTypeName($)
{
my $t = shift;
return "void" unless defined($t);
my $dt;
$t = expandAlias($t);
if ($dt = getType($t)) {
return mapType($dt, $dt->{NAME});
} elsif (ref($t) eq "HASH" and defined($t->{NAME})) {
return mapType($t, $t->{NAME});
} else {
# Best guess
return "struct $t";
}
}
sub LoadIdl($;$)
{
my $idl = shift;
my $basename = shift;
foreach my $x (@{$idl}) {
next if $x->{TYPE} ne "INTERFACE";
# DCOM interfaces can be types as well
addType({
NAME => $x->{NAME},
TYPE => "TYPEDEF",
DATA => $x,
BASEFILE => $basename,
}) if (has_property($x, "object"));
foreach my $y (@{$x->{DATA}}) {
if ($y->{TYPE} eq "TYPEDEF"
or $y->{TYPE} eq "UNION"
or $y->{TYPE} eq "STRUCT"
or $y->{TYPE} eq "ENUM"
or $y->{TYPE} eq "BITMAP"
or $y->{TYPE} eq "PIPE") {
$y->{BASEFILE} = $basename;
addType($y);
}
}
}
}
sub GenerateTypeLib()
{
return Parse::Pidl::Util::MyDumper(\%types);
}
RegisterScalars();
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Util.pm | ###################################################
# utility functions to support pidl
# Copyright [email protected] 2000
# released under the GNU GPL
package Parse::Pidl::Util;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(has_property property_matches ParseExpr ParseExprExt is_constant make_str unmake_str print_uuid MyDumper genpad);
use vars qw($VERSION);
$VERSION = '0.01';
use strict;
use Parse::Pidl::Expr;
use Parse::Pidl qw(error);
=head1 NAME
Parse::Pidl::Util - Generic utility functions for pidl
=head1 SYNOPSIS
use Parse::Pidl::Util;
=head1 DESCRIPTION
Simple module that contains a couple of trivial helper functions
used throughout the various pidl modules.
=head1 FUNCTIONS
=over 4
=cut
=item B<MyDumper>
a dumper wrapper to prevent dependence on the Data::Dumper module
unless we actually need it
=cut
sub MyDumper($)
{
require Data::Dumper;
$Data::Dumper::Sortkeys = 1;
my $s = shift;
return Data::Dumper::Dumper($s);
}
=item B<has_property>
see if a pidl property list contains a given property
=cut
sub has_property($$)
{
my($e, $p) = @_;
return undef if (not defined($e->{PROPERTIES}));
return $e->{PROPERTIES}->{$p};
}
=item B<property_matches>
see if a pidl property matches a value
=cut
sub property_matches($$$)
{
my($e,$p,$v) = @_;
if (!defined has_property($e, $p)) {
return undef;
}
if ($e->{PROPERTIES}->{$p} =~ /$v/) {
return 1;
}
return undef;
}
=item B<is_constant>
return 1 if the string is a C constant
=cut
sub is_constant($)
{
my $s = shift;
return 1 if ($s =~ /^\d+$/);
return 1 if ($s =~ /^0x[0-9A-Fa-f]+$/);
return 0;
}
=item B<make_str>
return a "" quoted string, unless already quoted
=cut
sub make_str($)
{
my $str = shift;
if (substr($str, 0, 1) eq "\"") {
return $str;
}
return "\"$str\"";
}
=item B<unmake_str>
unquote a "" quoted string
=cut
sub unmake_str($)
{
my $str = shift;
$str =~ s/^\"(.*)\"$/$1/;
return $str;
}
=item B<print_uuid>
Print C representation of a UUID.
=cut
sub print_uuid($)
{
my ($uuid) = @_;
$uuid =~ s/"//g;
my ($time_low,$time_mid,$time_hi,$clock_seq,$node) = split /-/, $uuid;
return undef if not defined($node);
my @clock_seq = $clock_seq =~ /(..)/g;
my @node = $node =~ /(..)/g;
return "{0x$time_low,0x$time_mid,0x$time_hi," .
"{".join(',', map {"0x$_"} @clock_seq)."}," .
"{".join(',', map {"0x$_"} @node)."}}";
}
=item B<ParseExpr>
Interpret an IDL expression, substituting particular variables.
=cut
sub ParseExpr($$$)
{
my($expr, $varlist, $e) = @_;
my $x = new Parse::Pidl::Expr();
return $x->Run($expr, sub { my $x = shift; error($e, $x); },
# Lookup fn
sub { my $x = shift;
return($varlist->{$x}) if (defined($varlist->{$x}));
return $x;
},
undef, undef);
}
=item B<ParseExprExt>
Interpret an IDL expression, substituting particular variables. Can call
callbacks when pointers are being dereferenced or variables are being used.
=cut
sub ParseExprExt($$$$$)
{
my($expr, $varlist, $e, $deref, $use) = @_;
my $x = new Parse::Pidl::Expr();
return $x->Run($expr, sub { my $x = shift; error($e, $x); },
# Lookup fn
sub { my $x = shift;
return($varlist->{$x}) if (defined($varlist->{$x}));
return $x;
},
$deref, $use);
}
=item B<genpad>
return an empty string consisting of tabs and spaces suitable for proper indent
of C-functions.
=cut
sub genpad($)
{
my ($s) = @_;
my $nt = int((length($s)+1)/8);
my $lt = ($nt*8)-1;
my $ns = (length($s)-$lt);
return "\t"x($nt)." "x($ns);
}
=back
=cut
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba3/ClientNDR.pm | ###################################################
# Samba3 client generator for IDL structures
# on top of Samba4 style NDR functions
# Copyright [email protected] 2005-2006
# Copyright [email protected] 2008
# released under the GNU GPL
package Parse::Pidl::Samba3::ClientNDR;
use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(ParseFunction $res $res_hdr);
use strict;
use Parse::Pidl qw(fatal warning error);
use Parse::Pidl::Util qw(has_property ParseExpr genpad);
use Parse::Pidl::NDR qw(ContainsPipe);
use Parse::Pidl::Typelist qw(mapTypeName);
use Parse::Pidl::Samba4 qw(DeclLong);
use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv);
use vars qw($VERSION);
$VERSION = '0.01';
sub indent($) { my ($self) = @_; $self->{tabs}.="\t"; }
sub deindent($) { my ($self) = @_; $self->{tabs} = substr($self->{tabs}, 1); }
sub pidl($$) { my ($self,$txt) = @_; $self->{res} .= $txt ? "$self->{tabs}$txt\n" : "\n"; }
sub pidl_hdr($$) { my ($self, $txt) = @_; $self->{res_hdr} .= "$txt\n"; }
sub fn_declare($$) { my ($self,$n) = @_; $self->pidl($n); $self->pidl_hdr("$n;"); }
sub new($)
{
my ($class) = shift;
my $self = { res => "", res_hdr => "", tabs => "" };
bless($self, $class);
}
sub ElementDirection($)
{
my ($e) = @_;
return "[in,out]" if (has_property($e, "in") and has_property($e, "out"));
return "[in]" if (has_property($e, "in"));
return "[out]" if (has_property($e, "out"));
return "[in,out]";
}
sub HeaderProperties($$)
{
my($props,$ignores) = @_;
my $ret = "";
foreach my $d (sort(keys %{$props})) {
next if (grep(/^$d$/, @$ignores));
if($props->{$d} ne "1") {
$ret.= "$d($props->{$d}),";
} else {
$ret.="$d,";
}
}
if ($ret) {
return "[" . substr($ret, 0, -1) . "]";
}
}
sub ParseInvalidResponse($$)
{
my ($self, $type) = @_;
if ($type eq "sync") {
$self->pidl("return NT_STATUS_INVALID_NETWORK_RESPONSE;");
} elsif ($type eq "async") {
$self->pidl("tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);");
$self->pidl("return;");
} else {
die("ParseInvalidResponse($type)");
}
}
sub ParseFunctionAsyncState($$$)
{
my ($self, $if, $fn) = @_;
my $state_str = "struct rpccli_$fn->{NAME}_state";
my $done_fn = "rpccli_$fn->{NAME}_done";
$self->pidl("$state_str {");
$self->indent;
$self->pidl("TALLOC_CTX *out_mem_ctx;");
if (defined($fn->{RETURN_TYPE})) {
$self->pidl(mapTypeName($fn->{RETURN_TYPE}). " result;");
}
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl("static void $done_fn(struct tevent_req *subreq);");
$self->pidl("");
}
sub ParseFunctionAsyncSend($$$)
{
my ($self, $if, $fn) = @_;
my $fn_args = "";
my $uif = uc($if);
my $ufn = "NDR_".uc($fn->{NAME});
my $state_str = "struct rpccli_$fn->{NAME}_state";
my $done_fn = "rpccli_$fn->{NAME}_done";
my $out_mem_ctx = "rpccli_$fn->{NAME}_out_memory";
my $fn_str = "struct tevent_req *rpccli_$fn->{NAME}_send";
my $pad = genpad($fn_str);
$fn_args .= "TALLOC_CTX *mem_ctx";
$fn_args .= ",\n" . $pad . "struct tevent_context *ev";
$fn_args .= ",\n" . $pad . "struct rpc_pipe_client *cli";
foreach (@{$fn->{ELEMENTS}}) {
my $dir = ElementDirection($_);
my $prop = HeaderProperties($_->{PROPERTIES}, ["in", "out"]);
$fn_args .= ",\n" . $pad . DeclLong($_, "_") . " /* $dir $prop */";
}
$self->fn_declare("$fn_str($fn_args)");
$self->pidl("{");
$self->indent;
$self->pidl("struct tevent_req *req;");
$self->pidl("$state_str *state;");
$self->pidl("struct tevent_req *subreq;");
$self->pidl("");
$self->pidl("req = tevent_req_create(mem_ctx, &state,");
$self->pidl("\t\t\t$state_str);");
$self->pidl("if (req == NULL) {");
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("state->out_mem_ctx = NULL;");
$self->pidl("");
my $out_params = 0;
foreach (@{$fn->{ELEMENTS}}) {
if (grep(/out/, @{$_->{DIRECTION}})) {
$out_params++;
}
}
if ($out_params > 0) {
$self->pidl("state->out_mem_ctx = talloc_named_const(state, 0,");
$self->pidl("\t\t \"$out_mem_ctx\");");
$self->pidl("if (tevent_req_nomem(state->out_mem_ctx, req)) {");
$self->indent;
$self->pidl("return tevent_req_post(req, ev);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
$fn_str = "subreq = dcerpc_$fn->{NAME}_send";
$pad = "\t" . genpad($fn_str);
$fn_args = "state,\n" . $pad . "ev,\n" . $pad . "cli->binding_handle";
foreach (@{$fn->{ELEMENTS}}) {
$fn_args .= ",\n" . $pad . "_". $_->{NAME};
}
$self->pidl("$fn_str($fn_args);");
$self->pidl("if (tevent_req_nomem(subreq, req)) {");
$self->indent;
$self->pidl("return tevent_req_post(req, ev);");
$self->deindent;
$self->pidl("}");
$self->pidl("tevent_req_set_callback(subreq, $done_fn, req);");
$self->pidl("return req;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunctionAsyncDone($$$)
{
my ($self, $if, $fn) = @_;
my $state_str = "struct rpccli_$fn->{NAME}_state";
my $done_fn = "rpccli_$fn->{NAME}_done";
$self->pidl("static void $done_fn(struct tevent_req *subreq)");
$self->pidl("{");
$self->indent;
$self->pidl("struct tevent_req *req = tevent_req_callback_data(");
$self->pidl("\tsubreq, struct tevent_req);");
$self->pidl("$state_str *state = tevent_req_data(");
$self->pidl("\treq, $state_str);");
$self->pidl("NTSTATUS status;");
$self->pidl("TALLOC_CTX *mem_ctx;");
$self->pidl("");
$self->pidl("if (state->out_mem_ctx) {");
$self->indent;
$self->pidl("mem_ctx = state->out_mem_ctx;");
$self->deindent;
$self->pidl("} else {");
$self->indent;
$self->pidl("mem_ctx = state;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
my $fn_str = "status = dcerpc_$fn->{NAME}_recv";
my $pad = "\t" . genpad($fn_str);
my $fn_args = "subreq,\n" . $pad . "mem_ctx";
if (defined($fn->{RETURN_TYPE})) {
$fn_args .= ",\n" . $pad . "&state->result";
}
$self->pidl("$fn_str($fn_args);");
$self->pidl("TALLOC_FREE(subreq);");
$self->pidl("if (!NT_STATUS_IS_OK(status)) {");
$self->indent;
$self->pidl("tevent_req_nterror(req, status);");
$self->pidl("return;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("tevent_req_done(req);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunctionAsyncRecv($$$)
{
my ($self, $if, $fn) = @_;
my $fn_args = "";
my $state_str = "struct rpccli_$fn->{NAME}_state";
my $fn_str = "NTSTATUS rpccli_$fn->{NAME}_recv";
my $pad = genpad($fn_str);
$fn_args .= "struct tevent_req *req,\n" . $pad . "TALLOC_CTX *mem_ctx";
if (defined($fn->{RETURN_TYPE})) {
$fn_args .= ",\n" . $pad . "$fn->{RETURN_TYPE} *result";
}
$self->fn_declare("$fn_str($fn_args)");
$self->pidl("{");
$self->indent;
$self->pidl("$state_str *state = tevent_req_data(");
$self->pidl("\treq, $state_str);");
$self->pidl("NTSTATUS status;");
$self->pidl("");
$self->pidl("if (tevent_req_is_nterror(req, &status)) {");
$self->indent;
$self->pidl("tevent_req_received(req);");
$self->pidl("return status;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("/* Steal possible out parameters to the callers context */");
$self->pidl("talloc_steal(mem_ctx, state->out_mem_ctx);");
$self->pidl("");
if (defined($fn->{RETURN_TYPE})) {
$self->pidl("/* Return result */");
$self->pidl("*result = state->result;");
$self->pidl("");
}
$self->pidl("tevent_req_received(req);");
$self->pidl("return NT_STATUS_OK;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunctionSync($$$)
{
my ($self, $if, $fn) = @_;
my $fn_args = "";
my $uif = uc($if);
my $ufn = "NDR_".uc($fn->{NAME});
my $fn_str = "NTSTATUS rpccli_$fn->{NAME}";
my $pad = genpad($fn_str);
$fn_args .= "struct rpc_pipe_client *cli,\n" . $pad . "TALLOC_CTX *mem_ctx";
foreach (@{$fn->{ELEMENTS}}) {
my $dir = ElementDirection($_);
my $prop = HeaderProperties($_->{PROPERTIES}, ["in", "out"]);
$fn_args .= ",\n" . $pad . DeclLong($_, "_") . " /* $dir $prop */";
}
if (defined($fn->{RETURN_TYPE}) && ($fn->{RETURN_TYPE} eq "WERROR")) {
$fn_args .= ",\n" . $pad . "WERROR *werror";
}
$self->fn_declare("$fn_str($fn_args)");
$self->pidl("{");
$self->indent;
if (defined($fn->{RETURN_TYPE})) {
$self->pidl(mapTypeName($fn->{RETURN_TYPE})." result;");
}
$self->pidl("NTSTATUS status;");
$self->pidl("");
$fn_str = "status = dcerpc_$fn->{NAME}";
$pad = "\t" . genpad($fn_str);
$fn_args = "cli->binding_handle,\n" . $pad . "mem_ctx";
foreach (@{$fn->{ELEMENTS}}) {
$fn_args .= ",\n" . $pad . "_". $_->{NAME};
}
if (defined($fn->{RETURN_TYPE})) {
$fn_args .= ",\n" . $pad . "&result";
}
$self->pidl("$fn_str($fn_args);");
$self->pidl("if (!NT_STATUS_IS_OK(status)) {");
$self->indent;
$self->pidl("return status;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("/* Return result */");
if (not $fn->{RETURN_TYPE}) {
$self->pidl("return NT_STATUS_OK;");
} elsif ($fn->{RETURN_TYPE} eq "NTSTATUS") {
$self->pidl("return result;");
} elsif ($fn->{RETURN_TYPE} eq "WERROR") {
$self->pidl("if (werror) {");
$self->indent;
$self->pidl("*werror = result;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("return werror_to_ntstatus(result);");
} else {
warning($fn->{ORIGINAL}, "Unable to convert $fn->{RETURN_TYPE} to NTSTATUS");
$self->pidl("return NT_STATUS_OK;");
}
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunction($$$)
{
my ($self, $if, $fn) = @_;
$self->ParseFunctionAsyncState($if, $fn);
$self->ParseFunctionAsyncSend($if, $fn);
$self->ParseFunctionAsyncDone($if, $fn);
$self->ParseFunctionAsyncRecv($if, $fn);
$self->ParseFunctionSync($if, $fn);
}
sub ParseInterface($$)
{
my ($self, $if) = @_;
my $uif = uc($if->{NAME});
$self->pidl_hdr("#ifndef __CLI_$uif\__");
$self->pidl_hdr("#define __CLI_$uif\__");
foreach my $fn (@{$if->{FUNCTIONS}}) {
next if has_property($fn, "noopnum");
next if has_property($fn, "todo");
my $skip = 0;
foreach my $e (@{$fn->{ELEMENTS}}) {
if (ContainsPipe($e, $e->{LEVELS}[0])) {
$skip = 1;
last;
}
}
next if $skip;
$self->ParseFunction($if->{NAME}, $fn);
}
$self->pidl_hdr("#endif /* __CLI_$uif\__ */");
}
sub Parse($$$$)
{
my($self,$ndr,$header,$c_header) = @_;
$self->pidl("/*");
$self->pidl(" * Unix SMB/CIFS implementation.");
$self->pidl(" * client auto-generated by pidl. DO NOT MODIFY!");
$self->pidl(" */");
$self->pidl("");
$self->pidl("#include \"includes.h\"");
$self->pidl("#include \"$header\"");
$self->pidl_hdr("#include \"$c_header\"");
$self->pidl("");
foreach (@$ndr) {
$self->ParseInterface($_) if ($_->{TYPE} eq "INTERFACE");
}
return ($self->{res}, $self->{res_hdr});
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba3/ServerNDR.pm | ###################################################
# Samba3 server generator for IDL structures
# on top of Samba4 style NDR functions
# Copyright [email protected] 2005-2006
# released under the GNU GPL
package Parse::Pidl::Samba3::ServerNDR;
use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(DeclLevel);
use strict;
use Parse::Pidl qw(warning error fatal);
use Parse::Pidl::Typelist qw(mapTypeName scalar_is_reference);
use Parse::Pidl::Util qw(ParseExpr has_property is_constant);
use Parse::Pidl::NDR qw(GetNextLevel ContainsPipe);
use Parse::Pidl::Samba4 qw(ElementStars DeclLong);
use Parse::Pidl::Samba4::Header qw(GenerateFunctionOutEnv);
use vars qw($VERSION);
$VERSION = '0.01';
my $res;
my $res_hdr;
my $tabs = "";
sub pidl_reset() { $res=""; $res_hdr="", $tabs=""; }
sub pidl_return() { my $s = $res; my $h = $res_hdr; pidl_reset(); return ($s, $h) }
sub indent() { $tabs.="\t"; }
sub deindent() { $tabs = substr($tabs, 1); }
sub pidl($) { my ($txt) = @_; $res .= $txt?$tabs.(shift)."\n":"\n"; }
sub pidl_hdr($) { $res_hdr .= (shift)."\n"; }
sub fn_declare($) { my ($n) = @_; pidl $n; pidl_hdr "$n;"; }
sub DeclLevel($$)
{
my ($e, $l) = @_;
my $res = "";
if (has_property($e, "charset")) {
$res .= "const char";
} else {
$res .= mapTypeName($e->{TYPE});
}
my $stars = ElementStars($e, $l);
$res .= " ".$stars unless ($stars eq "");
return $res;
}
sub AllocOutVar($$$$$$$)
{
my ($e, $mem_ctx, $name, $env, $check, $cleanup, $return) = @_;
my $l = $e->{LEVELS}[0];
# we skip pointer to arrays
if ($l->{TYPE} eq "POINTER") {
my $nl = GetNextLevel($e, $l);
$l = $nl if ($nl->{TYPE} eq "ARRAY");
} elsif
# we don't support multi-dimentional arrays yet
($l->{TYPE} eq "ARRAY") {
my $nl = GetNextLevel($e, $l);
if ($nl->{TYPE} eq "ARRAY") {
fatal($e->{ORIGINAL},"multi-dimentional [out] arrays are not supported!");
}
} else {
# neither pointer nor array, no need to alloc something.
return;
}
if ($l->{TYPE} eq "ARRAY") {
unless(defined($l->{SIZE_IS})) {
error($e->{ORIGINAL}, "No size known for array `$e->{NAME}'");
pidl "#error No size known for array `$e->{NAME}'";
} else {
my $size = ParseExpr($l->{SIZE_IS}, $env, $e);
pidl "$name = talloc_zero_array($mem_ctx, " . DeclLevel($e, 1) . ", $size);";
}
} else {
pidl "$name = talloc_zero($mem_ctx, " . DeclLevel($e, 1) . ");";
}
pidl "if (" . $check->($name) . ") {";
indent;
pidl $cleanup->($name) if defined($cleanup);
pidl $return->($name) if defined($return);
deindent;
pidl "}";
pidl "";
}
sub CallWithStruct($$$$$$)
{
my ($pipes_struct, $mem_ctx, $fn, $check, $cleanup, $return) = @_;
my $env = GenerateFunctionOutEnv($fn);
my $hasout = 0;
foreach (@{$fn->{ELEMENTS}}) {
if (grep(/out/, @{$_->{DIRECTION}})) { $hasout = 1; }
}
pidl "ZERO_STRUCT(r->out);" if ($hasout);
foreach (@{$fn->{ELEMENTS}}) {
my @dir = @{$_->{DIRECTION}};
if (grep(/in/, @dir) and grep(/out/, @dir)) {
pidl "r->out.$_->{NAME} = r->in.$_->{NAME};";
}
}
foreach (@{$fn->{ELEMENTS}}) {
next if ContainsPipe($_, $_->{LEVELS}[0]);
my @dir = @{$_->{DIRECTION}};
if (grep(/in/, @dir) and grep(/out/, @dir)) {
# noop
} elsif (grep(/out/, @dir) and not
has_property($_, "represent_as")) {
AllocOutVar($_, $mem_ctx, "r->out.$_->{NAME}", $env,
$check, $cleanup, $return);
}
}
my $proto = "_$fn->{NAME}(struct pipes_struct *p, struct $fn->{NAME} *r)";
my $ret = "_$fn->{NAME}($pipes_struct, r)";
if ($fn->{RETURN_TYPE}) {
$ret = "r->out.result = $ret";
$proto = mapTypeName($fn->{RETURN_TYPE})." $proto";
} else {
$proto = "void $proto";
}
pidl_hdr "$proto;";
pidl "$ret;";
}
sub ParseFunction($$)
{
my ($if,$fn) = @_;
my $op = "NDR_".uc($fn->{NAME});
pidl "static bool api_$fn->{NAME}(struct pipes_struct *p)";
pidl "{";
indent;
pidl "const struct ndr_interface_call *call;";
pidl "struct ndr_pull *pull;";
pidl "struct ndr_push *push;";
pidl "enum ndr_err_code ndr_err;";
pidl "struct $fn->{NAME} *r;";
pidl "";
pidl "call = &ndr_table_$if->{NAME}.calls[$op];";
pidl "";
pidl "r = talloc(talloc_tos(), struct $fn->{NAME});";
pidl "if (r == NULL) {";
pidl "\treturn false;";
pidl "}";
pidl "";
pidl "pull = ndr_pull_init_blob(&p->in_data.data, r);";
pidl "if (pull == NULL) {";
pidl "\ttalloc_free(r);";
pidl "\treturn false;";
pidl "}";
pidl "";
pidl "pull->flags |= LIBNDR_FLAG_REF_ALLOC;";
pidl "if (p->endian) {";
pidl "\tpull->flags |= LIBNDR_FLAG_BIGENDIAN;";
pidl "}";
pidl "ndr_err = call->ndr_pull(pull, NDR_IN, r);";
pidl "if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {";
pidl "\ttalloc_free(r);";
pidl "\treturn false;";
pidl "}";
pidl "";
pidl "if (DEBUGLEVEL >= 10) {";
pidl "\tNDR_PRINT_FUNCTION_DEBUG($fn->{NAME}, NDR_IN, r);";
pidl "}";
pidl "";
CallWithStruct("p", "r", $fn,
sub ($) {
my ($name) = @_;
return "${name} == NULL";
},
sub ($) {
my ($name) = @_;
return "talloc_free(r);";
},
sub ($) {
my ($name) = @_;
return "return false;";
}
);
pidl "";
pidl "if (p->fault_state) {";
pidl "\ttalloc_free(r);";
pidl "\t/* Return true here, srv_pipe_hnd.c will take care */";
pidl "\treturn true;";
pidl "}";
pidl "";
pidl "if (DEBUGLEVEL >= 10) {";
pidl "\tNDR_PRINT_FUNCTION_DEBUG($fn->{NAME}, NDR_OUT | NDR_SET_VALUES, r);";
pidl "}";
pidl "";
pidl "push = ndr_push_init_ctx(r);";
pidl "if (push == NULL) {";
pidl "\ttalloc_free(r);";
pidl "\treturn false;";
pidl "}";
pidl "";
pidl "/*";
pidl " * carry over the pointer count to the reply in case we are";
pidl " * using full pointer. See NDR specification for full pointers";
pidl " */";
pidl "push->ptr_count = pull->ptr_count;";
pidl "";
pidl "ndr_err = call->ndr_push(push, NDR_OUT, r);";
pidl "if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {";
pidl "\ttalloc_free(r);";
pidl "\treturn false;";
pidl "}";
pidl "";
pidl "p->out_data.rdata = ndr_push_blob(push);";
pidl "talloc_steal(p->mem_ctx, p->out_data.rdata.data);";
pidl "";
pidl "talloc_free(r);";
pidl "";
pidl "return true;";
deindent;
pidl "}";
pidl "";
}
sub ParseInterface($)
{
my $if = shift;
my $uif = uc($if->{NAME});
pidl_hdr "#ifndef __SRV_$uif\__";
pidl_hdr "#define __SRV_$uif\__";
foreach (@{$if->{FUNCTIONS}}) {
next if ($_->{PROPERTIES}{noopnum});
ParseFunction($if, $_);
}
pidl "";
pidl "/* Tables */";
pidl "static const struct api_struct api_$if->{NAME}_cmds[] = ";
pidl "{";
indent;
foreach (@{$if->{FUNCTIONS}}) {
next if ($_->{PROPERTIES}{noopnum});
pidl "{\"" . uc($_->{NAME}) . "\", NDR_" . uc($_->{NAME}) . ", api_$_->{NAME}},";
}
deindent;
pidl "};";
pidl "";
pidl_hdr "const struct api_struct *$if->{NAME}_get_pipe_fns(int *n_fns);";
pidl "const struct api_struct *$if->{NAME}_get_pipe_fns(int *n_fns)";
pidl "{";
indent;
pidl "*n_fns = sizeof(api_$if->{NAME}_cmds) / sizeof(struct api_struct);";
pidl "return api_$if->{NAME}_cmds;";
deindent;
pidl "}";
pidl "";
if (not has_property($if, "no_srv_register")) {
pidl_hdr "struct rpc_srv_callbacks;";
pidl_hdr "NTSTATUS rpc_$if->{NAME}_init(const struct rpc_srv_callbacks *rpc_srv_cb);";
pidl "NTSTATUS rpc_$if->{NAME}_init(const struct rpc_srv_callbacks *rpc_srv_cb)";
pidl "{";
pidl "\treturn rpc_srv_register(SMB_RPC_INTERFACE_VERSION, \"$if->{NAME}\", \"$if->{NAME}\", \&ndr_table_$if->{NAME}, api_$if->{NAME}_cmds, sizeof(api_$if->{NAME}_cmds) / sizeof(struct api_struct), rpc_srv_cb);";
pidl "}";
pidl "";
pidl_hdr "NTSTATUS rpc_$if->{NAME}_shutdown(void);";
pidl "NTSTATUS rpc_$if->{NAME}_shutdown(void)";
pidl "{";
pidl "\treturn rpc_srv_unregister(\&ndr_table_$if->{NAME});";
pidl "}";
}
pidl_hdr "#endif /* __SRV_$uif\__ */";
}
sub Parse($$$)
{
my($ndr,$header,$ndr_header) = @_;
pidl_reset();
pidl "/*";
pidl " * Unix SMB/CIFS implementation.";
pidl " * server auto-generated by pidl. DO NOT MODIFY!";
pidl " */";
pidl "";
pidl "#include \"includes.h\"";
pidl "#include \"ntdomain.h\"";
pidl "#include \"$header\"";
pidl_hdr "#include \"$ndr_header\"";
pidl "";
foreach (@$ndr) {
ParseInterface($_) if ($_->{TYPE} eq "INTERFACE");
}
return pidl_return();
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/Header.pm | ###################################################
# create C header files for an IDL structure
# Copyright [email protected] 2000
# Copyright [email protected] 2005
# released under the GNU GPL
package Parse::Pidl::Samba4::Header;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(GenerateFunctionInEnv GenerateFunctionOutEnv EnvSubstituteValue GenerateStructEnv);
use strict;
use Parse::Pidl qw(fatal);
use Parse::Pidl::Typelist qw(mapTypeName scalar_is_reference);
use Parse::Pidl::Util qw(has_property is_constant unmake_str ParseExpr);
use Parse::Pidl::Samba4 qw(is_intree ElementStars ArrayBrackets choose_header);
use vars qw($VERSION);
$VERSION = '0.01';
my($res);
my($tab_depth);
sub pidl($) { $res .= shift; }
sub tabs()
{
my $res = "";
$res .="\t" foreach (1..$tab_depth);
return $res;
}
#####################################################################
# parse a properties list
sub HeaderProperties($$)
{
my($props,$ignores) = @_;
my $ret = "";
foreach my $d (sort(keys %{$props})) {
next if (grep(/^$d$/, @$ignores));
if($props->{$d} ne "1") {
$ret.= "$d($props->{$d}),";
} else {
$ret.="$d,";
}
}
if ($ret) {
pidl "/* [" . substr($ret, 0, -1) . "] */";
}
}
#####################################################################
# parse a structure element
sub HeaderElement($)
{
my($element) = shift;
pidl tabs();
if (has_property($element, "represent_as")) {
pidl mapTypeName($element->{PROPERTIES}->{represent_as})." ";
} else {
if (ref($element->{TYPE}) eq "HASH") {
HeaderType($element, $element->{TYPE}, $element->{TYPE}->{NAME});
} else {
HeaderType($element, $element->{TYPE}, "");
}
pidl " ".ElementStars($element);
}
pidl $element->{NAME};
pidl ArrayBrackets($element);
pidl ";";
if (defined $element->{PROPERTIES}) {
HeaderProperties($element->{PROPERTIES}, ["in", "out"]);
}
pidl "\n";
}
#####################################################################
# parse a struct
sub HeaderStruct($$;$)
{
my($struct,$name,$tail) = @_;
pidl "struct $name";
pidl $tail if defined($tail) and not defined($struct->{ELEMENTS});
return if (not defined($struct->{ELEMENTS}));
pidl " {\n";
$tab_depth++;
my $el_count=0;
foreach (@{$struct->{ELEMENTS}}) {
HeaderElement($_);
$el_count++;
}
if ($el_count == 0) {
# some compilers can't handle empty structures
pidl tabs()."char _empty_;\n";
}
$tab_depth--;
pidl tabs()."}";
if (defined $struct->{PROPERTIES}) {
HeaderProperties($struct->{PROPERTIES}, []);
}
pidl $tail if defined($tail);
}
#####################################################################
# parse a enum
sub HeaderEnum($$;$)
{
my($enum,$name,$tail) = @_;
my $first = 1;
pidl "enum $name";
if (defined($enum->{ELEMENTS})) {
pidl "\n#ifndef USE_UINT_ENUMS\n";
pidl " {\n";
$tab_depth++;
foreach my $e (@{$enum->{ELEMENTS}}) {
my @enum_els = ();
unless ($first) { pidl ",\n"; }
$first = 0;
pidl tabs();
@enum_els = split(/=/, $e);
if (@enum_els == 2) {
pidl $enum_els[0];
pidl "=(int)";
pidl "(";
pidl $enum_els[1];
pidl ")";
} else {
pidl $e;
}
}
pidl "\n";
$tab_depth--;
pidl "}";
pidl "\n";
pidl "#else\n";
my $count = 0;
my $with_val = 0;
my $without_val = 0;
pidl " { __do_not_use_enum_$name=0x7FFFFFFF}\n";
foreach my $e (@{$enum->{ELEMENTS}}) {
my $t = "$e";
my $name;
my $value;
if ($t =~ /(.*)=(.*)/) {
$name = $1;
$value = $2;
$with_val = 1;
fatal($e->{ORIGINAL}, "you can't mix enum member with values and without values!")
unless ($without_val == 0);
} else {
$name = $t;
$value = $count++;
$without_val = 1;
fatal($e->{ORIGINAL}, "you can't mix enum member with values and without values!")
unless ($with_val == 0);
}
pidl "#define $name ( $value )\n";
}
pidl "#endif\n";
}
pidl $tail if defined($tail);
}
#####################################################################
# parse a bitmap
sub HeaderBitmap($$)
{
my($bitmap,$name) = @_;
return unless defined($bitmap->{ELEMENTS});
pidl "/* bitmap $name */\n";
pidl "#define $_\n" foreach (@{$bitmap->{ELEMENTS}});
pidl "\n";
}
#####################################################################
# parse a union
sub HeaderUnion($$;$)
{
my($union,$name,$tail) = @_;
my %done = ();
pidl "union $name";
pidl $tail if defined($tail) and not defined($union->{ELEMENTS});
return if (not defined($union->{ELEMENTS}));
pidl " {\n";
$tab_depth++;
my $needed = 0;
foreach my $e (@{$union->{ELEMENTS}}) {
if ($e->{TYPE} ne "EMPTY") {
if (! defined $done{$e->{NAME}}) {
HeaderElement($e);
}
$done{$e->{NAME}} = 1;
$needed++;
}
}
if (!$needed) {
# sigh - some compilers don't like empty structures
pidl tabs()."int _dummy_element;\n";
}
$tab_depth--;
pidl "}";
if (defined $union->{PROPERTIES}) {
HeaderProperties($union->{PROPERTIES}, []);
}
pidl $tail if defined($tail);
}
#####################################################################
# parse a pipe
sub HeaderPipe($$;$)
{
my($pipe,$name,$tail) = @_;
my $struct = $pipe->{DATA};
my $e = $struct->{ELEMENTS}[1];
pidl "struct $name;\n";
pidl "struct $struct->{NAME} {\n";
$tab_depth++;
pidl tabs()."uint32_t count;\n";
pidl tabs().mapTypeName($e->{TYPE})." *array;\n";
$tab_depth--;
pidl "}";
if (defined $struct->{PROPERTIES}) {
HeaderProperties($struct->{PROPERTIES}, []);
}
pidl $tail if defined($tail);
}
#####################################################################
# parse a type
sub HeaderType($$$;$)
{
my($e,$data,$name,$tail) = @_;
if (ref($data) eq "HASH") {
($data->{TYPE} eq "ENUM") && HeaderEnum($data, $name, $tail);
($data->{TYPE} eq "BITMAP") && HeaderBitmap($data, $name);
($data->{TYPE} eq "STRUCT") && HeaderStruct($data, $name, $tail);
($data->{TYPE} eq "UNION") && HeaderUnion($data, $name, $tail);
($data->{TYPE} eq "PIPE") && HeaderPipe($data, $name, $tail);
return;
}
if (has_property($e, "charset")) {
pidl "const char";
} else {
pidl mapTypeName($e->{TYPE});
}
pidl $tail if defined($tail);
}
#####################################################################
# parse a typedef
sub HeaderTypedef($;$)
{
my($typedef,$tail) = @_;
# Don't print empty "enum foo;", since some compilers don't like it.
return if ($typedef->{DATA}->{TYPE} eq "ENUM" and not defined($typedef->{DATA}->{ELEMENTS}));
HeaderType($typedef, $typedef->{DATA}, $typedef->{NAME}, $tail) if defined ($typedef->{DATA});
}
#####################################################################
# parse a const
sub HeaderConst($)
{
my($const) = shift;
if (!defined($const->{ARRAY_LEN}[0])) {
pidl "#define $const->{NAME}\t( $const->{VALUE} )\n";
} else {
pidl "#define $const->{NAME}\t $const->{VALUE}\n";
}
}
sub ElementDirection($)
{
my ($e) = @_;
return "inout" if (has_property($e, "in") and has_property($e, "out"));
return "in" if (has_property($e, "in"));
return "out" if (has_property($e, "out"));
return "inout";
}
#####################################################################
# parse a function
sub HeaderFunctionInOut($$)
{
my($fn,$prop) = @_;
return unless defined($fn->{ELEMENTS});
foreach my $e (@{$fn->{ELEMENTS}}) {
HeaderElement($e) if (ElementDirection($e) eq $prop);
}
}
#####################################################################
# determine if we need an "in" or "out" section
sub HeaderFunctionInOut_needed($$)
{
my($fn,$prop) = @_;
return 1 if ($prop eq "out" && defined($fn->{RETURN_TYPE}));
return undef unless defined($fn->{ELEMENTS});
foreach my $e (@{$fn->{ELEMENTS}}) {
return 1 if (ElementDirection($e) eq $prop);
}
return undef;
}
my %headerstructs;
#####################################################################
# parse a function
sub HeaderFunction($)
{
my($fn) = shift;
return if ($headerstructs{$fn->{NAME}});
$headerstructs{$fn->{NAME}} = 1;
pidl "\nstruct $fn->{NAME} {\n";
$tab_depth++;
my $needed = 0;
if (HeaderFunctionInOut_needed($fn, "in") or
HeaderFunctionInOut_needed($fn, "inout")) {
pidl tabs()."struct {\n";
$tab_depth++;
HeaderFunctionInOut($fn, "in");
HeaderFunctionInOut($fn, "inout");
$tab_depth--;
pidl tabs()."} in;\n\n";
$needed++;
}
if (HeaderFunctionInOut_needed($fn, "out") or
HeaderFunctionInOut_needed($fn, "inout")) {
pidl tabs()."struct {\n";
$tab_depth++;
HeaderFunctionInOut($fn, "out");
HeaderFunctionInOut($fn, "inout");
if (defined($fn->{RETURN_TYPE})) {
pidl tabs().mapTypeName($fn->{RETURN_TYPE}) . " result;\n";
}
$tab_depth--;
pidl tabs()."} out;\n\n";
$needed++;
}
if (!$needed) {
# sigh - some compilers don't like empty structures
pidl tabs()."int _dummy_element;\n";
}
$tab_depth--;
pidl "};\n\n";
}
sub HeaderImport
{
my @imports = @_;
foreach my $import (@imports) {
$import = unmake_str($import);
$import =~ s/\.idl$//;
pidl choose_header("librpc/gen_ndr/$import\.h", "gen_ndr/$import.h") . "\n";
}
}
sub HeaderInclude
{
my @includes = @_;
foreach (@includes) {
pidl "#include $_\n";
}
}
#####################################################################
# parse the interface definitions
sub HeaderInterface($)
{
my($interface) = shift;
pidl "#ifndef _HEADER_$interface->{NAME}\n";
pidl "#define _HEADER_$interface->{NAME}\n\n";
foreach my $c (@{$interface->{CONSTS}}) {
HeaderConst($c);
}
foreach my $t (@{$interface->{TYPES}}) {
HeaderTypedef($t, ";\n\n") if ($t->{TYPE} eq "TYPEDEF");
HeaderStruct($t, $t->{NAME}, ";\n\n") if ($t->{TYPE} eq "STRUCT");
HeaderUnion($t, $t->{NAME}, ";\n\n") if ($t->{TYPE} eq "UNION");
HeaderEnum($t, $t->{NAME}, ";\n\n") if ($t->{TYPE} eq "ENUM");
HeaderBitmap($t, $t->{NAME}) if ($t->{TYPE} eq "BITMAP");
HeaderPipe($t, $t->{NAME}, "\n\n") if ($t->{TYPE} eq "PIPE");
}
foreach my $fn (@{$interface->{FUNCTIONS}}) {
HeaderFunction($fn);
}
pidl "#endif /* _HEADER_$interface->{NAME} */\n";
}
sub HeaderQuote($)
{
my($quote) = shift;
pidl unmake_str($quote->{DATA}) . "\n";
}
#####################################################################
# parse a parsed IDL into a C header
sub Parse($)
{
my($ndr) = shift;
$tab_depth = 0;
$res = "";
%headerstructs = ();
pidl "/* header auto-generated by pidl */\n\n";
my $ifacename = "";
# work out a unique interface name
foreach (@{$ndr}) {
if ($_->{TYPE} eq "INTERFACE") {
$ifacename = $_->{NAME};
last;
}
}
pidl "#ifndef _PIDL_HEADER_$ifacename\n";
pidl "#define _PIDL_HEADER_$ifacename\n\n";
if (!is_intree()) {
pidl "#include <util/data_blob.h>\n";
}
pidl "#include <stdint.h>\n";
pidl "\n";
# FIXME: Include this only if NTSTATUS was actually used
pidl choose_header("libcli/util/ntstatus.h", "core/ntstatus.h") . "\n";
pidl "\n";
foreach (@{$ndr}) {
($_->{TYPE} eq "CPP_QUOTE") && HeaderQuote($_);
($_->{TYPE} eq "INTERFACE") && HeaderInterface($_);
($_->{TYPE} eq "IMPORT") && HeaderImport(@{$_->{PATHS}});
($_->{TYPE} eq "INCLUDE") && HeaderInclude(@{$_->{PATHS}});
}
pidl "#endif /* _PIDL_HEADER_$ifacename */\n";
return $res;
}
sub GenerateStructEnv($$)
{
my ($x, $v) = @_;
my %env;
foreach my $e (@{$x->{ELEMENTS}}) {
$env{$e->{NAME}} = "$v->$e->{NAME}";
}
$env{"this"} = $v;
return \%env;
}
sub EnvSubstituteValue($$)
{
my ($env,$s) = @_;
# Substitute the value() values in the env
foreach my $e (@{$s->{ELEMENTS}}) {
next unless (defined(my $v = has_property($e, "value")));
$env->{$e->{NAME}} = ParseExpr($v, $env, $e);
}
return $env;
}
sub GenerateFunctionInEnv($;$)
{
my ($fn, $base) = @_;
my %env;
$base = "r->" unless defined($base);
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep (/in/, @{$e->{DIRECTION}})) {
$env{$e->{NAME}} = $base."in.$e->{NAME}";
}
}
return \%env;
}
sub GenerateFunctionOutEnv($;$)
{
my ($fn, $base) = @_;
my %env;
$base = "r->" unless defined($base);
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep (/out/, @{$e->{DIRECTION}})) {
$env{$e->{NAME}} = $base."out.$e->{NAME}";
} elsif (grep (/in/, @{$e->{DIRECTION}})) {
$env{$e->{NAME}} = $base."in.$e->{NAME}";
}
}
return \%env;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/Python.pm | ###################################################
# Python function wrapper generator
# Copyright [email protected] 2007-2008
# released under the GNU GPL
package Parse::Pidl::Samba4::Python;
use Exporter;
@ISA = qw(Exporter);
use strict;
use Parse::Pidl qw(warning fatal error);
use Parse::Pidl::Typelist qw(hasType resolveType getType mapTypeName expandAlias bitmap_type_fn enum_type_fn);
use Parse::Pidl::Util qw(has_property ParseExpr unmake_str);
use Parse::Pidl::NDR qw(ReturnTypeElement GetPrevLevel GetNextLevel ContainsDeferred ContainsPipe is_charset_array);
use Parse::Pidl::CUtil qw(get_value_of get_pointer_to);
use Parse::Pidl::Samba4 qw(ArrayDynamicallyAllocated);
use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv EnvSubstituteValue GenerateStructEnv);
use vars qw($VERSION);
$VERSION = '0.01';
sub new($) {
my ($class) = @_;
my $self = { res => "", res_hdr => "", tabs => "",
constants => [], constants_uniq => {},
module_methods => [],
module_objects => [], module_objects_uniq => {},
ready_types => [],
module_imports => [], module_imports_uniq => {},
type_imports => [], type_imports_uniq => {},
patch_type_calls => [], prereadycode => [],
postreadycode => []};
bless($self, $class);
}
sub pidl_hdr ($$)
{
my $self = shift;
$self->{res_hdr} .= shift;
}
sub pidl($$)
{
my ($self, $d) = @_;
if ($d) {
if ((!($d =~ /^#/))) {
$self->{res} .= $self->{tabs};
}
$self->{res} .= $d;
}
$self->{res} .= "\n";
}
sub indent($)
{
my ($self) = @_;
$self->{tabs} .= "\t";
}
sub deindent($)
{
my ($self) = @_;
$self->{tabs} = substr($self->{tabs}, 0, -1);
}
sub PrettifyTypeName($$)
{
my ($name, $basename) = @_;
$basename =~ s/^.*\.([^.]+)$/\1/;
$name =~ s/^$basename\_//;
return $name;
}
sub Import
{
my $self = shift;
my @imports = @_;
foreach (@imports) {
$_ = unmake_str($_);
s/\.idl$//;
$self->pidl_hdr("#include \"librpc/gen_ndr/$_\.h\"\n");
$self->register_module_import("samba.dcerpc.$_");
}
}
sub Const($$)
{
my ($self, $const) = @_;
$self->register_constant($const->{NAME}, $const->{DTYPE}, $const->{VALUE});
}
sub register_constant($$$$)
{
my ($self, $name, $type, $value) = @_;
unless (defined $self->{constants_uniq}->{$name}) {
my $h = {"key" => $name, "val" => [$type, $value]};
push @{$self->{constants}}, $h;
$self->{constants_uniq}->{$name} = $h;
}
}
sub EnumAndBitmapConsts($$$)
{
my ($self, $name, $d) = @_;
return unless (defined($d->{ELEMENTS}));
foreach my $e (@{$d->{ELEMENTS}}) {
$e =~ /^([A-Za-z0-9_]+)/;
my $cname = $1;
$self->register_constant($cname, $d, $cname);
}
}
sub FromUnionToPythonFunction($$$$)
{
my ($self, $mem_ctx, $type, $switch, $name) = @_;
$self->pidl("PyObject *ret;");
$self->pidl("");
$self->pidl("switch ($switch) {");
$self->indent;
foreach my $e (@{$type->{ELEMENTS}}) {
$self->pidl("$e->{CASE}:");
$self->indent;
if ($e->{NAME}) {
$self->ConvertObjectToPython($mem_ctx, {}, $e, "$name->$e->{NAME}", "ret", "return NULL;");
} else {
$self->pidl("ret = Py_None;");
$self->pidl("Py_INCREF(ret);");
}
$self->pidl("return ret;");
$self->pidl("");
$self->deindent;
}
$self->deindent;
$self->pidl("}");
$self->pidl("PyErr_SetString(PyExc_TypeError, \"unknown union level\");");
$self->pidl("return NULL;");
}
sub FromPythonToUnionFunction($$$$$)
{
my ($self, $type, $typename, $switch, $mem_ctx, $name) = @_;
my $has_default = 0;
$self->pidl("$typename *ret = talloc_zero($mem_ctx, $typename);");
$self->pidl("switch ($switch) {");
$self->indent;
foreach my $e (@{$type->{ELEMENTS}}) {
$self->pidl("$e->{CASE}:");
if ($e->{CASE} eq "default") { $has_default = 1; }
$self->indent;
if ($e->{NAME}) {
$self->ConvertObjectFromPython({}, $mem_ctx, $e, $name, "ret->$e->{NAME}", "talloc_free(ret); return NULL;");
}
$self->pidl("break;");
$self->deindent;
$self->pidl("");
}
if (!$has_default) {
$self->pidl("default:");
$self->indent;
$self->pidl("PyErr_SetString(PyExc_TypeError, \"invalid union level value\");");
$self->pidl("talloc_free(ret);");
$self->pidl("ret = NULL;");
$self->deindent;
}
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("return ret;");
}
sub PythonElementGetSet($$$$$$) {
my ($self, $name, $cname, $ename, $e, $env) = @_;
my $varname = "object->$ename";
$self->pidl("static PyObject *py_$name\_get_$e->{NAME}(PyObject *obj, void *closure)");
$self->pidl("{");
$self->indent;
$self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(obj);");
$self->pidl("PyObject *py_$e->{NAME};");
$self->ConvertObjectToPython("pytalloc_get_mem_ctx(obj)", $env, $e, $varname, "py_$e->{NAME}", "return NULL;");
$self->pidl("return py_$e->{NAME};");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static int py_$name\_set_$e->{NAME}(PyObject *py_obj, PyObject *value, void *closure)");
$self->pidl("{");
$self->indent;
$self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
my $mem_ctx = "pytalloc_get_mem_ctx(py_obj)";
my $l = $e->{LEVELS}[0];
my $nl = GetNextLevel($e, $l);
if ($l->{TYPE} eq "POINTER" and
not ($nl->{TYPE} eq "ARRAY" and ($nl->{IS_FIXED} or is_charset_array($e, $nl))) and
not ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE}))) {
$self->pidl("talloc_unlink($mem_ctx, discard_const($varname));");
}
$self->ConvertObjectFromPython($env, $mem_ctx, $e, "value", $varname, "return -1;");
$self->pidl("return 0;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub PythonStruct($$$$$$)
{
my ($self, $modulename, $prettyname, $name, $cname, $d) = @_;
my $env = GenerateStructEnv($d, "object");
$self->pidl("");
my $getsetters = "NULL";
if ($#{$d->{ELEMENTS}} > -1) {
foreach my $e (@{$d->{ELEMENTS}}) {
$self->PythonElementGetSet($name, $cname, $e->{NAME}, $e, $env);
}
$getsetters = "py_$name\_getsetters";
$self->pidl("static PyGetSetDef ".$getsetters."[] = {");
$self->indent;
foreach my $e (@{$d->{ELEMENTS}}) {
my $etype = "";
if (ref($e->{TYPE}) eq "HASH") {
$etype = $e->{TYPE}->{NAME};
} else {
$etype = $e->{TYPE};
}
$self->pidl("{");
$self->indent;
$self->pidl(".name = discard_const_p(char, \"$e->{NAME}\"),");
$self->pidl(".get = py_$name\_get_$e->{NAME},");
$self->pidl(".set = py_$name\_set_$e->{NAME},");
$self->pidl(".doc = discard_const_p(char, \"PIDL-generated element of base type $etype\")");
$self->deindent;
$self->pidl("},");
}
$self->pidl("{ .name = NULL }");
$self->deindent;
$self->pidl("};");
$self->pidl("");
}
$self->pidl("static PyObject *py_$name\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("return pytalloc_new($cname, type);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
my $py_methods = "NULL";
# If the struct is not public there ndr_pull/ndr_push functions will
# be static so not callable from here
if (has_property($d, "public")) {
$self->pidl("static PyObject *py_$name\_ndr_pack(PyObject *py_obj)");
$self->pidl("{");
$self->indent;
$self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
$self->pidl("PyObject *ret = NULL;");
$self->pidl("DATA_BLOB blob;");
$self->pidl("enum ndr_err_code err;");
$self->pidl("TALLOC_CTX *tmp_ctx = talloc_new(pytalloc_get_mem_ctx(py_obj));");
$self->pidl("if (tmp_ctx == NULL) {");
$self->indent;
$self->pidl("PyErr_SetNdrError(NDR_ERR_ALLOC);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("err = ndr_push_struct_blob(&blob, tmp_ctx, object, (ndr_push_flags_fn_t)ndr_push_$name);");
$self->pidl("if (!NDR_ERR_CODE_IS_SUCCESS(err)) {");
$self->indent;
$self->pidl("TALLOC_FREE(tmp_ctx);");
$self->pidl("PyErr_SetNdrError(err);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("ret = PyBytes_FromStringAndSize((char *)blob.data, blob.length);");
$self->pidl("TALLOC_FREE(tmp_ctx);");
$self->pidl("return ret;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_unpack(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
$self->pidl("DATA_BLOB blob;");
$self->pidl("Py_ssize_t blob_length = 0;");
$self->pidl("enum ndr_err_code err;");
$self->pidl("const char * const kwnames[] = { \"data_blob\", \"allow_remaining\", NULL };");
$self->pidl("PyObject *allow_remaining_obj = NULL;");
$self->pidl("bool allow_remaining = false;");
$self->pidl("");
$self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, PYARG_BYTES_LEN \"|O:__ndr_unpack__\",");
$self->indent;
$self->pidl("discard_const_p(char *, kwnames),");
$self->pidl("&blob.data, &blob_length,");
$self->pidl("&allow_remaining_obj)) {");
$self->deindent;
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("blob.length = blob_length;");
$self->pidl("");
$self->pidl("if (allow_remaining_obj && PyObject_IsTrue(allow_remaining_obj)) {");
$self->indent;
$self->pidl("allow_remaining = true;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("if (allow_remaining) {");
$self->indent;
$self->pidl("err = ndr_pull_struct_blob(&blob, pytalloc_get_mem_ctx(py_obj), object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
$self->deindent;
$self->pidl("} else {");
$self->indent;
$self->pidl("err = ndr_pull_struct_blob_all(&blob, pytalloc_get_mem_ctx(py_obj), object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
$self->deindent;
$self->pidl("}");
$self->pidl("if (!NDR_ERR_CODE_IS_SUCCESS(err)) {");
$self->indent;
$self->pidl("PyErr_SetNdrError(err);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("Py_RETURN_NONE;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_print(PyObject *py_obj)");
$self->pidl("{");
$self->indent;
$self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
$self->pidl("PyObject *ret;");
$self->pidl("char *retstr;");
$self->pidl("");
$self->pidl("retstr = ndr_print_struct_string(pytalloc_get_mem_ctx(py_obj), (ndr_print_fn_t)ndr_print_$name, \"$name\", object);");
$self->pidl("ret = PyStr_FromString(retstr);");
$self->pidl("talloc_free(retstr);");
$self->pidl("");
$self->pidl("return ret;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$py_methods = "py_$name\_methods";
$self->pidl("static PyMethodDef $py_methods\[] = {");
$self->indent;
$self->pidl("{ \"__ndr_pack__\", (PyCFunction)py_$name\_ndr_pack, METH_NOARGS, \"S.ndr_pack(object) -> blob\\nNDR pack\" },");
$self->pidl("{ \"__ndr_unpack__\", (PyCFunction)py_$name\_ndr_unpack, METH_VARARGS|METH_KEYWORDS, \"S.ndr_unpack(class, blob, allow_remaining=False) -> None\\nNDR unpack\" },");
$self->pidl("{ \"__ndr_print__\", (PyCFunction)py_$name\_ndr_print, METH_NOARGS, \"S.ndr_print(object) -> None\\nNDR print\" },");
$self->pidl("{ NULL, NULL, 0, NULL }");
$self->deindent;
$self->pidl("};");
$self->pidl("");
}
$self->pidl_hdr("static PyTypeObject $name\_Type;\n");
$self->pidl("");
my $docstring = $self->DocString($d, $name);
my $typeobject = "$name\_Type";
$self->pidl("static PyTypeObject $typeobject = {");
$self->indent;
$self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
$self->pidl(".tp_name = \"$modulename.$prettyname\",");
$self->pidl(".tp_getset = $getsetters,");
if ($docstring) {
$self->pidl(".tp_doc = $docstring,");
}
$self->pidl(".tp_methods = $py_methods,");
$self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
$self->pidl(".tp_new = py_$name\_new,");
$self->deindent;
$self->pidl("};");
$self->pidl("");
my $talloc_typename = $self->import_type_variable("talloc", "BaseObject");
$self->register_module_prereadycode(["$name\_Type.tp_base = $talloc_typename;",
"$name\_Type.tp_basicsize = pytalloc_BaseObject_size();",
""]);
return "&$typeobject";
}
sub PythonFunctionStruct($$$$)
{
my ($self, $modulename, $fn, $iface, $prettyname) = @_;
my $inenv = GenerateFunctionInEnv($fn, "object->");
my $outenv = GenerateFunctionOutEnv($fn, "object->");
my $name = "$fn->{NAME}";
my $cname = "struct $name";
$self->pidl("");
my $getsetters = "NULL";
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep(/in/,@{$e->{DIRECTION}})) {
my $inname = "$name\_in";
my $ename = "in.$e->{NAME}";
$self->PythonElementGetSet($inname, $cname, $ename, $e, $inenv);
}
if (grep(/out/,@{$e->{DIRECTION}})) {
my $outname = "$name\_out";
my $ename = "out.$e->{NAME}";
$self->PythonElementGetSet($outname, $cname, $ename, $e, $outenv);
}
}
if (defined($fn->{RETURN_TYPE})) {
my $e = ReturnTypeElement($fn);
my $ename = "out.result";
$self->PythonElementGetSet($name, $cname, $ename, $e, $outenv);
}
$getsetters = "py_$name\_getsetters";
$self->pidl("static PyGetSetDef ".$getsetters."[] = {");
$self->indent;
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep(/in/,@{$e->{DIRECTION}})) {
$self->pidl("{");
$self->indent;
$self->pidl(".name = discard_const_p(char, \"in_$e->{NAME}\"),");
$self->pidl(".get = py_$name\_in_get_$e->{NAME},");
$self->pidl(".set = py_$name\_in_set_$e->{NAME},");
$self->pidl(".doc = discard_const_p(char, \"PIDL-generated element of base type $e->{TYPE}\")");
$self->deindent;
$self->pidl("},");
}
if (grep(/out/,@{$e->{DIRECTION}})) {
$self->pidl("{");
$self->indent;
$self->pidl(".name = discard_const_p(char, \"out_$e->{NAME}\"),");
$self->pidl(".get = py_$name\_out_get_$e->{NAME},");
$self->pidl(".set = py_$name\_out_set_$e->{NAME},");
$self->pidl(".doc = discard_const_p(char, \"PIDL-generated element of base type $e->{TYPE}\")");
$self->deindent;
$self->pidl("},");
}
}
if (defined($fn->{RETURN_TYPE})) {
$self->pidl("{");
$self->indent;
$self->pidl(".name = discard_const_p(char, \"result\"),");
$self->pidl(".get = py_$name\_get_result,");
$self->pidl(".set = py_$name\_set_result,");
$self->pidl(".doc = discard_const_p(char, \"PIDL-generated element of type $fn->{RETURN_TYPE}\")");
$self->deindent;
$self->pidl("},");
}
$self->pidl("{ .name = NULL }");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("return pytalloc_new($cname, type);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
my $py_methods = "NULL";
my $ndr_call = "const struct ndr_interface_call *call = NULL;";
my $object_ptr = "$cname *object = ($cname *)pytalloc_get_ptr(py_obj);";
$self->pidl("static PyObject *py_$name\_ndr_opnum(PyTypeObject *type)");
$self->pidl("{");
$self->indent;
$self->pidl("");
$self->pidl("");
$self->pidl("return PyInt_FromLong($fn->{OPNUM});");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_pack(PyObject *py_obj, int ndr_inout_flags, uint32_t ndr_push_flags)");
$self->pidl("{");
$self->indent;
$self->pidl("$ndr_call");
$self->pidl("$object_ptr");
$self->pidl("PyObject *ret = NULL;");
$self->pidl("struct ndr_push *push = NULL;");
$self->pidl("DATA_BLOB blob;");
$self->pidl("enum ndr_err_code err;");
$self->pidl("");
$self->pidl("if (ndr_table_$iface\.num_calls < " . ($fn->{OPNUM}+1) .
") {");
$self->indent;
$self->pidl("PyErr_SetString(PyExc_TypeError, \"Internal Error, ndr_interface_call missing for py_$name\_ndr_pack\");");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("call = &ndr_table_$iface\.calls[$fn->{OPNUM}];");
$self->pidl("");
$self->pidl("push = ndr_push_init_ctx(pytalloc_get_mem_ctx(py_obj));");
$self->pidl("if (push == NULL) {");
$self->indent;
$self->pidl("PyErr_SetNdrError(NDR_ERR_ALLOC);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("push->flags |= ndr_push_flags;");
$self->pidl("");
$self->pidl("err = call->ndr_push(push, ndr_inout_flags, object);");
$self->pidl("if (!NDR_ERR_CODE_IS_SUCCESS(err)) {");
$self->indent;
$self->pidl("TALLOC_FREE(push);");
$self->pidl("PyErr_SetNdrError(err);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("blob = ndr_push_blob(push);");
$self->pidl("ret = PyBytes_FromStringAndSize((char *)blob.data, blob.length);");
$self->pidl("TALLOC_FREE(push);");
$self->pidl("return ret;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_pack_in(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("const char * const kwnames[] = { \"bigendian\", \"ndr64\", NULL };");
$self->pidl("PyObject *bigendian_obj = NULL;");
$self->pidl("PyObject *ndr64_obj = NULL;");
$self->pidl("uint32_t ndr_push_flags = 0;");
$self->pidl("");
$self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"|OO:__ndr_pack_in__\",");
$self->indent;
$self->pidl("discard_const_p(char *, kwnames),");
$self->pidl("&bigendian_obj,");
$self->pidl("&ndr64_obj)) {");
$self->deindent;
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("if (bigendian_obj && PyObject_IsTrue(bigendian_obj)) {");
$self->indent;
$self->pidl("ndr_push_flags |= LIBNDR_FLAG_BIGENDIAN;");
$self->deindent;
$self->pidl("}");
$self->pidl("if (ndr64_obj && PyObject_IsTrue(ndr64_obj)) {");
$self->indent;
$self->pidl("ndr_push_flags |= LIBNDR_FLAG_NDR64;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("return py_$name\_ndr_pack(py_obj, NDR_IN, ndr_push_flags);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_pack_out(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("const char * const kwnames[] = { \"bigendian\", \"ndr64\", NULL };");
$self->pidl("PyObject *bigendian_obj = NULL;");
$self->pidl("PyObject *ndr64_obj = NULL;");
$self->pidl("uint32_t ndr_push_flags = 0;");
$self->pidl("");
$self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"|OO:__ndr_pack_out__\",");
$self->indent;
$self->pidl("discard_const_p(char *, kwnames),");
$self->pidl("&bigendian_obj,");
$self->pidl("&ndr64_obj)) {");
$self->deindent;
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("if (bigendian_obj && PyObject_IsTrue(bigendian_obj)) {");
$self->indent;
$self->pidl("ndr_push_flags |= LIBNDR_FLAG_BIGENDIAN;");
$self->deindent;
$self->pidl("}");
$self->pidl("if (ndr64_obj && PyObject_IsTrue(ndr64_obj)) {");
$self->indent;
$self->pidl("ndr_push_flags |= LIBNDR_FLAG_NDR64;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("return py_$name\_ndr_pack(py_obj, NDR_OUT, ndr_push_flags);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_unpack(PyObject *py_obj, const DATA_BLOB *blob, int ndr_inout_flags, uint32_t ndr_pull_flags, bool allow_remaining)");
$self->pidl("{");
$self->indent;
$self->pidl("$ndr_call");
$self->pidl("$object_ptr");
$self->pidl("struct ndr_pull *pull = NULL;");
$self->pidl("enum ndr_err_code err;");
$self->pidl("");
$self->pidl("if (ndr_table_$iface\.num_calls < " . ($fn->{OPNUM}+1) .
") {");
$self->indent;
$self->pidl("PyErr_SetString(PyExc_TypeError, \"Internal Error, ndr_interface_call missing for py_$name\_ndr_unpack\");");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("call = &ndr_table_$iface\.calls[$fn->{OPNUM}];");
$self->pidl("");
$self->pidl("pull = ndr_pull_init_blob(blob, object);");
$self->pidl("if (pull == NULL) {");
$self->indent;
$self->pidl("PyErr_SetNdrError(NDR_ERR_ALLOC);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("pull->flags |= ndr_pull_flags;");
$self->pidl("");
$self->pidl("err = call->ndr_pull(pull, ndr_inout_flags, object);");
$self->pidl("if (!NDR_ERR_CODE_IS_SUCCESS(err)) {");
$self->indent;
$self->pidl("TALLOC_FREE(pull);");
$self->pidl("PyErr_SetNdrError(err);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("if (!allow_remaining) {");
$self->indent;
$self->pidl("uint32_t highest_ofs;");
$self->pidl("");
$self->pidl("if (pull->offset > pull->relative_highest_offset) {");
$self->indent;
$self->pidl("highest_ofs = pull->offset;");
$self->deindent;
$self->pidl("} else {");
$self->indent;
$self->pidl("highest_ofs = pull->relative_highest_offset;");
$self->deindent;
$self->pidl("}");
$self->pidl("if (highest_ofs < pull->data_size) {");
$self->indent;
$self->pidl("err = ndr_pull_error(pull, NDR_ERR_UNREAD_BYTES,");
$self->indent;
$self->pidl("\"not all bytes consumed ofs[%u] size[%u]\",");
$self->pidl("highest_ofs, pull->data_size);");
$self->deindent;
$self->pidl("TALLOC_FREE(pull);");
$self->pidl("PyErr_SetNdrError(err);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("TALLOC_FREE(pull);");
$self->pidl("Py_RETURN_NONE;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_unpack_in(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("DATA_BLOB blob;");
$self->pidl("Py_ssize_t blob_length = 0;");
$self->pidl("const char * const kwnames[] = { \"data_blob\", \"bigendian\", \"ndr64\", \"allow_remaining\", NULL };");
$self->pidl("PyObject *bigendian_obj = NULL;");
$self->pidl("PyObject *ndr64_obj = NULL;");
$self->pidl("uint32_t ndr_pull_flags = LIBNDR_FLAG_REF_ALLOC;");
$self->pidl("PyObject *allow_remaining_obj = NULL;");
$self->pidl("bool allow_remaining = false;");
$self->pidl("");
$self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, PYARG_BYTES_LEN \"|OOO:__ndr_unpack_in__\",");
$self->indent;
$self->pidl("discard_const_p(char *, kwnames),");
$self->pidl("&blob.data, &blob_length,");
$self->pidl("&bigendian_obj,");
$self->pidl("&ndr64_obj,");
$self->pidl("&allow_remaining_obj)) {");
$self->deindent;
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("blob.length = blob_length;");
$self->pidl("");
$self->pidl("if (bigendian_obj && PyObject_IsTrue(bigendian_obj)) {");
$self->indent;
$self->pidl("ndr_pull_flags |= LIBNDR_FLAG_BIGENDIAN;");
$self->deindent;
$self->pidl("}");
$self->pidl("if (ndr64_obj && PyObject_IsTrue(ndr64_obj)) {");
$self->indent;
$self->pidl("ndr_pull_flags |= LIBNDR_FLAG_NDR64;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("if (allow_remaining_obj && PyObject_IsTrue(allow_remaining_obj)) {");
$self->indent;
$self->pidl("allow_remaining = true;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("return py_$name\_ndr_unpack(py_obj, &blob, NDR_IN, ndr_pull_flags, allow_remaining);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_unpack_out(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("DATA_BLOB blob;");
$self->pidl("Py_ssize_t blob_length = 0;");
$self->pidl("const char * const kwnames[] = { \"data_blob\", \"bigendian\", \"ndr64\", \"allow_remaining\", NULL };");
$self->pidl("PyObject *bigendian_obj = NULL;");
$self->pidl("PyObject *ndr64_obj = NULL;");
$self->pidl("uint32_t ndr_pull_flags = LIBNDR_FLAG_REF_ALLOC;");
$self->pidl("PyObject *allow_remaining_obj = NULL;");
$self->pidl("bool allow_remaining = false;");
$self->pidl("");
$self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, PYARG_BYTES_LEN \"|OOO:__ndr_unpack_out__\",");
$self->indent;
$self->pidl("discard_const_p(char *, kwnames),");
$self->pidl("&blob.data, &blob_length,");
$self->pidl("&bigendian_obj,");
$self->pidl("&ndr64_obj,");
$self->pidl("&allow_remaining_obj)) {");
$self->deindent;
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("blob.length = blob_length;");
$self->pidl("");
$self->pidl("if (bigendian_obj && PyObject_IsTrue(bigendian_obj)) {");
$self->indent;
$self->pidl("ndr_pull_flags |= LIBNDR_FLAG_BIGENDIAN;");
$self->deindent;
$self->pidl("}");
$self->pidl("if (ndr64_obj && PyObject_IsTrue(ndr64_obj)) {");
$self->indent;
$self->pidl("ndr_pull_flags |= LIBNDR_FLAG_NDR64;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("if (allow_remaining_obj && PyObject_IsTrue(allow_remaining_obj)) {");
$self->indent;
$self->pidl("allow_remaining = true;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("return py_$name\_ndr_unpack(py_obj, &blob, NDR_OUT, ndr_pull_flags, allow_remaining);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_print(PyObject *py_obj, const char *name, int ndr_inout_flags)");
$self->pidl("{");
$self->indent;
$self->pidl("$ndr_call");
$self->pidl("$object_ptr");
$self->pidl("PyObject *ret;");
$self->pidl("char *retstr;");
$self->pidl("");
$self->pidl("if (ndr_table_$iface\.num_calls < " . ($fn->{OPNUM}+1) .
") {");
$self->indent;
$self->pidl("PyErr_SetString(PyExc_TypeError, \"Internal Error, ndr_interface_call missing for py_$name\_ndr_print\");");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("call = &ndr_table_$iface\.calls[$fn->{OPNUM}];");
$self->pidl("");
$self->pidl("retstr = ndr_print_function_string(pytalloc_get_mem_ctx(py_obj), call->ndr_print, name, ndr_inout_flags, object);");
$self->pidl("ret = PyStr_FromString(retstr);");
$self->pidl("TALLOC_FREE(retstr);");
$self->pidl("");
$self->pidl("return ret;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_print_in(PyObject *py_obj)");
$self->pidl("{");
$self->indent;
$self->pidl("return py_$name\_ndr_print(py_obj, \"$name\_in\", NDR_IN);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$name\_ndr_print_out(PyObject *py_obj)");
$self->pidl("{");
$self->indent;
$self->pidl("return py_$name\_ndr_print(py_obj, \"$name\_out\", NDR_OUT);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$py_methods = "py_$name\_methods";
$self->pidl("static PyMethodDef $py_methods\[] = {");
$self->indent;
$self->pidl("{ \"opnum\", (PyCFunction)py_$name\_ndr_opnum, METH_NOARGS|METH_CLASS,");
$self->indent;
$self->pidl("\"$modulename.$prettyname.opnum() -> ".sprintf("%d (0x%02x)", $fn->{OPNUM}, $fn->{OPNUM})." \" },");
$self->deindent;
$self->pidl("{ \"__ndr_pack_in__\", (PyCFunction)py_$name\_ndr_pack_in, METH_VARARGS|METH_KEYWORDS,");
$self->indent;
$self->pidl("\"S.ndr_pack_in(object, bigendian=False, ndr64=False) -> blob\\nNDR pack input\" },");
$self->deindent;
$self->pidl("{ \"__ndr_pack_out__\", (PyCFunction)py_$name\_ndr_pack_out, METH_VARARGS|METH_KEYWORDS,");
$self->indent;
$self->pidl("\"S.ndr_pack_out(object, bigendian=False, ndr64=False) -> blob\\nNDR pack output\" },");
$self->deindent;
$self->pidl("{ \"__ndr_unpack_in__\", (PyCFunction)py_$name\_ndr_unpack_in, METH_VARARGS|METH_KEYWORDS,");
$self->indent;
$self->pidl("\"S.ndr_unpack_in(class, blob, bigendian=False, ndr64=False, allow_remaining=False) -> None\\nNDR unpack input\" },");
$self->deindent;
$self->pidl("{ \"__ndr_unpack_out__\", (PyCFunction)py_$name\_ndr_unpack_out, METH_VARARGS|METH_KEYWORDS,");
$self->indent;
$self->pidl("\"S.ndr_unpack_out(class, blob, bigendian=False, ndr64=False, allow_remaining=False) -> None\\nNDR unpack output\" },");
$self->deindent;
$self->pidl("{ \"__ndr_print_in__\", (PyCFunction)py_$name\_ndr_print_in, METH_NOARGS, \"S.ndr_print_in(object) -> None\\nNDR print input\" },");
$self->pidl("{ \"__ndr_print_out__\", (PyCFunction)py_$name\_ndr_print_out, METH_NOARGS, \"S.ndr_print_out(object) -> None\\nNDR print output\" },");
$self->pidl("{ NULL, NULL, 0, NULL }");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl_hdr("static PyTypeObject $name\_Type;\n");
$self->pidl("");
my $docstring = $self->DocString($fn, $name);
my $typeobject = "$name\_Type";
$self->pidl("static PyTypeObject $typeobject = {");
$self->indent;
$self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
$self->pidl(".tp_name = \"$modulename.$prettyname\",");
$self->pidl(".tp_getset = $getsetters,");
if ($docstring) {
$self->pidl(".tp_doc = $docstring,");
}
$self->pidl(".tp_methods = $py_methods,");
$self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
$self->pidl(".tp_new = py_$name\_new,");
$self->deindent;
$self->pidl("};");
$self->pidl("");
my $talloc_typename = $self->import_type_variable("talloc", "BaseObject");
$self->register_module_prereadycode(["$name\_Type.tp_base = $talloc_typename;",
"$name\_Type.tp_basicsize = pytalloc_BaseObject_size();",
""]);
return "&$typeobject";
}
sub get_metadata_var($)
{
my ($e) = @_;
sub get_var($) { my $x = shift; $x =~ s/\*//g; return $x; }
if (has_property($e, "length_is")) {
return get_var($e->{PROPERTIES}->{length_is});
} elsif (has_property($e, "size_is")) {
return get_var($e->{PROPERTIES}->{size_is});
}
return undef;
}
sub find_metadata_args($)
{
my ($fn) = @_;
my $metadata_args = { in => {}, out => {} };
# Determine arguments that are metadata for other arguments (size_is/length_is)
foreach my $e (@{$fn->{ELEMENTS}}) {
foreach my $dir (@{$e->{DIRECTION}}) {
my $main = get_metadata_var($e);
if ($main) {
$metadata_args->{$dir}->{$main} = $e->{NAME};
}
}
}
return $metadata_args;
}
sub PythonFunctionUnpackOut($$$)
{
my ($self, $fn, $fnname) = @_;
my $outfnname = "unpack_$fnname\_args_out";
my $signature = "";
my $metadata_args = find_metadata_args($fn);
my $env = GenerateFunctionOutEnv($fn, "r->");
my $result_size = 0;
$self->pidl("static PyObject *$outfnname(struct $fn->{NAME} *r)");
$self->pidl("{");
$self->indent;
$self->pidl("PyObject *result;");
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless (grep(/out/,@{$e->{DIRECTION}}));
next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or
($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
$self->pidl("PyObject *py_$e->{NAME};");
$result_size++;
}
if ($fn->{RETURN_TYPE}) {
$result_size++ unless ($fn->{RETURN_TYPE} eq "WERROR" or $fn->{RETURN_TYPE} eq "NTSTATUS");
}
my $i = 0;
if ($result_size > 1) {
$self->pidl("result = PyTuple_New($result_size);");
$signature .= "(";
} elsif ($result_size == 0) {
$self->pidl("result = Py_None;");
$self->pidl("Py_INCREF(result);");
$signature .= "None";
}
foreach my $e (@{$fn->{ELEMENTS}}) {
next if ($metadata_args->{out}->{$e->{NAME}});
my $py_name = "py_$e->{NAME}";
if (grep(/out/,@{$e->{DIRECTION}})) {
$self->ConvertObjectToPython("r", $env, $e, "r->out.$e->{NAME}", $py_name, "return NULL;");
if ($result_size > 1) {
$self->pidl("PyTuple_SetItem(result, $i, $py_name);");
$i++;
$signature .= "$e->{NAME}, ";
} else {
$self->pidl("result = $py_name;");
$signature .= $e->{NAME};
}
}
}
if (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "NTSTATUS") {
$self->handle_ntstatus("r->out.result", "NULL", undef);
} elsif (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "WERROR") {
$self->handle_werror("r->out.result", "NULL", undef);
} elsif (defined($fn->{RETURN_TYPE})) {
my $conv = $self->ConvertObjectToPythonData("r", $fn->{RETURN_TYPE}, "r->out.result", $fn);
if ($result_size > 1) {
$self->pidl("PyTuple_SetItem(result, $i, $conv);");
} else {
$self->pidl("result = $conv;");
}
$signature .= "result";
}
if (substr($signature, -2) eq ", ") {
$signature = substr($signature, 0, -2);
}
if ($result_size > 1) {
$signature .= ")";
}
$self->pidl("return result;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
return ($outfnname, $signature);
}
sub PythonFunctionPackIn($$$)
{
my ($self, $fn, $fnname) = @_;
my $metadata_args = find_metadata_args($fn);
my $infnname = "pack_$fnname\_args_in";
$self->pidl("static bool $infnname(PyObject *args, PyObject *kwargs, struct $fn->{NAME} *r)");
$self->pidl("{");
$self->indent;
my $args_format = "";
my $args_string = "";
my $args_names = "";
my $signature = "";
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless (grep(/in/,@{$e->{DIRECTION}}));
next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or
($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
$self->pidl("PyObject *py_$e->{NAME};");
$args_format .= "O";
$args_string .= ", &py_$e->{NAME}";
$args_names .= "\"$e->{NAME}\", ";
$signature .= "$e->{NAME}, ";
}
if (substr($signature, -2) eq ", ") {
$signature = substr($signature, 0, -2);
}
$self->pidl("const char *kwnames[] = {");
$self->indent;
$self->pidl($args_names . "NULL");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"$args_format:$fn->{NAME}\", discard_const_p(char *, kwnames)$args_string)) {");
$self->indent;
$self->pidl("return false;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
my $env = GenerateFunctionInEnv($fn, "r->");
my $fail = "return false;";
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless (grep(/in/,@{$e->{DIRECTION}}));
if ($metadata_args->{in}->{$e->{NAME}}) {
my $py_var = "py_".$metadata_args->{in}->{$e->{NAME}};
$self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
my $val = "PyList_GET_SIZE($py_var)";
if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
$self->pidl("r->in.$e->{NAME} = talloc_ptrtype(r, r->in.$e->{NAME});");
$self->pidl("if (r->in.$e->{NAME} == NULL) {");
$self->indent;
$self->pidl("PyErr_NoMemory();");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->pidl("*r->in.$e->{NAME} = $val;");
} else {
$self->pidl("r->in.$e->{NAME} = $val;");
}
} else {
$self->ConvertObjectFromPython($env, "r", $e, "py_$e->{NAME}", "r->in.$e->{NAME}", $fail);
}
}
$self->pidl("return true;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
return ($infnname, $signature);
}
sub PythonFunction($$$)
{
my ($self, $fn, $iface, $prettyname) = @_;
my $fnname = "py_$fn->{NAME}";
my $docstring = $self->DocString($fn, $fn->{NAME});
my ($infn, $insignature) = $self->PythonFunctionPackIn($fn, $fnname);
my ($outfn, $outsignature) = $self->PythonFunctionUnpackOut($fn, $fnname);
my $signature = "S.$prettyname($insignature) -> $outsignature";
if ($docstring) {
$docstring = "\"$signature\\n\\n\"$docstring";
} else {
$docstring = "\"$signature\"";
}
return ($infn, $outfn, $docstring);
}
sub handle_werror($$$$)
{
my ($self, $var, $retval, $mem_ctx) = @_;
$self->pidl("if (!W_ERROR_IS_OK($var)) {");
$self->indent;
$self->pidl("PyErr_SetWERROR($var);");
$self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
$self->pidl("return $retval;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub handle_ntstatus($$$$)
{
my ($self, $var, $retval, $mem_ctx) = @_;
$self->pidl("if (NT_STATUS_IS_ERR($var)) {");
$self->indent;
$self->pidl("PyErr_SetNTSTATUS($var);");
$self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
$self->pidl("return $retval;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub PythonType($$$$)
{
my ($self, $modulename, $d, $interface, $basename) = @_;
my $actual_ctype = $d;
if ($actual_ctype->{TYPE} eq "TYPEDEF") {
$actual_ctype = $actual_ctype->{DATA};
}
if ($actual_ctype->{TYPE} eq "STRUCT") {
my $typeobject;
my $fn_name = PrettifyTypeName($d->{NAME}, $basename);
if ($d->{TYPE} eq "STRUCT") {
$typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d);
} else {
$typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d->{DATA});
}
$self->register_module_typeobject($fn_name, $typeobject, $d->{ORIGINAL});
}
if ($d->{TYPE} eq "ENUM" or $d->{TYPE} eq "BITMAP") {
$self->EnumAndBitmapConsts($d->{NAME}, $d);
}
if ($d->{TYPE} eq "TYPEDEF" and ($d->{DATA}->{TYPE} eq "ENUM" or $d->{DATA}->{TYPE} eq "BITMAP")) {
$self->EnumAndBitmapConsts($d->{NAME}, $d->{DATA});
}
if ($actual_ctype->{TYPE} eq "UNION" and defined($actual_ctype->{ELEMENTS})) {
my $prettyname = PrettifyTypeName($d->{NAME}, $basename);
my $typeobject = "$d->{NAME}\_Type";
my $docstring = $self->DocString($d, $d->{NAME});
my $cname = "union $d->{NAME}";
$self->pidl("static PyObject *py_import_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, " .mapTypeName($d) . " *in)");
$self->pidl("{");
$self->indent;
$self->FromUnionToPythonFunction("mem_ctx", $actual_ctype, "level", "in") if ($actual_ctype->{TYPE} eq "UNION");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static ".mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in)");
$self->pidl("{");
$self->indent;
$self->FromPythonToUnionFunction($actual_ctype, mapTypeName($d), "level", "mem_ctx", "in") if ($actual_ctype->{TYPE} eq "UNION");
$self->deindent;
$self->pidl("}");
$self->pidl("");
my $getsetters = "NULL";
my $py_methods = "NULL";
my $typename = mapTypeName($d);
$self->pidl("static PyObject *py_$d->{NAME}\_import(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("const char * const kwnames[] = { \"mem_ctx\", \"level\", \"in\", NULL };");
$self->pidl("PyObject *mem_ctx_obj = NULL;");
$self->pidl("TALLOC_CTX *mem_ctx = NULL;");
$self->pidl("int level = 0;");
$self->pidl("PyObject *in_obj = NULL;");
$self->pidl("$typename *in = NULL;");
$self->pidl("");
$self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"OiO:import\",");
$self->indent;
$self->pidl("discard_const_p(char *, kwnames),");
$self->pidl("&mem_ctx_obj,");
$self->pidl("&level,");
$self->pidl("&in_obj)) {");
$self->deindent;
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("mem_ctx = pytalloc_get_ptr(mem_ctx_obj);");
$self->pidl("if (mem_ctx == NULL) {");
$self->indent;
$self->pidl("PyErr_SetString(PyExc_TypeError, \"mem_ctx is NULL)!\");");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("in = ($typename *)pytalloc_get_ptr(in_obj);");
$self->pidl("if (in == NULL) {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_TypeError, \"in needs to be a pointer to $typename!\");");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("return py_import_$d->{NAME}(mem_ctx, level, in);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("static PyObject *py_$d->{NAME}\_export(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("const char * const kwnames[] = { \"mem_ctx\", \"level\", \"in\", NULL };");
$self->pidl("PyObject *mem_ctx_obj = NULL;");
$self->pidl("TALLOC_CTX *mem_ctx = NULL;");
$self->pidl("int level = 0;");
$self->pidl("PyObject *in = NULL;");
$self->pidl("$typename *out = NULL;");
$self->pidl("");
$self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"OiO:import\",");
$self->indent;
$self->pidl("discard_const_p(char *, kwnames),");
$self->pidl("&mem_ctx_obj,");
$self->pidl("&level,");
$self->pidl("&in)) {");
$self->deindent;
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("mem_ctx = pytalloc_get_ptr(mem_ctx_obj);");
$self->pidl("if (mem_ctx == NULL) {");
$self->indent;
$self->pidl("PyErr_SetString(PyExc_TypeError, \"mem_ctx is NULL)!\");");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("out = py_export_$d->{NAME}(mem_ctx, level, in);");
$self->pidl("if (out == NULL) {");
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("return pytalloc_GenericObject_reference(out);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$py_methods = "py_$d->{NAME}_methods";
$self->pidl("static PyMethodDef $py_methods\[] = {");
$self->indent;
$self->pidl("{ \"__import__\", (PyCFunction)py_$d->{NAME}\_import,");
$self->indent;
$self->pidl("METH_VARARGS|METH_KEYWORDS|METH_CLASS,");
$self->pidl("\"T.__import__(mem_ctx, level, in) => ret.\" },");
$self->deindent;
$self->pidl("{ \"__export__\", (PyCFunction)py_$d->{NAME}\_export,");
$self->indent;
$self->pidl("METH_VARARGS|METH_KEYWORDS|METH_CLASS,");
$self->pidl("\"T.__export__(mem_ctx, level, in) => ret.\" },");
$self->deindent;
$self->pidl("{ NULL, NULL, 0, NULL }");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl("static PyObject *py_$d->{NAME}\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("PyErr_Format(PyExc_TypeError, \"New %s Objects are not supported\", type->tp_name);");
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("");
$self->pidl_hdr("static PyTypeObject $typeobject;\n");
$self->pidl("static PyTypeObject $typeobject = {");
$self->indent;
$self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
$self->pidl(".tp_name = \"$modulename.$prettyname\",");
$self->pidl(".tp_getset = $getsetters,");
if ($docstring) {
$self->pidl(".tp_doc = $docstring,");
}
$self->pidl(".tp_methods = $py_methods,");
$self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
$self->pidl(".tp_new = py_$d->{NAME}\_new,");
$self->deindent;
$self->pidl("};");
$self->pidl("");
my $talloc_typename = $self->import_type_variable("talloc", "BaseObject");
$self->register_module_prereadycode(["$typeobject.tp_base = $talloc_typename;",
"$typeobject.tp_basicsize = pytalloc_BaseObject_size();",
""]);
$self->register_module_typeobject($prettyname, "&$typeobject", $d->{ORIGINAL});
}
}
sub DocString($$$)
{
my ($self, $d, $name) = @_;
if (has_property($d, "helpstring")) {
my $docstring = uc("py_doc_$name");
$self->pidl("#define $docstring ".has_property($d, "helpstring"));
return $docstring;
}
return undef;
}
sub Interface($$$)
{
my($self,$interface,$basename) = @_;
if (has_property($interface, "pyhelper")) {
$self->pidl("#include \"".unmake_str($interface->{PROPERTIES}->{pyhelper})."\"\n");
}
$self->Const($_) foreach (@{$interface->{CONSTS}});
foreach my $d (@{$interface->{TYPES}}) {
next if has_property($d, "nopython");
$self->PythonType($basename, $d, $interface, $basename);
}
if (defined $interface->{PROPERTIES}->{uuid}) {
$self->pidl_hdr("static PyTypeObject $interface->{NAME}_InterfaceType;\n");
$self->pidl("");
my @fns = ();
foreach my $d (@{$interface->{FUNCTIONS}}) {
next if has_property($d, "noopnum");
next if has_property($d, "nopython");
next if has_property($d, "todo");
my $skip = 0;
foreach my $e (@{$d->{ELEMENTS}}) {
if (ContainsPipe($e, $e->{LEVELS}[0])) {
$skip = 1;
last;
}
}
next if $skip;
my $prettyname = $d->{NAME};
$prettyname =~ s/^$interface->{NAME}_//;
$prettyname =~ s/^$basename\_//;
my $typeobject = $self->PythonFunctionStruct($basename, $d, $interface->{NAME}, $prettyname);
$self->register_module_typeobject($prettyname, $typeobject, $d->{ORIGINAL});
my ($infn, $outfn, $fndocstring) = $self->PythonFunction($d, $interface->{NAME}, $prettyname);
push (@fns, [$infn, $outfn, "dcerpc_$d->{NAME}_r", $prettyname, $fndocstring, $d->{OPNUM}]);
}
$self->pidl("const struct PyNdrRpcMethodDef py_ndr_$interface->{NAME}\_methods[] = {");
$self->indent;
foreach my $d (@fns) {
my ($infn, $outfn, $callfn, $prettyname, $docstring, $opnum) = @$d;
$self->pidl("{ \"$prettyname\", $docstring, (py_dcerpc_call_fn)$callfn, (py_data_pack_fn)$infn, (py_data_unpack_fn)$outfn, $opnum, &ndr_table_$interface->{NAME} },");
}
$self->pidl("{ NULL }");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl("static PyObject *interface_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("return py_dcerpc_interface_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME});");
$self->deindent;
$self->pidl("}");
$self->pidl("");
my $signature =
"\"$interface->{NAME}(binding, lp_ctx=None, credentials=None) -> connection\\n\"
\"\\n\"
\"binding should be a DCE/RPC binding string (for example: ncacn_ip_tcp:127.0.0.1)\\n\"
\"lp_ctx should be a path to a smb.conf file or a param.LoadParm object\\n\"
\"credentials should be a credentials.Credentials object.\\n\\n\"";
my $docstring = $self->DocString($interface, $interface->{NAME});
if ($docstring) {
$docstring = "$signature$docstring";
} else {
$docstring = $signature;
}
my $if_typename = "$interface->{NAME}_InterfaceType";
$self->pidl("static PyTypeObject $if_typename = {");
$self->indent;
$self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
$self->pidl(".tp_name = \"$basename.$interface->{NAME}\",");
$self->pidl(".tp_basicsize = sizeof(dcerpc_InterfaceObject),");
$self->pidl(".tp_doc = $docstring,");
$self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
$self->pidl(".tp_new = interface_$interface->{NAME}_new,");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->register_module_typeobject($interface->{NAME}, "&$if_typename", $interface->{ORIGINAL});
my $dcerpc_typename = $self->import_type_variable("samba.dcerpc.base", "ClientConnection");
$self->register_module_prereadycode(["$if_typename.tp_base = $dcerpc_typename;", ""]);
$self->register_module_postreadycode(["if (!PyInterface_AddNdrRpcMethods(&$if_typename, py_ndr_$interface->{NAME}\_methods))", "\treturn NULL;", ""]);
$self->pidl("static PyObject *syntax_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
$self->pidl("{");
$self->indent;
$self->pidl("return py_dcerpc_syntax_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME}.syntax_id);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
my $signature = "\"$interface->{NAME}_abstract_syntax()\\n\"";
my $docstring = $self->DocString($interface, $interface->{NAME}."_syntax");
if ($docstring) {
$docstring = "$signature$docstring";
} else {
$docstring = $signature;
}
my $syntax_typename = "$interface->{NAME}_SyntaxType";
$self->pidl("static PyTypeObject $syntax_typename = {");
$self->indent;
$self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
$self->pidl(".tp_name = \"$basename.$interface->{NAME}_abstract_syntax\",");
$self->pidl(".tp_doc = $docstring,");
$self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
$self->pidl(".tp_new = syntax_$interface->{NAME}_new,");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->register_module_typeobject("$interface->{NAME}_abstract_syntax", "&$syntax_typename", $interface->{ORIGINAL});
if (not defined($self->existing_module_object("abstract_syntax"))) {
# Only the first syntax gets registered with the legacy
# "abstract_syntax" name
$self->register_module_typeobject("abstract_syntax", "&$syntax_typename", $interface->{ORIGINAL});
}
my $ndr_typename = $self->import_type_variable("samba.dcerpc.misc", "ndr_syntax_id");
$self->register_module_prereadycode(["$syntax_typename.tp_base = $ndr_typename;",
"$syntax_typename.tp_basicsize = pytalloc_BaseObject_size();",
""]);
}
$self->pidl_hdr("\n");
}
sub register_module_method($$$$$)
{
my ($self, $fn_name, $pyfn_name, $flags, $doc) = @_;
push (@{$self->{module_methods}}, [$fn_name, $pyfn_name, $flags, $doc])
}
sub register_module_typeobject($$$$)
{
my ($self, $name, $py_name, $location) = @_;
$self->register_module_object($name, "(PyObject *)(void *)$py_name", $location);
$self->check_ready_type($py_name);
$self->register_patch_type_call($name, $py_name);
}
sub check_ready_type($$)
{
my ($self, $py_name) = @_;
push (@{$self->{ready_types}}, $py_name) unless (grep(/^$py_name$/,@{$self->{ready_types}}));
}
sub register_module_import($$)
{
my ($self, $module_path) = @_;
my $var_name = $module_path;
$var_name =~ s/\./_/g;
$var_name = "dep_$var_name";
unless (defined $self->{module_imports_uniq}->{$var_name}) {
my $h = { "key" => $var_name, "val" => $module_path};
push @{$self->{module_imports}}, $h;
$self->{module_imports_uniq}->{$var_name} = $h;
}
return $var_name;
}
sub import_type_variable($$$)
{
my ($self, $module, $name) = @_;
$self->register_module_import($module);
unless (defined $self->{type_imports_uniq}->{$name}) {
my $h = { "key" => $name, "val" => $module};
push @{$self->{type_imports}}, $h;
$self->{type_imports_uniq}->{$name} = $h;
}
return "$name\_Type";
}
sub use_type_variable($$)
{
my ($self, $orig_ctype) = @_;
# FIXME: Have a global lookup table for types that look different on the
# wire than they are named in C?
if ($orig_ctype->{NAME} eq "dom_sid2" or
$orig_ctype->{NAME} eq "dom_sid28" or
$orig_ctype->{NAME} eq "dom_sid0") {
$orig_ctype->{NAME} = "dom_sid";
}
if ($orig_ctype->{NAME} eq "spoolss_security_descriptor") {
$orig_ctype->{NAME} = "security_descriptor";
}
my $ctype = resolveType($orig_ctype);
unless (defined($ctype->{BASEFILE})) {
return undef;
}
# If this is an external type, make sure we do the right imports.
if (($ctype->{BASEFILE} ne $self->{BASENAME})) {
return $self->import_type_variable("samba.dcerpc.$ctype->{BASEFILE}", $ctype->{NAME});
}
return "&$ctype->{NAME}_Type";
}
sub register_patch_type_call($$$)
{
my ($self, $typename, $cvar) = @_;
push(@{$self->{patch_type_calls}}, [$typename, $cvar]);
}
sub register_module_prereadycode($$)
{
my ($self, $code) = @_;
push (@{$self->{prereadycode}}, @$code);
}
sub register_module_postreadycode($$)
{
my ($self, $code) = @_;
push (@{$self->{postreadycode}}, @$code);
}
sub existing_module_object($$)
{
my ($self, $name) = @_;
if (defined($self->{module_object_uniq}->{$name})) {
return $self->{module_object_uniq}->{$name};
}
return undef;
}
sub register_module_object($$$$)
{
my ($self, $name, $py_name, $location) = @_;
my $existing = $self->existing_module_object($name);
fatal($location, "module_object($name, $py_name) registered twice! $existing.") if defined($existing);
push (@{$self->{module_objects}}, [$name, $py_name]);
$self->{module_object_uniq}->{$name} = $py_name;
}
sub assign($$$)
{
my ($self, $dest, $src) = @_;
if ($dest =~ /^\&/ and $src eq "NULL") {
$self->pidl("memset($dest, 0, sizeof(" . get_value_of($dest) . "));");
} elsif ($dest =~ /^\&/) {
my $destvar = get_value_of($dest);
$self->pidl("$destvar = *$src;");
} else {
$self->pidl("$dest = $src;");
}
}
sub ConvertStringFromPythonData($$$$$)
{
my ($self, $mem_ctx, $py_var, $target, $fail) = @_;
$self->pidl("{");
$self->indent;
$self->pidl("const char *test_str;");
$self->pidl("const char *talloc_str;");
$self->pidl("PyObject *unicode = NULL;");
$self->pidl("if (PyUnicode_Check($py_var)) {");
$self->indent;
# FIXME: Use Unix charset setting rather than utf-8
$self->pidl("unicode = PyUnicode_AsEncodedString($py_var, \"utf-8\", \"ignore\");");
$self->pidl("if (unicode == NULL) {");
$self->indent;
$self->pidl("PyErr_NoMemory();");
$self->pidl("$fail");
$self->deindent;
$self->pidl("}");
$self->pidl("test_str = PyBytes_AS_STRING(unicode);");
$self->deindent;
$self->pidl("} else if (PyBytes_Check($py_var)) {");
$self->indent;
$self->pidl("test_str = PyBytes_AS_STRING($py_var);");
$self->deindent;
$self->pidl("} else {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_TypeError, \"Expected string or unicode object, got %s\", Py_TYPE($py_var)->tp_name);");
$self->pidl("$fail");
$self->deindent;
$self->pidl("}");
$self->pidl("talloc_str = talloc_strdup($mem_ctx, test_str);");
$self->pidl("if (unicode != NULL) {");
$self->indent;
$self->pidl("Py_DECREF(unicode);");
$self->deindent;
$self->pidl("}");
$self->pidl("if (talloc_str == NULL) {");
$self->indent;
$self->pidl("PyErr_NoMemory();");
$self->pidl("$fail");
$self->deindent;
$self->pidl("}");
$self->pidl("$target = talloc_str;");
$self->deindent;
$self->pidl("}");
}
sub ConvertObjectFromPythonData($$$$$$;$$)
{
my ($self, $mem_ctx, $cvar, $ctype, $target, $fail, $location, $switch) = @_;
fatal($location, "undef type for $cvar") unless(defined($ctype));
$ctype = resolveType($ctype);
my $actual_ctype = $ctype;
if ($actual_ctype->{TYPE} eq "TYPEDEF") {
$actual_ctype = $actual_ctype->{DATA};
}
# We need to cover ENUMs, BITMAPS and SCALAR values here, as
# all could otherwise be assigned invalid integer values
my $ctype_alias = "";
my $uint_max = "";
if ($actual_ctype->{TYPE} eq "ENUM") {
# Importantly, ENUM values are unsigned in pidl, and
# typically map to uint32
$ctype_alias = enum_type_fn($actual_ctype);
} elsif ($actual_ctype->{TYPE} eq "BITMAP") {
$ctype_alias = bitmap_type_fn($actual_ctype);
} elsif ($actual_ctype->{TYPE} eq "SCALAR") {
$ctype_alias = expandAlias($actual_ctype->{NAME});
}
# This is the unsigned Python Integer -> C integer validation
# case. The signed case is below.
if ($ctype_alias =~ /^(uint[0-9]*|hyper|udlong|udlongr
|NTTIME_hyper|NTTIME|NTTIME_1sec
|uid_t|gid_t)$/x) {
$self->pidl("{");
$self->indent;
$self->pidl("const unsigned long long uint_max = ndr_sizeof2uintmax(sizeof($target));");
$self->pidl("if (PyLong_Check($cvar)) {");
$self->indent;
$self->pidl("unsigned long long test_var;");
$self->pidl("test_var = PyLong_AsUnsignedLongLong($cvar);");
$self->pidl("if (PyErr_Occurred() != NULL) {");
$self->indent;
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->pidl("if (test_var > uint_max) {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range 0 - %llu, got %llu\",\\");
$self->pidl(" PyInt_Type.tp_name, PyLong_Type.tp_name, uint_max, test_var);");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->pidl("$target = test_var;");
$self->deindent;
$self->pidl("} else if (PyInt_Check($cvar)) {");
$self->indent;
$self->pidl("long test_var;");
$self->pidl("test_var = PyInt_AsLong($cvar);");
$self->pidl("if (test_var < 0 || test_var > uint_max) {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range 0 - %llu, got %ld\",\\");
$self->pidl(" PyInt_Type.tp_name, PyLong_Type.tp_name, uint_max, test_var);");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->pidl("$target = test_var;");
$self->deindent;
$self->pidl("} else {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
$self->pidl(" PyInt_Type.tp_name, PyLong_Type.tp_name);");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->deindent;
$self->pidl("}");
return;
}
# Confirm the signed python integer fits in the C type
# correctly. It is subtly different from the unsigned case
# above, so while it looks like a duplicate, it is not
# actually a duplicate.
if ($ctype_alias =~ /^(dlong|char|int[0-9]*|time_t)$/x) {
$self->pidl("{");
$self->indent;
$self->pidl("const long long int_max = ndr_sizeof2intmax(sizeof($target));");
$self->pidl("const long long int_min = -int_max - 1;");
$self->pidl("if (PyLong_Check($cvar)) {");
$self->indent;
$self->pidl("long long test_var;");
$self->pidl("test_var = PyLong_AsLongLong($cvar);");
$self->pidl("if (PyErr_Occurred() != NULL) {");
$self->indent;
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->pidl("if (test_var < int_min || test_var > int_max) {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range %lld - %lld, got %lld\",\\");
$self->pidl(" PyInt_Type.tp_name, PyLong_Type.tp_name, int_min, int_max, test_var);");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->pidl("$target = test_var;");
$self->deindent;
$self->pidl("} else if (PyInt_Check($cvar)) {");
$self->indent;
$self->pidl("long test_var;");
$self->pidl("test_var = PyInt_AsLong($cvar);");
$self->pidl("if (test_var < int_min || test_var > int_max) {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range %lld - %lld, got %ld\",\\");
$self->pidl(" PyInt_Type.tp_name, PyLong_Type.tp_name, int_min, int_max, test_var);");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->pidl("$target = test_var;");
$self->deindent;
$self->pidl("} else {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
$self->pidl(" PyInt_Type.tp_name, PyLong_Type.tp_name);");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
$self->deindent;
$self->pidl("}");
return;
}
if ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
my $ctype_name = $self->use_type_variable($ctype);
unless (defined ($ctype_name)) {
error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
$self->pidl("PyErr_SetString(PyExc_TypeError, \"Can not convert C Type " . mapTypeName($ctype) . " from Python\");");
return;
}
$self->pidl("PY_CHECK_TYPE($ctype_name, $cvar, $fail);");
$self->pidl("if (talloc_reference($mem_ctx, pytalloc_get_mem_ctx($cvar)) == NULL) {");
$self->indent;
$self->pidl("PyErr_NoMemory();");
$self->pidl("$fail");
$self->deindent;
$self->pidl("}");
$self->assign($target, "(".mapTypeName($ctype)." *)pytalloc_get_ptr($cvar)");
return;
}
if ($actual_ctype->{TYPE} eq "UNION") {
my $ctype_name = $self->use_type_variable($ctype);
unless (defined ($ctype_name)) {
error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
$self->pidl("PyErr_SetString(PyExc_TypeError, \"Can not convert C Type " . mapTypeName($ctype) . " from Python\");");
return;
}
my $export = "pyrpc_export_union($ctype_name, $mem_ctx, $switch, $cvar, \"".mapTypeName($ctype)."\")";
$self->assign($target, "(".mapTypeName($ctype)." *)$export");
return;
}
if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "DATA_BLOB") {
$self->pidl("$target = data_blob_talloc($mem_ctx, PyBytes_AS_STRING($cvar), PyBytes_GET_SIZE($cvar));");
return;
}
if ($actual_ctype->{TYPE} eq "SCALAR" and
($actual_ctype->{NAME} eq "string"
or $actual_ctype->{NAME} eq "nbt_string"
or $actual_ctype->{NAME} eq "nbt_name"
or $actual_ctype->{NAME} eq "wrepl_nbt_name"
or $actual_ctype->{NAME} eq "dns_string"
or $actual_ctype->{NAME} eq "dnsp_string"
or $actual_ctype->{NAME} eq "dns_name"
or $actual_ctype->{NAME} eq "ipv4address"
or $actual_ctype->{NAME} eq "ipv6address"
or $actual_ctype->{NAME} eq "dnsp_name")) {
$self->ConvertStringFromPythonData($mem_ctx, $cvar, $target, $fail);
return;
}
if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "NTSTATUS") {
$self->pidl("$target = NT_STATUS(PyInt_AsLong($cvar));");
return;
}
if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "WERROR") {
$self->pidl("$target = W_ERROR(PyInt_AsLong($cvar));");
return;
}
if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "HRESULT") {
$self->pidl("$target = HRES_ERROR(PyInt_AsLong($cvar));");
return;
}
if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "string_array") {
$self->pidl("$target = pytalloc_get_ptr($cvar);");
return;
}
if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "pointer") {
$self->assign($target, "pytalloc_get_ptr($cvar)");
return;
}
fatal($location, "unknown type `$actual_ctype->{TYPE}' for ".mapTypeName($ctype) . ": $cvar");
}
sub ConvertObjectFromPythonLevel($$$$$$$$$)
{
my ($self, $env, $mem_ctx, $py_var, $e, $l, $var_name, $fail, $recurse) = @_;
my $nl = GetNextLevel($e, $l);
if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
$nl = GetNextLevel($e, $nl);
}
my $pl = GetPrevLevel($e, $l);
if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
$pl = GetPrevLevel($e, $pl);
}
if ($recurse == 0) {
$self->pidl("if ($py_var == NULL) {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_AttributeError, \"Cannot delete NDR object: " .
mapTypeName($var_name) . "\");");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
}
$recurse = $recurse + 1;
if ($l->{TYPE} eq "POINTER") {
if ($l->{POINTER_TYPE} ne "ref") {
$self->pidl("if ($py_var == Py_None) {");
$self->indent;
$self->pidl("$var_name = NULL;");
$self->deindent;
$self->pidl("} else {");
$self->indent;
}
# if we want to handle more than one level of pointer in python interfaces
# then this is where we would need to allocate it
if ($l->{POINTER_TYPE} eq "ref") {
$self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
$self->pidl("if ($var_name == NULL) {");
$self->indent;
$self->pidl("PyErr_NoMemory();");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
} elsif ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::is_scalar($nl->{DATA_TYPE})
and not Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
$self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
$self->pidl("if ($var_name == NULL) {");
$self->indent;
$self->pidl("PyErr_NoMemory();");
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
} else {
$self->pidl("$var_name = NULL;");
}
unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
$var_name = get_value_of($var_name);
}
$self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail, $recurse);
if ($l->{POINTER_TYPE} ne "ref") {
$self->deindent;
$self->pidl("}");
}
} elsif ($l->{TYPE} eq "ARRAY") {
if ($pl && $pl->{TYPE} eq "POINTER") {
$var_name = get_pointer_to($var_name);
}
if (is_charset_array($e, $l)) {
$self->ConvertStringFromPythonData($mem_ctx, $py_var, $var_name, $fail);
} else {
my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
$self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
$self->pidl("{");
$self->indent;
$self->pidl("int $counter;");
if (ArrayDynamicallyAllocated($e, $l)) {
$self->pidl("$var_name = talloc_array_ptrtype($mem_ctx, $var_name, PyList_GET_SIZE($py_var));");
$self->pidl("if (!$var_name) { $fail; }");
$self->pidl("talloc_set_name_const($var_name, \"ARRAY: $var_name\");");
} else {
$self->pidl("if (ARRAY_SIZE($var_name) != PyList_GET_SIZE($py_var)) {");
$self->indent;
$self->pidl("PyErr_Format(PyExc_TypeError, \"Expected list of type %s, length %zu, got %zd\", Py_TYPE($py_var)->tp_name, ARRAY_SIZE($var_name), PyList_GET_SIZE($py_var));");
$self->pidl("$fail");
$self->deindent;
$self->pidl("}");
}
$self->pidl("for ($counter = 0; $counter < PyList_GET_SIZE($py_var); $counter++) {");
$self->indent;
$self->ConvertObjectFromPythonLevel($env, $var_name, "PyList_GET_ITEM($py_var, $counter)", $e, $nl, $var_name."[$counter]", $fail, 0);
$self->deindent;
$self->pidl("}");
$self->deindent;
$self->pidl("}");
}
} elsif ($l->{TYPE} eq "DATA") {
if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
$var_name = get_pointer_to($var_name);
}
$self->ConvertObjectFromPythonData($mem_ctx, $py_var, $l->{DATA_TYPE}, $var_name, $fail, $e->{ORIGINAL});
} elsif ($l->{TYPE} eq "SWITCH") {
$var_name = get_pointer_to($var_name);
my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
my $switch_ptr = "$e->{NAME}_switch_$l->{LEVEL_INDEX}";
$self->pidl("{");
$self->indent;
my $union_type = mapTypeName($nl->{DATA_TYPE});
$self->pidl("$union_type *$switch_ptr;");
$self->ConvertObjectFromPythonData($mem_ctx, $py_var, $nl->{DATA_TYPE}, $switch_ptr, $fail, $e->{ORIGINAL}, $switch);
$self->fail_on_null($switch_ptr, $fail);
$self->assign($var_name, "$switch_ptr");
$self->deindent;
$self->pidl("}");
} elsif ($l->{TYPE} eq "SUBCONTEXT") {
$self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail, $recurse);
} else {
fatal($e->{ORIGINAL}, "unknown level type $l->{TYPE}");
}
}
sub ConvertObjectFromPython($$$$$$$)
{
my ($self, $env, $mem_ctx, $ctype, $cvar, $target, $fail) = @_;
my $recurse = 0;
$self->ConvertObjectFromPythonLevel($env, $mem_ctx, $cvar, $ctype, $ctype->{LEVELS}[0], $target, $fail, $recurse);
}
sub ConvertScalarToPython($$$$)
{
my ($self, $ctypename, $cvar, $mem_ctx) = @_;
die("expected string for $cvar, not $ctypename") if (ref($ctypename) eq "HASH");
$ctypename = expandAlias($ctypename);
if ($ctypename =~ /^(int64|dlong)$/) {
return "ndr_PyLong_FromLongLong($cvar)";
}
if ($ctypename =~ /^(uint64|hyper|NTTIME_hyper|NTTIME|NTTIME_1sec|udlong|udlongr|uid_t|gid_t)$/) {
return "ndr_PyLong_FromUnsignedLongLong($cvar)";
}
if ($ctypename =~ /^(char|int|int8|int16|int32|time_t)$/) {
return "PyInt_FromLong($cvar)";
}
# Needed to ensure unsigned values in a 32 or 16 bit enum is
# cast correctly to a uint32_t, not sign extended to a a
# possibly 64 bit unsigned long. (enums are signed in C,
# unsigned in NDR)
if ($ctypename =~ /^(uint32|uint3264)$/) {
return "ndr_PyLong_FromUnsignedLongLong((uint32_t)$cvar)";
}
if ($ctypename =~ /^(uint|uint8|uint16|uint1632)$/) {
return "PyInt_FromLong((uint16_t)$cvar)";
}
if ($ctypename eq "DATA_BLOB") {
return "PyBytes_FromStringAndSize((char *)($cvar).data, ($cvar).length)";
}
if ($ctypename eq "NTSTATUS") {
return "PyErr_FromNTSTATUS($cvar)";
}
if ($ctypename eq "WERROR") {
return "PyErr_FromWERROR($cvar)";
}
if ($ctypename eq "HRESULT") {
return "PyErr_FromHRESULT($cvar)";
}
if (($ctypename eq "string" or $ctypename eq "nbt_string" or $ctypename eq "nbt_name" or $ctypename eq "wrepl_nbt_name")) {
return "PyString_FromStringOrNULL($cvar)";
}
if (($ctypename eq "dns_string" or $ctypename eq "dns_name")) {
return "PyString_FromStringOrNULL($cvar)";
}
# Not yet supported
if ($ctypename eq "string_array") {
return "pytalloc_GenericObject_reference_ex($mem_ctx, $cvar)";
}
if ($ctypename eq "ipv4address") { return "PyString_FromStringOrNULL($cvar)"; }
if ($ctypename eq "ipv6address") { return "PyString_FromStringOrNULL($cvar)"; }
if ($ctypename eq "dnsp_name") { return "PyString_FromStringOrNULL($cvar)"; }
if ($ctypename eq "dnsp_string") { return "PyString_FromStringOrNULL($cvar)"; }
if ($ctypename eq "pointer") {
return "pytalloc_GenericObject_reference_ex($mem_ctx, $cvar)";
}
die("Unknown scalar type $ctypename");
}
sub ConvertObjectToPythonData($$$$$;$$)
{
my ($self, $mem_ctx, $ctype, $cvar, $location, $switch) = @_;
die("undef type for $cvar") unless(defined($ctype));
$ctype = resolveType($ctype);
my $actual_ctype = $ctype;
if ($actual_ctype->{TYPE} eq "TYPEDEF") {
$actual_ctype = $actual_ctype->{DATA};
}
if ($actual_ctype->{TYPE} eq "ENUM") {
return $self->ConvertScalarToPython(Parse::Pidl::Typelist::enum_type_fn($actual_ctype), $cvar, $mem_ctx);
} elsif ($actual_ctype->{TYPE} eq "BITMAP") {
return $self->ConvertScalarToPython(Parse::Pidl::Typelist::bitmap_type_fn($actual_ctype), $cvar, $mem_ctx);
} elsif ($actual_ctype->{TYPE} eq "SCALAR") {
return $self->ConvertScalarToPython($actual_ctype->{NAME}, $cvar, $mem_ctx);
} elsif ($actual_ctype->{TYPE} eq "UNION") {
my $ctype_name = $self->use_type_variable($ctype);
unless (defined($ctype_name)) {
error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
return "NULL"; # FIXME!
}
return "pyrpc_import_union($ctype_name, $mem_ctx, $switch, $cvar, \"".mapTypeName($ctype)."\")";
} elsif ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
my $ctype_name = $self->use_type_variable($ctype);
unless (defined($ctype_name)) {
error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
return "NULL"; # FIXME!
}
return "pytalloc_reference_ex($ctype_name, $mem_ctx, $cvar)";
}
fatal($location, "unknown type $actual_ctype->{TYPE} for ".mapTypeName($ctype) . ": $cvar");
}
sub fail_on_null($$$)
{
my ($self, $var, $fail) = @_;
$self->pidl("if ($var == NULL) {");
$self->indent;
$self->pidl($fail);
$self->deindent;
$self->pidl("}");
}
sub ConvertObjectToPythonLevel($$$$$$$)
{
my ($self, $mem_ctx, $env, $e, $l, $var_name, $py_var, $fail, $recurse) = @_;
my $nl = GetNextLevel($e, $l);
if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
$nl = GetNextLevel($e, $nl);
}
my $pl = GetPrevLevel($e, $l);
if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
$pl = GetPrevLevel($e, $pl);
}
if ($l->{TYPE} eq "POINTER") {
if ($l->{POINTER_TYPE} ne "ref") {
if ($recurse == 0) {
$self->pidl("if ($var_name == NULL) {");
$self->indent;
$self->pidl("$py_var = Py_None;");
$self->pidl("Py_INCREF($py_var);");
$self->deindent;
$self->pidl("} else {");
$self->indent;
} else {
$self->pidl("{");
$self->indent;
}
$recurse = $recurse + 1;
}
my $var_name2 = $var_name;
my $recurse2 = $recurse;
unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
$var_name2 = get_value_of($var_name);
$recurse2 = 0;
}
$self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name2, $py_var, $fail, $recurse2);
if ($l->{POINTER_TYPE} ne "ref") {
$self->deindent;
$self->pidl("}");
}
} elsif ($l->{TYPE} eq "ARRAY") {
if ($pl && $pl->{TYPE} eq "POINTER") {
$var_name = get_pointer_to($var_name);
}
if (is_charset_array($e, $l)) {
# FIXME: Use Unix charset setting rather than utf-8
$self->pidl("if ($var_name == NULL) {");
$self->indent;
$self->pidl("$py_var = Py_None;");
$self->pidl("Py_INCREF($py_var);");
$self->deindent;
$self->pidl("} else {");
$self->indent;
$self->pidl("$py_var = PyUnicode_Decode($var_name, strlen($var_name), \"utf-8\", \"ignore\");");
$self->deindent;
$self->pidl("}");
} else {
die("No SIZE_IS for array $var_name") unless (defined($l->{SIZE_IS}));
my $length = $l->{SIZE_IS};
if (defined($l->{LENGTH_IS})) {
$length = $l->{LENGTH_IS};
}
$length = ParseExpr($length, $env, $e);
$self->pidl("$py_var = PyList_New($length);");
$self->fail_on_null($py_var, $fail);
$self->pidl("{");
$self->indent;
my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
$self->pidl("int $counter;");
$self->pidl("for ($counter = 0; $counter < ($length); $counter++) {");
$self->indent;
my $member_var = "py_$e->{NAME}_$l->{LEVEL_INDEX}";
$self->pidl("PyObject *$member_var;");
$self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name."[$counter]", $member_var, $fail, $recurse);
$self->pidl("PyList_SetItem($py_var, $counter, $member_var);");
$self->deindent;
$self->pidl("}");
$self->deindent;
$self->pidl("}");
}
} elsif ($l->{TYPE} eq "SWITCH") {
$var_name = get_pointer_to($var_name);
my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
my $conv = $self->ConvertObjectToPythonData($mem_ctx, $nl->{DATA_TYPE}, $var_name, $e->{ORIGINAL}, $switch);
$self->pidl("$py_var = $conv;");
$self->fail_on_null($py_var, $fail);
} elsif ($l->{TYPE} eq "DATA") {
if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
$var_name = get_pointer_to($var_name);
}
my $conv = $self->ConvertObjectToPythonData($mem_ctx, $l->{DATA_TYPE}, $var_name, $e->{ORIGINAL});
$self->pidl("$py_var = $conv;");
} elsif ($l->{TYPE} eq "SUBCONTEXT") {
$self->ConvertObjectToPythonLevel($mem_ctx, $env, $e, $nl, $var_name, $py_var, $fail, $recurse);
} else {
fatal($e->{ORIGINAL}, "Unknown level type $l->{TYPE} $var_name");
}
}
sub ConvertObjectToPython($$$$$$)
{
my ($self, $mem_ctx, $env, $ctype, $cvar, $py_var, $fail) = @_;
my $recurse = 0;
$self->ConvertObjectToPythonLevel($mem_ctx, $env, $ctype, $ctype->{LEVELS}[0], $cvar, $py_var, $fail, $recurse);
}
sub Parse($$$$$)
{
my($self,$basename,$ndr,$ndr_hdr,$hdr) = @_;
$self->{BASENAME} = $basename;
$self->pidl_hdr("
/* Python wrapper functions auto-generated by pidl */
#define PY_SSIZE_T_CLEAN 1 /* We use Py_ssize_t for PyArg_ParseTupleAndKeywords */
#include <Python.h>
#include \"python/py3compat.h\"
#include \"includes.h\"
#include <pytalloc.h>
#include \"librpc/rpc/pyrpc.h\"
#include \"librpc/rpc/pyrpc_util.h\"
#include \"$hdr\"
#include \"$ndr_hdr\"
/*
* These functions are here to ensure they can be optimized out by
* the compiler based on the constant input values
*/
static inline unsigned long long ndr_sizeof2uintmax(size_t var_size)
{
switch (var_size) {
case 8:
return UINT64_MAX;
case 4:
return UINT32_MAX;
case 2:
return UINT16_MAX;
case 1:
return UINT8_MAX;
}
return 0;
}
static inline long long ndr_sizeof2intmax(size_t var_size)
{
switch (var_size) {
case 8:
return INT64_MAX;
case 4:
return INT32_MAX;
case 2:
return INT16_MAX;
case 1:
return INT8_MAX;
}
return 0;
}
static inline PyObject *ndr_PyLong_FromLongLong(long long v)
{
if (v > LONG_MAX || v < LONG_MIN) {
return PyLong_FromLongLong(v);
} else {
return PyInt_FromLong(v);
}
}
static inline PyObject *ndr_PyLong_FromUnsignedLongLong(unsigned long long v)
{
if (v > LONG_MAX) {
return PyLong_FromUnsignedLongLong(v);
} else {
return PyInt_FromLong(v);
}
}
");
foreach my $x (@$ndr) {
($x->{TYPE} eq "IMPORT") && $self->Import(@{$x->{PATHS}});
($x->{TYPE} eq "INTERFACE") && $self->Interface($x, $basename);
}
$self->pidl("static PyMethodDef $basename\_methods[] = {");
$self->indent;
foreach (@{$self->{module_methods}}) {
my ($fn_name, $pyfn_name, $flags, $doc) = @$_;
$self->pidl("{ \"$fn_name\", (PyCFunction)$pyfn_name, $flags, $doc },");
}
$self->pidl("{ NULL, NULL, 0, NULL }");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl("static struct PyModuleDef moduledef = {");
$self->indent;
$self->pidl("PyModuleDef_HEAD_INIT,");
$self->pidl(".m_name = \"$basename\",");
$self->pidl(".m_doc = \"$basename DCE/RPC\",");
$self->pidl(".m_size = -1,");
$self->pidl(".m_methods = $basename\_methods,");
$self->deindent;
$self->pidl("};");
$self->pidl("MODULE_INIT_FUNC($basename)");
$self->pidl("{");
$self->indent;
$self->pidl("PyObject *m;");
foreach my $h (@{$self->{module_imports}}) {
$self->pidl("PyObject *$h->{'key'};");
}
$self->pidl("");
foreach my $h (@{$self->{module_imports}}) {
my $var_name = $h->{'key'};
my $module_path = $h->{'val'};
$self->pidl("$var_name = PyImport_ImportModule(\"$module_path\");");
$self->pidl("if ($var_name == NULL)");
$self->pidl("\treturn NULL;");
$self->pidl("");
}
foreach my $h (@{$self->{type_imports}}) {
my $type_var = "$h->{'key'}\_Type";
my $module_path = $h->{'val'};
$self->pidl_hdr("static PyTypeObject *$type_var;\n");
my $pretty_name = PrettifyTypeName($h->{'key'}, $module_path);
my $module_var = "dep_$module_path";
$module_var =~ s/\./_/g;
$self->pidl("$type_var = (PyTypeObject *)PyObject_GetAttrString($module_var, \"$pretty_name\");");
$self->pidl("if ($type_var == NULL)");
$self->pidl("\treturn NULL;");
$self->pidl("");
}
$self->pidl($_) foreach (@{$self->{prereadycode}});
foreach (@{$self->{ready_types}}) {
$self->pidl("if (PyType_Ready($_) < 0)");
$self->pidl("\treturn NULL;");
}
$self->pidl($_) foreach (@{$self->{postreadycode}});
foreach (@{$self->{patch_type_calls}}) {
my ($typename, $cvar) = @$_;
$self->pidl("#ifdef PY_".uc($typename)."_PATCH");
$self->pidl("PY_".uc($typename)."_PATCH($cvar);");
$self->pidl("#endif");
}
$self->pidl("");
$self->pidl("m = PyModule_Create(&moduledef);");
$self->pidl("if (m == NULL)");
$self->pidl("\treturn NULL;");
$self->pidl("");
foreach my $h (@{$self->{constants}}) {
my $pretty_name = PrettifyTypeName($h->{'key'}, $basename);
my $py_obj;
my ($ctype, $cvar) = @{$h->{'val'}};
if ($cvar =~ /^[0-9]+$/ or $cvar =~ /^0x[0-9a-fA-F]+$/) {
$py_obj = "ndr_PyLong_FromUnsignedLongLong($cvar)";
} elsif ($cvar =~ /^".*"$/) {
$py_obj = "PyStr_FromString($cvar)";
} else {
$py_obj = $self->ConvertObjectToPythonData("NULL", expandAlias($ctype), $cvar, undef);
}
$self->pidl("PyModule_AddObject(m, \"$pretty_name\", $py_obj);");
}
foreach (@{$self->{module_objects}}) {
my ($object_name, $c_name) = @$_;
$self->pidl("Py_INCREF($c_name);");
$self->pidl("PyModule_AddObject(m, \"$object_name\", $c_name);");
}
$self->pidl("#ifdef PY_MOD_".uc($basename)."_PATCH");
$self->pidl("PY_MOD_".uc($basename)."_PATCH(m);");
$self->pidl("#endif");
$self->pidl("return m;");
$self->pidl("");
$self->deindent;
$self->pidl("}");
return ($self->{res_hdr} . $self->{res});
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/TDR.pm | ###################################################
# Trivial Parser Generator
# Copyright [email protected] 2005-2007
# released under the GNU GPL
package Parse::Pidl::Samba4::TDR;
use Parse::Pidl qw(fatal);
use Parse::Pidl::Util qw(has_property ParseExpr is_constant);
use Parse::Pidl::Samba4 qw(is_intree choose_header);
use Parse::Pidl::Typelist qw(mapTypeName);
use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(ParserType $ret $ret_hdr);
use vars qw($VERSION);
$VERSION = '0.01';
use strict;
sub new($) {
my ($class) = shift;
my $self = { ret => "", ret_hdr => "", tabs => "" };
bless($self, $class);
}
sub indent($) { my $self = shift; $self->{tabs}.="\t"; }
sub deindent($) { my $self = shift; $self->{tabs} = substr($self->{tabs}, 1); }
sub pidl($$) { my $self = shift; $self->{ret} .= $self->{tabs}.(shift)."\n"; }
sub pidl_hdr($$) { my $self = shift; $self->{ret_hdr} .= (shift)."\n"; }
sub typearg($) {
my $t = shift;
return(", const char *name") if ($t eq "print");
return(", TALLOC_CTX *mem_ctx") if ($t eq "pull");
return("");
}
sub fn_declare($$$)
{
my ($self, $p, $d) = @_;
if ($p) {
$self->pidl($d); $self->pidl_hdr("$d;");
} else {
$self->pidl("static $d");
}
}
sub ContainsArray($)
{
my $e = shift;
foreach (@{$e->{ELEMENTS}}) {
next if (has_property($_, "charset") and
scalar(@{$_->{ARRAY_LEN}}) == 1);
return 1 if (defined($_->{ARRAY_LEN}) and
scalar(@{$_->{ARRAY_LEN}}) > 0);
}
return 0;
}
sub ParserElement($$$$)
{
my ($self, $e,$t,$env) = @_;
my $switch = "";
my $array = "";
my $name = "";
my $mem_ctx = "mem_ctx";
fatal($e,"Pointers not supported in TDR") if ($e->{POINTERS} > 0);
fatal($e,"size_is() not supported in TDR") if (has_property($e, "size_is"));
fatal($e,"length_is() not supported in TDR") if (has_property($e, "length_is"));
if ($t eq "print") {
$name = ", \"$e->{NAME}\"$array";
}
if (has_property($e, "flag")) {
$self->pidl("{");
$self->indent;
$self->pidl("uint32_t saved_flags = tdr->flags;");
$self->pidl("tdr->flags |= $e->{PROPERTIES}->{flag};");
}
if (has_property($e, "charset")) {
fatal($e,"charset() on non-array element") unless (defined($e->{ARRAY_LEN}) and scalar(@{$e->{ARRAY_LEN}}) > 0);
my $len = ParseExpr(@{$e->{ARRAY_LEN}}[0], $env, $e);
if ($len eq "*") { $len = "-1"; }
$name = ", mem_ctx" if ($t eq "pull");
$self->pidl("TDR_CHECK(tdr_$t\_charset(tdr$name, &v->$e->{NAME}, $len, sizeof($e->{TYPE}_t), CH_$e->{PROPERTIES}->{charset}));");
return;
}
if (has_property($e, "switch_is")) {
$switch = ", " . ParseExpr($e->{PROPERTIES}->{switch_is}, $env, $e);
}
if (defined($e->{ARRAY_LEN}) and scalar(@{$e->{ARRAY_LEN}}) > 0) {
my $len = ParseExpr($e->{ARRAY_LEN}[0], $env, $e);
if ($t eq "pull" and not is_constant($len)) {
$self->pidl("TDR_ALLOC(mem_ctx, v->$e->{NAME}, $len);");
$mem_ctx = "v->$e->{NAME}";
}
$self->pidl("for (i = 0; i < $len; i++) {");
$self->indent;
$array = "[i]";
}
if ($t eq "pull") {
$name = ", $mem_ctx";
}
if (has_property($e, "value") && $t eq "push") {
$self->pidl("v->$e->{NAME} = ".ParseExpr($e->{PROPERTIES}->{value}, $env, $e).";");
}
$self->pidl("TDR_CHECK(tdr_$t\_$e->{TYPE}(tdr$name$switch, &v->$e->{NAME}$array));");
if ($array) { $self->deindent; $self->pidl("}"); }
if (has_property($e, "flag")) {
$self->pidl("tdr->flags = saved_flags;");
$self->deindent;
$self->pidl("}");
}
}
sub ParserStruct($$$$$)
{
my ($self, $e,$t,$p) = @_;
$self->fn_declare($p,"NTSTATUS tdr_$t\_$e->{NAME} (struct tdr_$t *tdr".typearg($t).", struct $e->{NAME} *v)");
$self->pidl("{"); $self->indent;
$self->pidl("int i;") if (ContainsArray($e));
if ($t eq "print") {
$self->pidl("tdr->print(tdr, \"\%-25s: struct $e->{NAME}\", name);");
$self->pidl("tdr->level++;");
}
my %env = map { $_->{NAME} => "v->$_->{NAME}" } @{$e->{ELEMENTS}};
$env{"this"} = "v";
$self->ParserElement($_, $t, \%env) foreach (@{$e->{ELEMENTS}});
if ($t eq "print") {
$self->pidl("tdr->level--;");
}
$self->pidl("return NT_STATUS_OK;");
$self->deindent; $self->pidl("}");
}
sub ParserUnion($$$$)
{
my ($self, $e,$t,$p) = @_;
$self->fn_declare($p,"NTSTATUS tdr_$t\_$e->{NAME}(struct tdr_$t *tdr".typearg($t).", int level, union $e->{NAME} *v)");
$self->pidl("{"); $self->indent;
$self->pidl("int i;") if (ContainsArray($e));
if ($t eq "print") {
$self->pidl("tdr->print(tdr, \"\%-25s: union $e->{NAME}\", name);");
$self->pidl("tdr->level++;");
}
$self->pidl("switch (level) {"); $self->indent;
foreach (@{$e->{ELEMENTS}}) {
if (has_property($_, "case")) {
$self->pidl("case " . $_->{PROPERTIES}->{case} . ":");
} elsif (has_property($_, "default")) {
$self->pidl("default:");
}
$self->indent; $self->ParserElement($_, $t, {}); $self->deindent;
$self->pidl("break;");
}
$self->deindent; $self->pidl("}");
if ($t eq "print") {
$self->pidl("tdr->level--;");
}
$self->pidl("return NT_STATUS_OK;\n");
$self->deindent; $self->pidl("}");
}
sub ParserBitmap($$$$)
{
my ($self,$e,$t,$p) = @_;
return if ($p);
$self->pidl("#define tdr_$t\_$e->{NAME} tdr_$t\_" . Parse::Pidl::Typelist::bitmap_type_fn($e));
}
sub ParserEnum($$$$)
{
my ($self,$e,$t,$p) = @_;
my $bt = Parse::Pidl::Typelist::enum_type_fn($e);
my $mt = mapTypeName($bt);
$self->fn_declare($p, "NTSTATUS tdr_$t\_$e->{NAME} (struct tdr_$t *tdr".typearg($t).", enum $e->{NAME} *v)");
$self->pidl("{");
if ($t eq "pull") {
$self->pidl("\t$mt r;");
$self->pidl("\tTDR_CHECK(tdr_$t\_$bt(tdr, mem_ctx, \&r));");
$self->pidl("\t*v = r;");
} elsif ($t eq "push") {
$self->pidl("\tTDR_CHECK(tdr_$t\_$bt(tdr, ($mt *)v));");
} elsif ($t eq "print") {
$self->pidl("\t/* FIXME */");
}
$self->pidl("\treturn NT_STATUS_OK;");
$self->pidl("}");
}
sub ParserTypedef($$$$)
{
my ($self, $e,$t,$p) = @_;
$self->ParserType($e->{DATA},$t);
}
sub ParserType($$$)
{
my ($self, $e,$t) = @_;
return if (has_property($e, "no$t"));
my $handlers = {
STRUCT => \&ParserStruct, UNION => \&ParserUnion,
ENUM => \&ParserEnum, BITMAP => \&ParserBitmap,
TYPEDEF => \&ParserTypedef
};
$handlers->{$e->{TYPE}}->($self, $e, $t, has_property($e, "public"))
if (defined($handlers->{$e->{TYPE}}));
$self->pidl("");
}
sub ParserInterface($$)
{
my ($self,$x) = @_;
$self->pidl_hdr("#ifndef __TDR_$x->{NAME}_HEADER__");
$self->pidl_hdr("#define __TDR_$x->{NAME}_HEADER__");
foreach (@{$x->{DATA}}) {
$self->ParserType($_, "pull");
$self->ParserType($_, "push");
$self->ParserType($_, "print");
}
$self->pidl_hdr("#endif /* __TDR_$x->{NAME}_HEADER__ */");
}
sub Parser($$$$)
{
my ($self,$idl,$hdrname,$baseheader) = @_;
$self->pidl("/* autogenerated by pidl */");
if (is_intree()) {
$self->pidl("#include \"includes.h\"");
} else {
$self->pidl("#include <stdio.h>");
$self->pidl("#include <stdbool.h>");
$self->pidl("#include <stdlib.h>");
$self->pidl("#include <stdint.h>");
$self->pidl("#include <stdarg.h>");
$self->pidl("#include <string.h>");
$self->pidl("#include <core/ntstatus.h>");
}
$self->pidl("#include \"$hdrname\"");
$self->pidl("");
$self->pidl_hdr("/* autogenerated by pidl */");
$self->pidl_hdr("#include \"$baseheader\"");
$self->pidl_hdr(choose_header("lib/tdr/tdr.h", "tdr.h"));
$self->pidl_hdr("");
foreach (@$idl) { $self->ParserInterface($_) if ($_->{TYPE} eq "INTERFACE"); }
return ($self->{ret_hdr}, $self->{ret});
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/Template.pm | ###################################################
# server template function generator
# Copyright [email protected] 2003
# released under the GNU GPL
package Parse::Pidl::Samba4::Template;
use vars qw($VERSION);
$VERSION = '0.01';
use Parse::Pidl::Util qw(genpad);
use strict;
my($res);
#####################################################################
# produce boilerplate code for a interface
sub Template($)
{
my($interface) = shift;
my($data) = $interface->{DATA};
my $name = $interface->{NAME};
$res .=
"/*
Unix SMB/CIFS implementation.
endpoint server for the $name pipe
Copyright (C) YOUR NAME HERE YEAR
SPDX-License-Identifier: GPL-3.0-or-later
*/
#include \"includes.h\"
#include \"rpc_server/dcerpc_server.h\"
#include \"librpc/gen_ndr/ndr_$name.h\"
#include \"rpc_server/common/common.h\"
";
foreach my $d (@{$data}) {
if ($d->{TYPE} eq "FUNCTION") {
my $fname = $d->{NAME};
my $pad = genpad("static $d->{RETURN_TYPE} dcesrv_$fname");
$res .=
"
/*
$fname
*/
static $d->{RETURN_TYPE} dcesrv_$fname(struct dcesrv_call_state *dce_call,
$pad"."TALLOC_CTX *mem_ctx,
$pad"."struct $fname *r)
{
";
if ($d->{RETURN_TYPE} eq "void") {
$res .= "\tDCESRV_FAULT_VOID(DCERPC_FAULT_OP_RNG_ERROR);\n";
} else {
$res .= "\tDCESRV_FAULT(DCERPC_FAULT_OP_RNG_ERROR);\n";
}
$res .= "}
";
}
}
$res .=
"
/* include the generated boilerplate */
#include \"librpc/gen_ndr/ndr_$name\_s.c\"
"
}
#####################################################################
# parse a parsed IDL structure back into an IDL file
sub Parse($)
{
my($idl) = shift;
$res = "";
foreach my $x (@{$idl}) {
($x->{TYPE} eq "INTERFACE") &&
Template($x);
}
return $res;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/COM/Header.pm | # COM Header generation
# (C) 2005 Jelmer Vernooij <[email protected]>
package Parse::Pidl::Samba4::COM::Header;
use Parse::Pidl::Typelist qw(mapTypeName);
use Parse::Pidl::Util qw(has_property is_constant);
use vars qw($VERSION);
$VERSION = '0.01';
use strict;
sub GetArgumentProtoList($)
{
my $f = shift;
my $res = "";
foreach my $a (@{$f->{ELEMENTS}}) {
$res .= ", " . mapTypeName($a->{TYPE}) . " ";
my $l = $a->{POINTERS};
$l-- if (Parse::Pidl::Typelist::scalar_is_reference($a->{TYPE}));
foreach my $i (1..$l) {
$res .= "*";
}
if (defined $a->{ARRAY_LEN}[0] && !is_constant($a->{ARRAY_LEN}[0]) &&
!$a->{POINTERS}) {
$res .= "*";
}
$res .= $a->{NAME};
if (defined $a->{ARRAY_LEN}[0] && is_constant($a->{ARRAY_LEN}[0])) {
$res .= "[$a->{ARRAY_LEN}[0]]";
}
}
return $res;
}
sub GetArgumentList($)
{
my $f = shift;
my $res = "";
foreach (@{$f->{ELEMENTS}}) { $res .= ", $_->{NAME}"; }
return $res;
}
#####################################################################
# generate vtable structure for COM interface
sub HeaderVTable($)
{
my $interface = shift;
my $res;
$res .= "#define " . uc($interface->{NAME}) . "_METHODS \\\n";
if (defined($interface->{BASE})) {
$res .= "\t" . uc($interface->{BASE} . "_METHODS") . "\\\n";
}
my $data = $interface->{DATA};
foreach my $d (@{$data}) {
$res .= "\t" . mapTypeName($d->{RETURN_TYPE}) . " (*$d->{NAME}) (struct $interface->{NAME} *d, TALLOC_CTX *mem_ctx" . GetArgumentProtoList($d) . ");\\\n" if ($d->{TYPE} eq "FUNCTION");
}
$res .= "\n";
$res .= "struct $interface->{NAME}_vtable {\n";
$res .= "\tstruct GUID iid;\n";
$res .= "\t" . uc($interface->{NAME}) . "_METHODS\n";
$res .= "};\n\n";
return $res;
}
sub ParseInterface($)
{
my $if = shift;
my $res;
$res .= "\n#ifndef _$if->{NAME}_\n";
$res .= "#define _$if->{NAME}_\n";
$res .="\n\n/* $if->{NAME} */\n";
$res .="#define COM_" . uc($if->{NAME}) . "_UUID $if->{PROPERTIES}->{uuid}\n\n";
$res .="struct $if->{NAME}_vtable;\n\n";
$res .="struct $if->{NAME} {
struct OBJREF obj;
struct com_context *ctx;
struct $if->{NAME}_vtable *vtable;
void *object_data;
};\n\n";
$res.=HeaderVTable($if);
foreach my $d (@{$if->{DATA}}) {
next if ($d->{TYPE} ne "FUNCTION");
$res .= "#define $if->{NAME}_$d->{NAME}(interface, mem_ctx" . GetArgumentList($d) . ") ";
$res .= "((interface)->vtable->$d->{NAME}(interface, mem_ctx" . GetArgumentList($d) . "))";
$res .="\n";
}
$res .= "#endif\n";
return $res;
}
sub ParseCoClass($)
{
my ($c) = @_;
my $res = "";
$res .= "#define CLSID_" . uc($c->{NAME}) . " $c->{PROPERTIES}->{uuid}\n";
if (has_property($c, "progid")) {
$res .= "#define PROGID_" . uc($c->{NAME}) . " $c->{PROPERTIES}->{progid}\n";
}
$res .= "\n";
return $res;
}
sub Parse($$)
{
my ($idl,$ndr_header) = @_;
my $res = "";
my $has_obj = 0;
$res .= "#include \"librpc/gen_ndr/orpc.h\"\n" .
"#include \"$ndr_header\"\n\n";
foreach (@{$idl})
{
if ($_->{TYPE} eq "INTERFACE" && has_property($_, "object")) {
$res .="struct $_->{NAME};\n";
$has_obj = 1;
}
}
foreach (@{$idl})
{
if ($_->{TYPE} eq "INTERFACE" && has_property($_, "object")) {
$res.=ParseInterface($_);
$has_obj = 1;
}
if ($_->{TYPE} eq "COCLASS") {
$res.=ParseCoClass($_);
$has_obj = 1;
}
}
return $res if ($has_obj);
return undef;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/COM/Proxy.pm | ###################################################
# DCOM parser for Samba
# Basically the glue between COM and DCE/RPC with NDR
# Copyright [email protected] 2003-2005
# released under the GNU GPL
package Parse::Pidl::Samba4::COM::Proxy;
use Parse::Pidl::Samba4::COM::Header;
use Parse::Pidl::Typelist qw(mapTypeName);
use Parse::Pidl::Util qw(has_property);
use vars qw($VERSION);
$VERSION = '0.01';
use strict;
my($res);
sub ParseVTable($$)
{
my ($interface, $name) = @_;
# Generate the vtable
$res .="\tstruct $interface->{NAME}_vtable $name = {";
if (defined($interface->{BASE})) {
$res .= "\n\t\t{},";
}
my $data = $interface->{DATA};
foreach my $d (@{$data}) {
if ($d->{TYPE} eq "FUNCTION") {
$res .= "\n\t\tdcom_proxy_$interface->{NAME}_$d->{NAME}";
$res .= ",";
}
}
$res .= "\n\t};\n\n";
}
sub ParseRegFunc($)
{
my $interface = shift;
$res .= "static NTSTATUS dcom_proxy_$interface->{NAME}_init(TALLOC_CTX *ctx)
{
struct $interface->{NAME}_vtable *proxy_vtable = talloc(ctx, struct $interface->{NAME}_vtable);
";
if (defined($interface->{BASE})) {
$res.= "
struct GUID base_iid;
const void *base_vtable;
base_iid = ndr_table_$interface->{BASE}.syntax_id.uuid;
base_vtable = dcom_proxy_vtable_by_iid(&base_iid);
if (base_vtable == NULL) {
DEBUG(0, (\"No proxy registered for base interface '$interface->{BASE}'\\n\"));
return NT_STATUS_FOOBAR;
}
memcpy(&proxy_vtable, base_vtable, sizeof(struct $interface->{BASE}_vtable));
";
}
foreach my $x (@{$interface->{DATA}}) {
next unless ($x->{TYPE} eq "FUNCTION");
$res .= "\tproxy_vtable->$x->{NAME} = dcom_proxy_$interface->{NAME}_$x->{NAME};\n";
}
$res.= "
proxy_vtable->iid = ndr_table_$interface->{NAME}.syntax_id.uuid;
return dcom_register_proxy(ctx, (struct IUnknown_vtable *)proxy_vtable);
}\n\n";
}
#####################################################################
# parse a function
sub ParseFunction($$)
{
my ($interface, $fn) = @_;
my $name = $fn->{NAME};
my $uname = uc $name;
my $tn = mapTypeName($fn->{RETURN_TYPE});
$res.="
static $tn dcom_proxy_$interface->{NAME}_$name(struct $interface->{NAME} *d, TALLOC_CTX *mem_ctx" . Parse::Pidl::Samba4::COM::Header::GetArgumentProtoList($fn) . ")
{
struct dcerpc_pipe *p;
NTSTATUS status = dcom_get_pipe(d, &p);
struct $name r;
struct rpc_request *req;
if (NT_STATUS_IS_ERR(status)) {
return status;
}
ZERO_STRUCT(r.in.ORPCthis);
r.in.ORPCthis.version.MajorVersion = COM_MAJOR_VERSION;
r.in.ORPCthis.version.MinorVersion = COM_MINOR_VERSION;
";
# Put arguments into r
foreach my $a (@{$fn->{ELEMENTS}}) {
next unless (has_property($a, "in"));
if (Parse::Pidl::Typelist::typeIs($a->{TYPE}, "INTERFACE")) {
$res .="\tNDR_CHECK(dcom_OBJREF_from_IUnknown(mem_ctx, &r.in.$a->{NAME}.obj, $a->{NAME}));\n";
} else {
$res .= "\tr.in.$a->{NAME} = $a->{NAME};\n";
}
}
$res .="
if (p->conn->flags & DCERPC_DEBUG_PRINT_IN) {
NDR_PRINT_IN_DEBUG($name, &r);
}
status = dcerpc_ndr_request(p, &d->ipid, &ndr_table_$interface->{NAME}, NDR_$uname, mem_ctx, &r);
if (NT_STATUS_IS_OK(status) && (p->conn->flags & DCERPC_DEBUG_PRINT_OUT)) {
NDR_PRINT_OUT_DEBUG($name, r);
}
";
# Put r info back into arguments
foreach my $a (@{$fn->{ELEMENTS}}) {
next unless (has_property($a, "out"));
if (Parse::Pidl::Typelist::typeIs($a->{TYPE}, "INTERFACE")) {
$res .="\tNDR_CHECK(dcom_IUnknown_from_OBJREF(d->ctx, &$a->{NAME}, r.out.$a->{NAME}.obj));\n";
} else {
$res .= "\t*$a->{NAME} = r.out.$a->{NAME};\n";
}
}
if ($fn->{RETURN_TYPE} eq "NTSTATUS") {
$res .= "\tif (NT_STATUS_IS_OK(status)) status = r.out.result;\n";
}
$res .=
"
return r.out.result;
}\n\n";
}
#####################################################################
# parse the interface definitions
sub ParseInterface($)
{
my($interface) = shift;
my($data) = $interface->{DATA};
$res = "/* DCOM proxy for $interface->{NAME} generated by pidl */\n\n";
foreach my $d (@{$data}) {
($d->{TYPE} eq "FUNCTION") &&
ParseFunction($interface, $d);
}
ParseRegFunc($interface);
}
sub RegistrationFunction($$)
{
my $idl = shift;
my $basename = shift;
my $res = "\n\nNTSTATUS dcom_$basename\_init(void)\n";
$res .= "{\n";
$res .="\tNTSTATUS status = NT_STATUS_OK;\n";
foreach my $interface (@{$idl}) {
next if $interface->{TYPE} ne "INTERFACE";
next if not has_property($interface, "object");
my $data = $interface->{DATA};
my $count = 0;
foreach my $d (@{$data}) {
if ($d->{TYPE} eq "FUNCTION") { $count++; }
}
next if ($count == 0);
$res .= "\tstatus = dcom_$interface->{NAME}_init();\n";
$res .= "\tif (NT_STATUS_IS_ERR(status)) {\n";
$res .= "\t\treturn status;\n";
$res .= "\t}\n\n";
}
$res .= "\treturn status;\n";
$res .= "}\n\n";
return $res;
}
sub Parse($$)
{
my ($pidl,$comh_filename) = @_;
my $res = "";
my $has_obj = 0;
$res .= "#include \"includes.h\"\n" .
"#include \"lib/com/dcom/dcom.h\"\n" .
"#include \"$comh_filename\"\n" .
"#include \"librpc/rpc/dcerpc.h\"\n";
foreach (@{$pidl}) {
next if ($_->{TYPE} ne "INTERFACE");
next if has_property($_, "local");
next unless has_property($_, "object");
$res .= ParseInterface($_);
$has_obj = 1;
}
return $res if ($has_obj);
return undef;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/COM/Stub.pm | ###################################################
# DCOM stub boilerplate generator
# Copyright [email protected] 2004-2005
# Copyright [email protected] 2003
# Copyright [email protected] 2004
# released under the GNU GPL
package Parse::Pidl::Samba4::COM::Stub;
use Parse::Pidl::Util qw(has_property);
use strict;
use vars qw($VERSION);
$VERSION = '0.01';
my($res);
sub pidl($)
{
$res .= shift;
}
#####################################################
# generate the switch statement for function dispatch
sub gen_dispatch_switch($)
{
my $data = shift;
my $count = 0;
foreach my $d (@{$data}) {
next if ($d->{TYPE} ne "FUNCTION");
pidl "\tcase $count: {\n";
if ($d->{RETURN_TYPE} && $d->{RETURN_TYPE} ne "void") {
pidl "\t\tNTSTATUS result;\n";
}
pidl "\t\tstruct $d->{NAME} *r2 = r;\n";
pidl "\t\tif (DEBUGLEVEL > 10) {\n";
pidl "\t\t\tNDR_PRINT_FUNCTION_DEBUG($d->{NAME}, NDR_IN, r2);\n";
pidl "\t\t}\n";
if ($d->{RETURN_TYPE} && $d->{RETURN_TYPE} ne "void") {
pidl "\t\tresult = vtable->$d->{NAME}(iface, mem_ctx, r2);\n";
} else {
pidl "\t\tvtable->$d->{NAME}(iface, mem_ctx, r2);\n";
}
pidl "\t\tif (dce_call->state_flags & DCESRV_CALL_STATE_FLAG_ASYNC) {\n";
pidl "\t\t\tDEBUG(5,(\"function $d->{NAME} will reply async\\n\"));\n";
pidl "\t\t}\n";
pidl "\t\tbreak;\n\t}\n";
$count++;
}
}
#####################################################
# generate the switch statement for function reply
sub gen_reply_switch($)
{
my $data = shift;
my $count = 0;
foreach my $d (@{$data}) {
next if ($d->{TYPE} ne "FUNCTION");
pidl "\tcase $count: {\n";
pidl "\t\tstruct $d->{NAME} *r2 = r;\n";
pidl "\t\tif (dce_call->state_flags & DCESRV_CALL_STATE_FLAG_ASYNC) {\n";
pidl "\t\t\tDEBUG(5,(\"function $d->{NAME} replied async\\n\"));\n";
pidl "\t\t}\n";
pidl "\t\tif (DEBUGLEVEL > 10 && dce_call->fault_code == 0) {\n";
pidl "\t\t\tNDR_PRINT_FUNCTION_DEBUG($d->{NAME}, NDR_OUT | NDR_SET_VALUES, r2);\n";
pidl "\t\t}\n";
pidl "\t\tif (dce_call->fault_code != 0) {\n";
pidl "\t\t\tDEBUG(2,(\"dcerpc_fault %s in $d->{NAME}\\n\", dcerpc_errstr(mem_ctx, dce_call->fault_code)));\n";
pidl "\t\t}\n";
pidl "\t\tbreak;\n\t}\n";
$count++;
}
}
#####################################################################
# produce boilerplate code for a interface
sub Boilerplate_Iface($)
{
my($interface) = shift;
my($data) = $interface->{DATA};
my $name = $interface->{NAME};
my $uname = uc $name;
my $uuid = Parse::Pidl::Util::make_str($interface->{PROPERTIES}->{uuid});
my $if_version = $interface->{PROPERTIES}->{version};
pidl "
static NTSTATUS $name\__op_bind(struct dcesrv_call_state *dce_call, const struct dcesrv_interface *iface, uint32_t if_version)
{
#ifdef DCESRV_INTERFACE_$uname\_BIND
return DCESRV_INTERFACE_$uname\_BIND(dce_call,iface);
#else
return NT_STATUS_OK;
#endif
}
static void $name\__op_unbind(struct dcesrv_connection_context *context, const struct dcesrv_interface *iface)
{
#ifdef DCESRV_INTERFACE_$uname\_UNBIND
DCESRV_INTERFACE_$uname\_UNBIND(context, iface);
#else
return;
#endif
}
static NTSTATUS $name\__op_ndr_pull(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, struct ndr_pull *pull, void **r)
{
NTSTATUS status;
uint16_t opnum = dce_call->pkt.u.request.opnum;
dce_call->fault_code = 0;
if (opnum >= dcerpc_table_$name.num_calls) {
dce_call->fault_code = DCERPC_FAULT_OP_RNG_ERROR;
return NT_STATUS_NET_WRITE_FAULT;
}
*r = talloc_size(mem_ctx, dcerpc_table_$name.calls[opnum].struct_size);
NT_STATUS_HAVE_NO_MEMORY(*r);
/* unravel the NDR for the packet */
status = dcerpc_table_$name.calls[opnum].ndr_pull(pull, NDR_IN, *r);
if (!NT_STATUS_IS_OK(status)) {
dcerpc_log_packet(&dcerpc_table_$name, opnum, NDR_IN,
&dce_call->pkt.u.request.stub_and_verifier);
dce_call->fault_code = DCERPC_FAULT_NDR;
return NT_STATUS_NET_WRITE_FAULT;
}
return NT_STATUS_OK;
}
static NTSTATUS $name\__op_dispatch(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, void *r)
{
uint16_t opnum = dce_call->pkt.u.request.opnum;
struct GUID ipid = dce_call->pkt.u.request.object.object;
struct dcom_interface_p *iface = dcom_get_local_iface_p(&ipid);
const struct dcom_$name\_vtable *vtable = iface->vtable;
switch (opnum) {
";
gen_dispatch_switch($data);
pidl "
default:
dce_call->fault_code = DCERPC_FAULT_OP_RNG_ERROR;
break;
}
if (dce_call->fault_code != 0) {
dcerpc_log_packet(&dcerpc_table_$name, opnum, NDR_IN,
&dce_call->pkt.u.request.stub_and_verifier);
return NT_STATUS_NET_WRITE_FAULT;
}
return NT_STATUS_OK;
}
static NTSTATUS $name\__op_reply(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, void *r)
{
uint16_t opnum = dce_call->pkt.u.request.opnum;
switch (opnum) {
";
gen_reply_switch($data);
pidl "
default:
dce_call->fault_code = DCERPC_FAULT_OP_RNG_ERROR;
break;
}
if (dce_call->fault_code != 0) {
dcerpc_log_packet(&dcerpc_table_$name, opnum, NDR_IN,
&dce_call->pkt.u.request.stub_and_verifier);
return NT_STATUS_NET_WRITE_FAULT;
}
return NT_STATUS_OK;
}
static NTSTATUS $name\__op_ndr_push(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, struct ndr_push *push, const void *r)
{
NTSTATUS status;
uint16_t opnum = dce_call->pkt.u.request.opnum;
status = dcerpc_table_$name.calls[opnum].ndr_push(push, NDR_OUT, r);
if (!NT_STATUS_IS_OK(status)) {
dce_call->fault_code = DCERPC_FAULT_NDR;
return NT_STATUS_NET_WRITE_FAULT;
}
return NT_STATUS_OK;
}
static const struct dcesrv_interface $name\_interface = {
.name = \"$name\",
.uuid = $uuid,
.if_version = $if_version,
.bind = $name\__op_bind,
.unbind = $name\__op_unbind,
.ndr_pull = $name\__op_ndr_pull,
.dispatch = $name\__op_dispatch,
.reply = $name\__op_reply,
.ndr_push = $name\__op_ndr_push
};
";
}
#####################################################################
# produce boilerplate code for an endpoint server
sub Boilerplate_Ep_Server($)
{
my($interface) = shift;
my $name = $interface->{NAME};
my $uname = uc $name;
pidl "
static NTSTATUS $name\__op_init_server(struct dcesrv_context *dce_ctx, const struct dcesrv_endpoint_server *ep_server)
{
int i;
for (i=0;i<dcerpc_table_$name.endpoints->count;i++) {
NTSTATUS ret;
const char *name = dcerpc_table_$name.endpoints->names[i];
ret = dcesrv_interface_register(dce_ctx, name, &$name\_interface, NULL);
if (!NT_STATUS_IS_OK(ret)) {
DEBUG(1,(\"$name\_op_init_server: failed to register endpoint \'%s\'\\n\",name));
return ret;
}
}
return NT_STATUS_OK;
}
static BOOL $name\__op_interface_by_uuid(struct dcesrv_interface *iface, const char *uuid, uint32_t if_version)
{
if (dcerpc_table_$name.if_version == if_version &&
strcmp(dcerpc_table_$name.uuid, uuid)==0) {
memcpy(iface,&dcerpc_table_$name, sizeof(*iface));
return True;
}
return False;
}
static BOOL $name\__op_interface_by_name(struct dcesrv_interface *iface, const char *name)
{
if (strcmp(dcerpc_table_$name.name, name)==0) {
memcpy(iface,&dcerpc_table_$name, sizeof(*iface));
return True;
}
return False;
}
NTSTATUS dcerpc_server_$name\_init(void)
{
NTSTATUS ret;
struct dcesrv_endpoint_server ep_server;
/* fill in our name */
ep_server.name = \"$name\";
/* fill in all the operations */
ep_server.init_server = $name\__op_init_server;
ep_server.interface_by_uuid = $name\__op_interface_by_uuid;
ep_server.interface_by_name = $name\__op_interface_by_name;
/* register ourselves with the DCERPC subsystem. */
ret = dcerpc_register_ep_server(&ep_server);
if (!NT_STATUS_IS_OK(ret)) {
DEBUG(0,(\"Failed to register \'$name\' endpoint server!\\n\"));
return ret;
}
return ret;
}
";
}
#####################################################################
# dcom interface stub from a parsed IDL structure
sub ParseInterface($)
{
my($interface) = shift;
return "" if has_property($interface, "local");
my($data) = $interface->{DATA};
my $count = 0;
$res = "";
if (!defined $interface->{PROPERTIES}->{uuid}) {
return $res;
}
if (!defined $interface->{PROPERTIES}->{version}) {
$interface->{PROPERTIES}->{version} = "0.0";
}
foreach my $d (@{$data}) {
if ($d->{TYPE} eq "FUNCTION") { $count++; }
}
if ($count == 0) {
return $res;
}
$res = "/* dcom interface stub generated by pidl */\n\n";
Boilerplate_Iface($interface);
Boilerplate_Ep_Server($interface);
return $res;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/NDR/Client.pm | ###################################################
# client calls generator
# Copyright [email protected] 2003
# Copyright [email protected] 2005-2006
# released under the GNU GPL
package Parse::Pidl::Samba4::NDR::Client;
use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(Parse);
use Parse::Pidl qw(fatal warning error);
use Parse::Pidl::Util qw(has_property ParseExpr genpad);
use Parse::Pidl::NDR qw(ContainsPipe);
use Parse::Pidl::Typelist qw(mapTypeName);
use Parse::Pidl::Samba4 qw(choose_header is_intree DeclLong);
use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv);
use vars qw($VERSION);
$VERSION = '0.01';
use strict;
sub indent($) { my ($self) = @_; $self->{tabs}.="\t"; }
sub deindent($) { my ($self) = @_; $self->{tabs} = substr($self->{tabs}, 1); }
sub pidl($$) { my ($self,$txt) = @_; $self->{res} .= $txt ? "$self->{tabs}$txt\n" : "\n"; }
sub pidl_hdr($$) { my ($self, $txt) = @_; $self->{res_hdr} .= "$txt\n"; }
sub pidl_both($$) { my ($self, $txt) = @_; $self->{hdr} .= "$txt\n"; $self->{res_hdr} .= "$txt\n"; }
sub fn_declare($$) { my ($self,$n) = @_; $self->pidl($n); $self->pidl_hdr("$n;"); }
sub new($)
{
my ($class) = shift;
my $self = { res => "", res_hdr => "", tabs => "" };
bless($self, $class);
}
sub ParseFunctionHasPipes($$)
{
my ($self, $fn) = @_;
foreach my $e (@{$fn->{ELEMENTS}}) {
return 1 if ContainsPipe($e, $e->{LEVELS}[0]);
}
return 0;
}
sub ParseFunction_r_State($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $uname = uc $name;
$self->pidl("struct dcerpc_$name\_r_state {");
$self->indent;
$self->pidl("TALLOC_CTX *out_mem_ctx;");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl("static void dcerpc_$name\_r_done(struct tevent_req *subreq);");
$self->pidl("");
}
sub ParseFunction_r_Send($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $uname = uc $name;
my $proto = "struct tevent_req *dcerpc_$name\_r_send(TALLOC_CTX *mem_ctx,\n";
$proto .= "\tstruct tevent_context *ev,\n",
$proto .= "\tstruct dcerpc_binding_handle *h,\n",
$proto .= "\tstruct $name *r)";
$self->fn_declare($proto);
$self->pidl("{");
$self->indent;
$self->pidl("struct tevent_req *req;");
$self->pidl("struct dcerpc_$name\_r_state *state;");
$self->pidl("struct tevent_req *subreq;");
$self->pidl("");
$self->pidl("req = tevent_req_create(mem_ctx, &state,");
$self->pidl("\t\t\tstruct dcerpc_$name\_r_state);");
$self->pidl("if (req == NULL) {");
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
my $out_params = 0;
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless grep(/out/, @{$e->{DIRECTION}});
next if ContainsPipe($e, $e->{LEVELS}[0]);
$out_params++;
}
my $submem;
if ($out_params > 0) {
$self->pidl("state->out_mem_ctx = talloc_new(state);");
$self->pidl("if (tevent_req_nomem(state->out_mem_ctx, req)) {");
$self->indent;
$self->pidl("return tevent_req_post(req, ev);");
$self->deindent;
$self->pidl("}");
$submem = "state->out_mem_ctx";
} else {
$self->pidl("state->out_mem_ctx = NULL;");
$submem = "state";
}
$self->pidl("");
$self->pidl("subreq = dcerpc_binding_handle_call_send(state, ev, h,");
$self->pidl("\t\tNULL, &ndr_table_$if->{NAME},");
$self->pidl("\t\tNDR_$uname, $submem, r);");
$self->pidl("if (tevent_req_nomem(subreq, req)) {");
$self->indent;
$self->pidl("return tevent_req_post(req, ev);");
$self->deindent;
$self->pidl("}");
$self->pidl("tevent_req_set_callback(subreq, dcerpc_$name\_r_done, req);");
$self->pidl("");
$self->pidl("return req;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunction_r_Done($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $uname = uc $name;
my $proto = "static void dcerpc_$name\_r_done(struct tevent_req *subreq)";
$self->pidl("$proto");
$self->pidl("{");
$self->indent;
$self->pidl("struct tevent_req *req =");
$self->pidl("\ttevent_req_callback_data(subreq,");
$self->pidl("\tstruct tevent_req);");
$self->pidl("NTSTATUS status;");
$self->pidl("");
$self->pidl("status = dcerpc_binding_handle_call_recv(subreq);");
$self->pidl("TALLOC_FREE(subreq);");
$self->pidl("if (tevent_req_nterror(req, status)) {");
$self->indent;
$self->pidl("return;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("tevent_req_done(req);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunction_r_Recv($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $uname = uc $name;
my $proto = "NTSTATUS dcerpc_$name\_r_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx)";
$self->fn_declare($proto);
$self->pidl("{");
$self->indent;
$self->pidl("struct dcerpc_$name\_r_state *state =");
$self->pidl("\ttevent_req_data(req,");
$self->pidl("\tstruct dcerpc_$name\_r_state);");
$self->pidl("NTSTATUS status;");
$self->pidl("");
$self->pidl("if (tevent_req_is_nterror(req, &status)) {");
$self->indent;
$self->pidl("tevent_req_received(req);");
$self->pidl("return status;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("talloc_steal(mem_ctx, state->out_mem_ctx);");
$self->pidl("");
$self->pidl("tevent_req_received(req);");
$self->pidl("return NT_STATUS_OK;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunction_r_Sync($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $uname = uc $name;
if ($self->ParseFunctionHasPipes($fn)) {
$self->pidl_both("/*");
$self->pidl_both(" * The following function is skipped because");
$self->pidl_both(" * it uses pipes:");
$self->pidl_both(" *");
$self->pidl_both(" * dcerpc_$name\_r()");
$self->pidl_both(" */");
$self->pidl_both("");
return;
}
my $proto = "NTSTATUS dcerpc_$name\_r(struct dcerpc_binding_handle *h, TALLOC_CTX *mem_ctx, struct $name *r)";
$self->fn_declare($proto);
$self->pidl("{");
$self->indent;
$self->pidl("NTSTATUS status;");
$self->pidl("");
$self->pidl("status = dcerpc_binding_handle_call(h,");
$self->pidl("\t\tNULL, &ndr_table_$if->{NAME},");
$self->pidl("\t\tNDR_$uname, mem_ctx, r);");
$self->pidl("");
$self->pidl("return status;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ElementDirection($)
{
my ($e) = @_;
return "[in,out]" if (has_property($e, "in") and has_property($e, "out"));
return "[in]" if (has_property($e, "in"));
return "[out]" if (has_property($e, "out"));
return "[in,out]";
}
sub HeaderProperties($$)
{
my($props,$ignores) = @_;
my $ret = "";
foreach my $d (sort(keys %{$props})) {
next if (grep(/^$d$/, @$ignores));
if($props->{$d} ne "1") {
$ret.= "$d($props->{$d}),";
} else {
$ret.="$d,";
}
}
if ($ret) {
return "[" . substr($ret, 0, -1) . "]";
}
}
sub ParseCopyArgument($$$$$)
{
my ($self, $fn, $e, $r, $i) = @_;
my $l = $e->{LEVELS}[0];
if ($l->{TYPE} eq "ARRAY" and $l->{IS_FIXED} == 1) {
$self->pidl("memcpy(${r}$e->{NAME}, ${i}$e->{NAME}, sizeof(${r}$e->{NAME}));");
} else {
$self->pidl("${r}$e->{NAME} = ${i}$e->{NAME};");
}
}
sub ParseInvalidResponse($$)
{
my ($self, $type) = @_;
if ($type eq "sync") {
$self->pidl("return NT_STATUS_INVALID_NETWORK_RESPONSE;");
} elsif ($type eq "async") {
$self->pidl("tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);");
$self->pidl("return;");
} else {
die("ParseInvalidResponse($type)");
}
}
sub ParseOutputArgument($$$$$$)
{
my ($self, $fn, $e, $r, $o, $invalid_response_type) = @_;
my $level = 0;
if ($e->{LEVELS}[0]->{TYPE} ne "POINTER" and $e->{LEVELS}[0]->{TYPE} ne "ARRAY") {
fatal($e->{ORIGINAL}, "[out] argument is not a pointer or array");
return;
}
if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
$level = 1;
if ($e->{LEVELS}[0]->{POINTER_TYPE} ne "ref") {
$self->pidl("if ($o$e->{NAME} && ${r}out.$e->{NAME}) {");
$self->indent;
}
}
if ($e->{LEVELS}[$level]->{TYPE} eq "ARRAY") {
# This is a call to GenerateFunctionInEnv intentionally.
# Since the data is being copied into a user-provided data
# structure, the user should be able to know the size beforehand
# to allocate a structure of the right size.
my $in_env = GenerateFunctionInEnv($fn, $r);
my $out_env = GenerateFunctionOutEnv($fn, $r);
my $l = $e->{LEVELS}[$level];
my $in_var = undef;
if (grep(/in/, @{$e->{DIRECTION}})) {
$in_var = ParseExpr($e->{NAME}, $in_env, $e->{ORIGINAL});
}
my $out_var = ParseExpr($e->{NAME}, $out_env, $e->{ORIGINAL});
my $in_size_is = undef;
my $out_size_is = undef;
my $out_length_is = undef;
my $avail_len = undef;
my $needed_len = undef;
$self->pidl("{");
$self->indent;
my $copy_len_var = "_copy_len_$e->{NAME}";
$self->pidl("size_t $copy_len_var;");
if (not defined($l->{SIZE_IS})) {
if (not $l->{IS_ZERO_TERMINATED}) {
fatal($e->{ORIGINAL}, "no size known for [out] array `$e->{NAME}'");
}
if (has_property($e, "charset")) {
$avail_len = "ndr_charset_length($in_var, CH_UNIX)";
$needed_len = "ndr_charset_length($out_var, CH_UNIX)";
} else {
$avail_len = "ndr_string_length($in_var, sizeof(*$in_var))";
$needed_len = "ndr_string_length($out_var, sizeof(*$out_var))";
}
$in_size_is = "";
$out_size_is = "";
$out_length_is = "";
} else {
$in_size_is = ParseExpr($l->{SIZE_IS}, $in_env, $e->{ORIGINAL});
$out_size_is = ParseExpr($l->{SIZE_IS}, $out_env, $e->{ORIGINAL});
$out_length_is = $out_size_is;
if (defined($l->{LENGTH_IS})) {
$out_length_is = ParseExpr($l->{LENGTH_IS}, $out_env, $e->{ORIGINAL});
}
if (has_property($e, "charset")) {
if (defined($in_var)) {
$avail_len = "ndr_charset_length($in_var, CH_UNIX)";
} else {
$avail_len = $out_length_is;
}
$needed_len = "ndr_charset_length($out_var, CH_UNIX)";
}
}
if ($out_size_is ne $in_size_is) {
$self->pidl("if (($out_size_is) > ($in_size_is)) {");
$self->indent;
$self->ParseInvalidResponse($invalid_response_type);
$self->deindent;
$self->pidl("}");
}
if ($out_length_is ne $out_size_is) {
$self->pidl("if (($out_length_is) > ($out_size_is)) {");
$self->indent;
$self->ParseInvalidResponse($invalid_response_type);
$self->deindent;
$self->pidl("}");
}
if (defined($needed_len)) {
$self->pidl("$copy_len_var = $needed_len;");
$self->pidl("if ($copy_len_var > $avail_len) {");
$self->indent;
$self->ParseInvalidResponse($invalid_response_type);
$self->deindent;
$self->pidl("}");
} else {
$self->pidl("$copy_len_var = $out_length_is;");
}
my $dest_ptr = "$o$e->{NAME}";
my $elem_size = "sizeof(*$dest_ptr)";
$self->pidl("if ($dest_ptr != $out_var) {");
$self->indent;
if (has_property($e, "charset")) {
$dest_ptr = "discard_const_p(uint8_t *, $dest_ptr)";
}
$self->pidl("memcpy($dest_ptr, $out_var, $copy_len_var * $elem_size);");
$self->deindent;
$self->pidl("}");
$self->deindent;
$self->pidl("}");
} else {
$self->pidl("*$o$e->{NAME} = *${r}out.$e->{NAME};");
}
if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
if ($e->{LEVELS}[0]->{POINTER_TYPE} ne "ref") {
$self->deindent;
$self->pidl("}");
}
}
}
sub ParseFunction_State($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $state_str = "struct dcerpc_$name\_state";
my $done_fn = "dcerpc_$name\_done";
$self->pidl("$state_str {");
$self->indent;
$self->pidl("struct $name orig;");
$self->pidl("struct $name tmp;");
$self->pidl("TALLOC_CTX *out_mem_ctx;");
$self->deindent;
$self->pidl("};");
$self->pidl("");
$self->pidl("static void $done_fn(struct tevent_req *subreq);");
$self->pidl("");
}
sub ParseFunction_Send($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $fn_args = "";
my $state_str = "struct dcerpc_$name\_state";
my $done_fn = "dcerpc_$name\_done";
my $out_mem_ctx = "dcerpc_$name\_out_memory";
my $fn_str = "struct tevent_req *dcerpc_$name\_send";
my $pad = genpad($fn_str);
$fn_args .= "TALLOC_CTX *mem_ctx";
$fn_args .= ",\n" . $pad . "struct tevent_context *ev";
$fn_args .= ",\n" . $pad . "struct dcerpc_binding_handle *h";
foreach (@{$fn->{ELEMENTS}}) {
my $dir = ElementDirection($_);
my $prop = HeaderProperties($_->{PROPERTIES}, ["in", "out"]);
$fn_args .= ",\n" . $pad . DeclLong($_, "_") . " /* $dir $prop */";
}
$self->fn_declare("$fn_str($fn_args)");
$self->pidl("{");
$self->indent;
$self->pidl("struct tevent_req *req;");
$self->pidl("$state_str *state;");
$self->pidl("struct tevent_req *subreq;");
$self->pidl("");
$self->pidl("req = tevent_req_create(mem_ctx, &state,");
$self->pidl("\t\t\t$state_str);");
$self->pidl("if (req == NULL) {");
$self->indent;
$self->pidl("return NULL;");
$self->deindent;
$self->pidl("}");
$self->pidl("state->out_mem_ctx = NULL;");
$self->pidl("");
$self->pidl("/* In parameters */");
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless (grep(/in/, @{$e->{DIRECTION}}));
$self->ParseCopyArgument($fn, $e, "state->orig.in.", "_");
}
$self->pidl("");
my $out_params = 0;
$self->pidl("/* Out parameters */");
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless grep(/out/, @{$e->{DIRECTION}});
$self->ParseCopyArgument($fn, $e, "state->orig.out.", "_");
next if ContainsPipe($e, $e->{LEVELS}[0]);
$out_params++;
}
$self->pidl("");
if (defined($fn->{RETURN_TYPE})) {
$self->pidl("/* Result */");
$self->pidl("ZERO_STRUCT(state->orig.out.result);");
$self->pidl("");
}
if ($out_params > 0) {
$self->pidl("state->out_mem_ctx = talloc_named_const(state, 0,");
$self->pidl("\t\t \"$out_mem_ctx\");");
$self->pidl("if (tevent_req_nomem(state->out_mem_ctx, req)) {");
$self->indent;
$self->pidl("return tevent_req_post(req, ev);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
$self->pidl("/* make a temporary copy, that we pass to the dispatch function */");
$self->pidl("state->tmp = state->orig;");
$self->pidl("");
$self->pidl("subreq = dcerpc_$name\_r_send(state, ev, h, &state->tmp);");
$self->pidl("if (tevent_req_nomem(subreq, req)) {");
$self->indent;
$self->pidl("return tevent_req_post(req, ev);");
$self->deindent;
$self->pidl("}");
$self->pidl("tevent_req_set_callback(subreq, $done_fn, req);");
$self->pidl("return req;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunction_Done($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $state_str = "struct dcerpc_$name\_state";
my $done_fn = "dcerpc_$name\_done";
$self->pidl("static void $done_fn(struct tevent_req *subreq)");
$self->pidl("{");
$self->indent;
$self->pidl("struct tevent_req *req = tevent_req_callback_data(");
$self->pidl("\tsubreq, struct tevent_req);");
$self->pidl("$state_str *state = tevent_req_data(");
$self->pidl("\treq, $state_str);");
$self->pidl("NTSTATUS status;");
$self->pidl("TALLOC_CTX *mem_ctx;");
$self->pidl("");
$self->pidl("if (state->out_mem_ctx) {");
$self->indent;
$self->pidl("mem_ctx = state->out_mem_ctx;");
$self->deindent;
$self->pidl("} else {");
$self->indent;
$self->pidl("mem_ctx = state;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("status = dcerpc_$name\_r_recv(subreq, mem_ctx);");
$self->pidl("TALLOC_FREE(subreq);");
$self->pidl("if (tevent_req_nterror(req, status)) {");
$self->indent;
$self->pidl("return;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("/* Copy out parameters */");
foreach my $e (@{$fn->{ELEMENTS}}) {
next if ContainsPipe($e, $e->{LEVELS}[0]);
next unless (grep(/out/, @{$e->{DIRECTION}}));
$self->ParseOutputArgument($fn, $e,
"state->tmp.",
"state->orig.out.",
"async");
}
$self->pidl("");
if (defined($fn->{RETURN_TYPE})) {
$self->pidl("/* Copy result */");
$self->pidl("state->orig.out.result = state->tmp.out.result;");
$self->pidl("");
}
$self->pidl("/* Reset temporary structure */");
$self->pidl("ZERO_STRUCT(state->tmp);");
$self->pidl("");
$self->pidl("tevent_req_done(req);");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunction_Recv($$$$)
{
my ($self, $if, $fn, $name) = @_;
my $fn_args = "";
my $state_str = "struct dcerpc_$name\_state";
my $fn_str = "NTSTATUS dcerpc_$name\_recv";
my $pad = genpad($fn_str);
$fn_args .= "struct tevent_req *req,\n" . $pad . "TALLOC_CTX *mem_ctx";
if (defined($fn->{RETURN_TYPE})) {
$fn_args .= ",\n" . $pad . mapTypeName($fn->{RETURN_TYPE}). " *result";
}
$self->fn_declare("$fn_str($fn_args)");
$self->pidl("{");
$self->indent;
$self->pidl("$state_str *state = tevent_req_data(");
$self->pidl("\treq, $state_str);");
$self->pidl("NTSTATUS status;");
$self->pidl("");
$self->pidl("if (tevent_req_is_nterror(req, &status)) {");
$self->indent;
$self->pidl("tevent_req_received(req);");
$self->pidl("return status;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("/* Steal possible out parameters to the callers context */");
$self->pidl("talloc_steal(mem_ctx, state->out_mem_ctx);");
$self->pidl("");
if (defined($fn->{RETURN_TYPE})) {
$self->pidl("/* Return result */");
$self->pidl("*result = state->orig.out.result;");
$self->pidl("");
}
$self->pidl("tevent_req_received(req);");
$self->pidl("return NT_STATUS_OK;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseFunction_Sync($$$$)
{
my ($self, $if, $fn, $name) = @_;
if ($self->ParseFunctionHasPipes($fn)) {
$self->pidl_both("/*");
$self->pidl_both(" * The following function is skipped because");
$self->pidl_both(" * it uses pipes:");
$self->pidl_both(" *");
$self->pidl_both(" * dcerpc_$name()");
$self->pidl_both(" */");
$self->pidl_both("");
return;
}
my $uname = uc $name;
my $fn_args = "";
my $fn_str = "NTSTATUS dcerpc_$name";
my $pad = genpad($fn_str);
$fn_args .= "struct dcerpc_binding_handle *h,\n" . $pad . "TALLOC_CTX *mem_ctx";
foreach (@{$fn->{ELEMENTS}}) {
my $dir = ElementDirection($_);
my $prop = HeaderProperties($_->{PROPERTIES}, ["in", "out"]);
$fn_args .= ",\n" . $pad . DeclLong($_, "_") . " /* $dir $prop */";
}
if (defined($fn->{RETURN_TYPE})) {
$fn_args .= ",\n" . $pad . mapTypeName($fn->{RETURN_TYPE}). " *result";
}
$self->fn_declare("$fn_str($fn_args)");
$self->pidl("{");
$self->indent;
$self->pidl("struct $name r;");
$self->pidl("NTSTATUS status;");
$self->pidl("");
$self->pidl("/* In parameters */");
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless (grep(/in/, @{$e->{DIRECTION}}));
$self->ParseCopyArgument($fn, $e, "r.in.", "_");
}
$self->pidl("");
$self->pidl("/* Out parameters */");
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless grep(/out/, @{$e->{DIRECTION}});
$self->ParseCopyArgument($fn, $e, "r.out.", "_");
}
$self->pidl("");
if (defined($fn->{RETURN_TYPE})) {
$self->pidl("/* Result */");
$self->pidl("ZERO_STRUCT(r.out.result);");
$self->pidl("");
}
$self->pidl("status = dcerpc_$name\_r(h, mem_ctx, &r);");
$self->pidl("if (!NT_STATUS_IS_OK(status)) {");
$self->indent;
$self->pidl("return status;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
$self->pidl("/* Return variables */");
foreach my $e (@{$fn->{ELEMENTS}}) {
next if ContainsPipe($e, $e->{LEVELS}[0]);
next unless (grep(/out/, @{$e->{DIRECTION}}));
$self->ParseOutputArgument($fn, $e, "r.", "_", "sync");
}
$self->pidl("");
$self->pidl("/* Return result */");
if ($fn->{RETURN_TYPE}) {
$self->pidl("*result = r.out.result;");
}
$self->pidl("");
$self->pidl("return NT_STATUS_OK;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
#####################################################################
# parse a function
sub ParseFunction($$$)
{
my ($self, $if, $fn) = @_;
if ($self->ParseFunctionHasPipes($fn)) {
$self->pidl_both("/*");
$self->pidl_both(" * The following function is skipped because");
$self->pidl_both(" * it uses pipes:");
$self->pidl_both(" *");
$self->pidl_both(" * dcerpc_$fn->{NAME}_r_send()");
$self->pidl_both(" * dcerpc_$fn->{NAME}_r_recv()");
$self->pidl_both(" * dcerpc_$fn->{NAME}_r()");
$self->pidl_both(" *");
$self->pidl_both(" * dcerpc_$fn->{NAME}_send()");
$self->pidl_both(" * dcerpc_$fn->{NAME}_recv()");
$self->pidl_both(" * dcerpc_$fn->{NAME}()");
$self->pidl_both(" */");
$self->pidl_both("");
warning($fn->{ORIGINAL}, "$fn->{NAME}: dcerpc client does not support pipe yet");
return;
}
$self->ParseFunction_r_State($if, $fn, $fn->{NAME});
$self->ParseFunction_r_Send($if, $fn, $fn->{NAME});
$self->ParseFunction_r_Done($if, $fn, $fn->{NAME});
$self->ParseFunction_r_Recv($if, $fn, $fn->{NAME});
$self->ParseFunction_r_Sync($if, $fn, $fn->{NAME});
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless (grep(/out/, @{$e->{DIRECTION}}));
my $reason = "is not a pointer or array";
# TODO: make this fatal at NDR level
if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
if ($e->{LEVELS}[1]->{TYPE} eq "DATA" and
$e->{LEVELS}[1]->{DATA_TYPE} eq "string") {
$reason = "is a pointer to type 'string'";
} elsif ($e->{LEVELS}[1]->{TYPE} eq "ARRAY" and
$e->{LEVELS}[1]->{IS_ZERO_TERMINATED}) {
next;
} elsif ($e->{LEVELS}[1]->{TYPE} eq "ARRAY" and
not defined($e->{LEVELS}[1]->{SIZE_IS})) {
$reason = "is a pointer to an unsized array";
} else {
next;
}
}
if ($e->{LEVELS}[0]->{TYPE} eq "ARRAY") {
if (not defined($e->{LEVELS}[0]->{SIZE_IS})) {
$reason = "is an unsized array";
} else {
next;
}
}
$self->pidl_both("/*");
$self->pidl_both(" * The following functions are skipped because");
$self->pidl_both(" * an [out] argument $e->{NAME} $reason:");
$self->pidl_both(" *");
$self->pidl_both(" * dcerpc_$fn->{NAME}_send()");
$self->pidl_both(" * dcerpc_$fn->{NAME}_recv()");
$self->pidl_both(" * dcerpc_$fn->{NAME}()");
$self->pidl_both(" */");
$self->pidl_both("");
error($e->{ORIGINAL}, "$fn->{NAME}: [out] argument '$e->{NAME}' $reason, skip client functions");
return;
}
$self->ParseFunction_State($if, $fn, $fn->{NAME});
$self->ParseFunction_Send($if, $fn, $fn->{NAME});
$self->ParseFunction_Done($if, $fn, $fn->{NAME});
$self->ParseFunction_Recv($if, $fn, $fn->{NAME});
$self->ParseFunction_Sync($if, $fn, $fn->{NAME});
$self->pidl_hdr("");
}
my %done;
#####################################################################
# parse the interface definitions
sub ParseInterface($$)
{
my ($self, $if) = @_;
my $ifu = uc($if->{NAME});
$self->pidl_hdr("#ifndef _HEADER_RPC_$if->{NAME}");
$self->pidl_hdr("#define _HEADER_RPC_$if->{NAME}");
$self->pidl_hdr("");
if (defined $if->{PROPERTIES}->{uuid}) {
$self->pidl_hdr("extern const struct ndr_interface_table ndr_table_$if->{NAME};");
$self->pidl_hdr("");
}
$self->pidl("/* $if->{NAME} - client functions generated by pidl */");
$self->pidl("");
foreach my $fn (@{$if->{FUNCTIONS}}) {
next if defined($done{$fn->{NAME}});
next if has_property($fn, "noopnum");
next if has_property($fn, "todo");
$self->ParseFunction($if, $fn);
$done{$fn->{NAME}} = 1;
}
$self->pidl_hdr("#endif /* _HEADER_RPC_$if->{NAME} */");
}
sub Parse($$$$$$)
{
my($self,$ndr,$header,$ndr_header,$client_header) = @_;
$self->pidl("/* client functions auto-generated by pidl */");
$self->pidl("");
if (is_intree()) {
$self->pidl("#include \"includes.h\"");
} else {
$self->pidl("#ifndef _GNU_SOURCE");
$self->pidl("#define _GNU_SOURCE");
$self->pidl("#endif");
$self->pidl("#include <stdio.h>");
$self->pidl("#include <stdbool.h>");
$self->pidl("#include <stdlib.h>");
$self->pidl("#include <stdint.h>");
$self->pidl("#include <stdarg.h>");
$self->pidl("#include <string.h>");
$self->pidl("#include <core/ntstatus.h>");
}
$self->pidl("#include <tevent.h>");
$self->pidl(choose_header("lib/util/tevent_ntstatus.h", "util/tevent_ntstatus.h")."");
$self->pidl("#include \"$ndr_header\"");
$self->pidl("#include \"$client_header\"");
$self->pidl("");
$self->pidl_hdr(choose_header("librpc/rpc/dcerpc.h", "dcerpc.h")."");
$self->pidl_hdr("#include \"$header\"");
foreach my $x (@{$ndr}) {
($x->{TYPE} eq "INTERFACE") && $self->ParseInterface($x);
}
return ($self->{res},$self->{res_hdr});
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/NDR/Parser.pm | ###################################################
# Samba4 NDR parser generator for IDL structures
# Copyright [email protected] 2000-2003
# Copyright [email protected] 2001
# Copyright [email protected] 2004-2006
# released under the GNU GPL
package Parse::Pidl::Samba4::NDR::Parser;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(check_null_pointer NeededFunction NeededElement NeededType $res NeededInterface TypeFunctionName ParseElementPrint);
use strict;
use Parse::Pidl::Typelist qw(hasType getType mapTypeName typeHasBody);
use Parse::Pidl::Util qw(has_property ParseExpr ParseExprExt print_uuid unmake_str);
use Parse::Pidl::CUtil qw(get_pointer_to get_value_of get_array_element);
use Parse::Pidl::NDR qw(GetPrevLevel GetNextLevel ContainsDeferred ContainsPipe is_charset_array);
use Parse::Pidl::Samba4 qw(is_intree choose_header ArrayDynamicallyAllocated);
use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv EnvSubstituteValue GenerateStructEnv);
use Parse::Pidl qw(warning);
use vars qw($VERSION);
$VERSION = '0.01';
# list of known types
my %typefamily;
sub new($$) {
my ($class) = @_;
my $self = { res => "", res_hdr => "", deferred => [], tabs => "", defer_tabs => "" };
bless($self, $class);
}
sub get_typefamily($)
{
my $n = shift;
return $typefamily{$n};
}
sub append_prefix($$)
{
my ($e, $var_name) = @_;
my $pointers = 0;
my $arrays = 0;
foreach my $l (@{$e->{LEVELS}}) {
if ($l->{TYPE} eq "POINTER") {
$pointers++;
} elsif ($l->{TYPE} eq "ARRAY") {
$arrays++;
if (($pointers == 0) and
(not $l->{IS_FIXED}) and
(not $l->{IS_INLINE})) {
return get_value_of($var_name);
}
} elsif ($l->{TYPE} eq "DATA") {
if (Parse::Pidl::Typelist::scalar_is_reference($l->{DATA_TYPE})) {
return get_value_of($var_name) unless ($pointers or $arrays);
}
}
}
return $var_name;
}
sub has_fast_array($$)
{
my ($e,$l) = @_;
return 0 if ($l->{TYPE} ne "ARRAY");
my $nl = GetNextLevel($e,$l);
return 0 unless ($nl->{TYPE} eq "DATA");
return 0 unless (hasType($nl->{DATA_TYPE}));
my $t = getType($nl->{DATA_TYPE});
# Only uint8 and string have fast array functions at the moment
return ($t->{NAME} eq "uint8") or ($t->{NAME} eq "string");
}
####################################
# pidl() is our basic output routine
sub pidl($$)
{
my ($self, $d) = @_;
if ($d) {
$self->{res} .= $self->{tabs};
$self->{res} .= $d;
}
$self->{res} .="\n";
}
sub pidl_hdr($$) { my ($self, $d) = @_; $self->{res_hdr} .= "$d\n"; }
####################################
# defer() is like pidl(), but adds to
# a deferred buffer which is then added to the
# output buffer at the end of the structure/union/function
# This is needed to cope with code that must be pushed back
# to the end of a block of elements
sub defer_indent($) { my ($self) = @_; $self->{defer_tabs}.="\t"; }
sub defer_deindent($) { my ($self) = @_; $self->{defer_tabs}=substr($self->{defer_tabs}, 0, -1); }
sub defer($$)
{
my ($self, $d) = @_;
if ($d) {
push(@{$self->{deferred}}, $self->{defer_tabs}.$d);
}
}
########################################
# add the deferred content to the current
# output
sub add_deferred($)
{
my ($self) = @_;
$self->pidl($_) foreach (@{$self->{deferred}});
$self->{deferred} = [];
$self->{defer_tabs} = "";
}
sub indent($)
{
my ($self) = @_;
$self->{tabs} .= "\t";
}
sub deindent($)
{
my ($self) = @_;
$self->{tabs} = substr($self->{tabs}, 0, -1);
}
#####################################################################
# declare a function public or static, depending on its attributes
sub fn_declare($$$$)
{
my ($self,$type,$fn,$decl) = @_;
if (has_property($fn, "no$type")) {
$self->pidl_hdr("$decl;");
return 0;
}
if (has_property($fn, "public")) {
$self->pidl_hdr("$decl;");
$self->pidl("_PUBLIC_ $decl");
} else {
$self->pidl("static $decl");
}
return 1;
}
###################################################################
# setup any special flags for an element or structure
sub start_flags($$$)
{
my ($self, $e, $ndr) = @_;
my $flags = has_property($e, "flag");
if (defined $flags) {
$self->pidl("{");
$self->indent;
$self->pidl("uint32_t _flags_save_$e->{TYPE} = $ndr->flags;");
$self->pidl("ndr_set_flags(&$ndr->flags, $flags);");
}
}
###################################################################
# end any special flags for an element or structure
sub end_flags($$$)
{
my ($self, $e, $ndr) = @_;
my $flags = has_property($e, "flag");
if (defined $flags) {
$self->pidl("$ndr->flags = _flags_save_$e->{TYPE};");
$self->deindent;
$self->pidl("}");
}
}
#####################################################################
# parse the data of an array - push side
sub ParseArrayPushHeader($$$$$$)
{
my ($self,$e,$l,$ndr,$var_name,$env) = @_;
my $size;
my $length;
if ($l->{IS_ZERO_TERMINATED}) {
if (has_property($e, "charset")) {
$size = $length = "ndr_charset_length($var_name, CH_$e->{PROPERTIES}->{charset})";
} else {
$size = $length = "ndr_string_length($var_name, sizeof(*$var_name))";
}
if (defined($l->{SIZE_IS})) {
$size = ParseExpr($l->{SIZE_IS}, $env, $e);
}
if (defined($l->{LENGTH_IS})) {
$length = ParseExpr($l->{LENGTH_IS}, $env, $e);
}
} else {
$size = ParseExpr($l->{SIZE_IS}, $env, $e);
$length = ParseExpr($l->{LENGTH_IS}, $env, $e);
}
if ((!$l->{IS_SURROUNDING}) and $l->{IS_CONFORMANT}) {
$self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, $size));");
}
if ($l->{IS_VARYING}) {
$self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, 0));"); # array offset
$self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, $length));");
}
return $length;
}
sub check_fully_dereferenced($$)
{
my ($element, $env) = @_;
return sub ($) {
my $origvar = shift;
my $check = 0;
# Figure out the number of pointers in $ptr
my $expandedvar = $origvar;
$expandedvar =~ s/^(\**)//;
my $ptr = $1;
my $var = undef;
foreach (keys %$env) {
if ($env->{$_} eq $expandedvar) {
$var = $_;
last;
}
}
return($origvar) unless (defined($var));
my $e;
foreach (@{$element->{PARENT}->{ELEMENTS}}) {
if ($_->{NAME} eq $var) {
$e = $_;
last;
}
}
$e or die("Environment doesn't match siblings");
# See if pointer at pointer level $level
# needs to be checked.
my $nump = 0;
foreach (@{$e->{LEVELS}}) {
if ($_->{TYPE} eq "POINTER") {
$nump = $_->{POINTER_INDEX}+1;
}
}
warning($element->{ORIGINAL}, "Got pointer for `$e->{NAME}', expected fully dereferenced variable") if ($nump > length($ptr));
return ($origvar);
}
}
sub check_null_pointer($$$$)
{
my ($element, $env, $print_fn, $return) = @_;
return sub ($) {
my $expandedvar = shift;
my $check = 0;
# Figure out the number of pointers in $ptr
$expandedvar =~ s/^(\**)//;
my $ptr = $1;
my $var = undef;
foreach (keys %$env) {
if ($env->{$_} eq $expandedvar) {
$var = $_;
last;
}
}
if (defined($var)) {
my $e;
# lookup ptr in $e
foreach (@{$element->{PARENT}->{ELEMENTS}}) {
if ($_->{NAME} eq $var) {
$e = $_;
last;
}
}
$e or die("Environment doesn't match siblings");
# See if pointer at pointer level $level
# needs to be checked.
foreach my $l (@{$e->{LEVELS}}) {
if ($l->{TYPE} eq "POINTER" and
$l->{POINTER_INDEX} == length($ptr)) {
# No need to check ref pointers
$check = ($l->{POINTER_TYPE} ne "ref");
last;
}
if ($l->{TYPE} eq "DATA") {
warning($element, "too much dereferences for `$var'");
}
}
} else {
warning($element, "unknown dereferenced expression `$expandedvar'");
$check = 1;
}
$print_fn->("if ($ptr$expandedvar == NULL) $return") if $check;
}
}
sub is_deferred_switch_non_empty($)
{
# 1 if there needs to be a deferred branch in an ndr_pull/push,
# 0 otherwise.
my ($e) = @_;
my $have_default = 0;
foreach my $el (@{$e->{ELEMENTS}}) {
if ($el->{CASE} eq "default") {
$have_default = 1;
}
if ($el->{TYPE} ne "EMPTY") {
if (ContainsDeferred($el, $el->{LEVELS}[0])) {
return 1;
}
}
}
return ! $have_default;
}
sub ParseArrayPullGetSize($$$$$$)
{
my ($self,$e,$l,$ndr,$var_name,$env) = @_;
my $size;
if ($l->{IS_CONFORMANT}) {
$size = "ndr_get_array_size($ndr, " . get_pointer_to($var_name) . ")";
} elsif ($l->{IS_ZERO_TERMINATED} and $l->{SIZE_IS} == 0 and $l->{LENGTH_IS} == 0) { # Noheader arrays
$size = "ndr_get_string_size($ndr, sizeof(*$var_name))";
} else {
$size = ParseExprExt($l->{SIZE_IS}, $env, $e->{ORIGINAL},
check_null_pointer($e, $env, sub { $self->pidl(shift); },
"return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for size_is()\");"),
check_fully_dereferenced($e, $env));
}
$self->pidl("size_$e->{NAME}_$l->{LEVEL_INDEX} = $size;");
my $array_size = "size_$e->{NAME}_$l->{LEVEL_INDEX}";
if (my $range = has_property($e, "range")) {
my ($low, $high) = split(/,/, $range, 2);
if ($low < 0) {
warning(0, "$low is invalid for the range of an array size");
}
if ($low == 0) {
$self->pidl("if ($array_size > $high) {");
} else {
$self->pidl("if ($array_size < $low || $array_size > $high) {");
}
$self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_RANGE, \"value out of range\");");
$self->pidl("}");
}
return $array_size;
}
#####################################################################
# parse an array - pull side
sub ParseArrayPullGetLength($$$$$$;$)
{
my ($self,$e,$l,$ndr,$var_name,$env,$array_size) = @_;
if (not defined($array_size)) {
$array_size = $self->ParseArrayPullGetSize($e, $l, $ndr, $var_name, $env);
}
if (not $l->{IS_VARYING}) {
return $array_size;
}
my $length = "ndr_get_array_length($ndr, " . get_pointer_to($var_name) .")";
$self->pidl("length_$e->{NAME}_$l->{LEVEL_INDEX} = $length;");
my $array_length = "length_$e->{NAME}_$l->{LEVEL_INDEX}";
if (my $range = has_property($e, "range")) {
my ($low, $high) = split(/,/, $range, 2);
if ($low < 0) {
warning(0, "$low is invalid for the range of an array size");
}
if ($low == 0) {
$self->pidl("if ($array_length > $high) {");
} else {
$self->pidl("if ($array_length < $low || $array_length > $high) {");
}
$self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_RANGE, \"value out of range\");");
$self->pidl("}");
}
return $array_length;
}
#####################################################################
# parse an array - pull side
sub ParseArrayPullHeader($$$$$$)
{
my ($self,$e,$l,$ndr,$var_name,$env) = @_;
if ((!$l->{IS_SURROUNDING}) and $l->{IS_CONFORMANT}) {
$self->pidl("NDR_CHECK(ndr_pull_array_size($ndr, " . get_pointer_to($var_name) . "));");
}
if ($l->{IS_VARYING}) {
$self->pidl("NDR_CHECK(ndr_pull_array_length($ndr, " . get_pointer_to($var_name) . "));");
}
my $array_size = $self->ParseArrayPullGetSize($e, $l, $ndr, $var_name, $env);
my $array_length = $self->ParseArrayPullGetLength($e, $l, $ndr, $var_name, $env, $array_size);
if ($array_length ne $array_size) {
$self->pidl("if ($array_length > $array_size) {");
$self->indent;
$self->pidl("return ndr_pull_error($ndr, NDR_ERR_ARRAY_SIZE, \"Bad array size %u should exceed array length %u\", $array_size, $array_length);");
$self->deindent;
$self->pidl("}");
}
if ($l->{IS_CONFORMANT} and (defined($l->{SIZE_IS}) or not $l->{IS_ZERO_TERMINATED})) {
$self->defer("if ($var_name) {");
$self->defer_indent;
my $size = ParseExprExt($l->{SIZE_IS}, $env, $e->{ORIGINAL},
check_null_pointer($e, $env, sub { $self->defer(shift); },
"return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for size_is()\");"),
check_fully_dereferenced($e, $env));
$self->defer("NDR_CHECK(ndr_check_array_size($ndr, (void*)" . get_pointer_to($var_name) . ", $size));");
$self->defer_deindent;
$self->defer("}");
}
if ($l->{IS_VARYING} and (defined($l->{LENGTH_IS}) or not $l->{IS_ZERO_TERMINATED})) {
$self->defer("if ($var_name) {");
$self->defer_indent;
my $length = ParseExprExt($l->{LENGTH_IS}, $env, $e->{ORIGINAL},
check_null_pointer($e, $env, sub { $self->defer(shift); },
"return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for length_is()\");"),
check_fully_dereferenced($e, $env));
$self->defer("NDR_CHECK(ndr_check_array_length($ndr, (void*)" . get_pointer_to($var_name) . ", $length));");
$self->defer_deindent;
$self->defer("}");
}
if (ArrayDynamicallyAllocated($e,$l) and not is_charset_array($e,$l)) {
$self->AllocateArrayLevel($e,$l,$ndr,$var_name,$array_size);
}
return $array_length;
}
sub compression_alg($$)
{
my ($e, $l) = @_;
my ($alg, $clen, $dlen) = split(/,/, $l->{COMPRESSION});
return $alg;
}
sub compression_clen($$$)
{
my ($e, $l, $env) = @_;
my ($alg, $clen, $dlen) = split(/,/, $l->{COMPRESSION});
return ParseExpr($clen, $env, $e->{ORIGINAL});
}
sub compression_dlen($$$)
{
my ($e,$l,$env) = @_;
my ($alg, $clen, $dlen) = split(/,/, $l->{COMPRESSION});
return ParseExpr($dlen, $env, $e->{ORIGINAL});
}
sub ParseCompressionPushStart($$$$$)
{
my ($self,$e,$l,$ndr,$env) = @_;
my $comndr = "$ndr\_compressed";
my $alg = compression_alg($e, $l);
my $dlen = compression_dlen($e, $l, $env);
$self->pidl("{");
$self->indent;
$self->pidl("struct ndr_push *$comndr;");
$self->pidl("NDR_CHECK(ndr_push_compression_start($ndr, &$comndr, $alg, $dlen));");
return $comndr;
}
sub ParseCompressionPushEnd($$$$$)
{
my ($self,$e,$l,$ndr,$env) = @_;
my $comndr = "$ndr\_compressed";
my $alg = compression_alg($e, $l);
my $dlen = compression_dlen($e, $l, $env);
$self->pidl("NDR_CHECK(ndr_push_compression_end($ndr, $comndr, $alg, $dlen));");
$self->deindent;
$self->pidl("}");
}
sub ParseCompressionPullStart($$$$$)
{
my ($self,$e,$l,$ndr,$env) = @_;
my $comndr = "$ndr\_compressed";
my $alg = compression_alg($e, $l);
my $dlen = compression_dlen($e, $l, $env);
my $clen = compression_clen($e, $l, $env);
$self->pidl("{");
$self->indent;
$self->pidl("struct ndr_pull *$comndr;");
$self->pidl("NDR_CHECK(ndr_pull_compression_start($ndr, &$comndr, $alg, $dlen, $clen));");
return $comndr;
}
sub ParseCompressionPullEnd($$$$$)
{
my ($self,$e,$l,$ndr,$env) = @_;
my $comndr = "$ndr\_compressed";
my $alg = compression_alg($e, $l);
my $dlen = compression_dlen($e, $l, $env);
$self->pidl("NDR_CHECK(ndr_pull_compression_end($ndr, $comndr, $alg, $dlen));");
$self->deindent;
$self->pidl("}");
}
sub ParseSubcontextPushStart($$$$$)
{
my ($self,$e,$l,$ndr,$env) = @_;
my $subndr = "_ndr_$e->{NAME}";
my $subcontext_size = ParseExpr($l->{SUBCONTEXT_SIZE}, $env, $e->{ORIGINAL});
$self->pidl("{");
$self->indent;
$self->pidl("struct ndr_push *$subndr;");
$self->pidl("NDR_CHECK(ndr_push_subcontext_start($ndr, &$subndr, $l->{HEADER_SIZE}, $subcontext_size));");
if (defined $l->{COMPRESSION}) {
$subndr = $self->ParseCompressionPushStart($e, $l, $subndr, $env);
}
return $subndr;
}
sub ParseSubcontextPushEnd($$$$$)
{
my ($self,$e,$l,$ndr,$env) = @_;
my $subndr = "_ndr_$e->{NAME}";
my $subcontext_size = ParseExpr($l->{SUBCONTEXT_SIZE}, $env, $e->{ORIGINAL});
if (defined $l->{COMPRESSION}) {
$self->ParseCompressionPushEnd($e, $l, $subndr, $env);
}
$self->pidl("NDR_CHECK(ndr_push_subcontext_end($ndr, $subndr, $l->{HEADER_SIZE}, $subcontext_size));");
$self->deindent;
$self->pidl("}");
}
sub ParseSubcontextPullStart($$$$$)
{
my ($self,$e,$l,$ndr,$env) = @_;
my $subndr = "_ndr_$e->{NAME}";
my $subcontext_size = ParseExpr($l->{SUBCONTEXT_SIZE}, $env, $e->{ORIGINAL});
$self->pidl("{");
$self->indent;
$self->pidl("struct ndr_pull *$subndr;");
$self->pidl("NDR_CHECK(ndr_pull_subcontext_start($ndr, &$subndr, $l->{HEADER_SIZE}, $subcontext_size));");
if (defined $l->{COMPRESSION}) {
$subndr = $self->ParseCompressionPullStart($e, $l, $subndr, $env);
}
return $subndr;
}
sub ParseSubcontextPullEnd($$$$$)
{
my ($self,$e,$l,$ndr,$env) = @_;
my $subndr = "_ndr_$e->{NAME}";
my $subcontext_size = ParseExpr($l->{SUBCONTEXT_SIZE}, $env, $e->{ORIGINAL});
if (defined $l->{COMPRESSION}) {
$self->ParseCompressionPullEnd($e, $l, $subndr, $env);
}
$self->pidl("NDR_CHECK(ndr_pull_subcontext_end($ndr, $subndr, $l->{HEADER_SIZE}, $subcontext_size));");
$self->deindent;
$self->pidl("}");
}
sub ParseElementPushLevel
{
my ($self,$e,$l,$ndr,$var_name,$env,$primitives,$deferred) = @_;
my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
if ($l->{TYPE} eq "ARRAY" and ($l->{IS_CONFORMANT} or $l->{IS_VARYING})) {
$var_name = get_pointer_to($var_name);
}
if (defined($ndr_flags)) {
if ($l->{TYPE} eq "SUBCONTEXT") {
my $subndr = $self->ParseSubcontextPushStart($e, $l, $ndr, $env);
$self->ParseElementPushLevel($e, GetNextLevel($e, $l), $subndr, $var_name, $env, 1, 1);
$self->ParseSubcontextPushEnd($e, $l, $ndr, $env);
} elsif ($l->{TYPE} eq "POINTER") {
$self->ParsePtrPush($e, $l, $ndr, $var_name);
} elsif ($l->{TYPE} eq "ARRAY") {
my $length = $self->ParseArrayPushHeader($e, $l, $ndr, $var_name, $env);
my $nl = GetNextLevel($e, $l);
# Allow speedups for arrays of scalar types
if (is_charset_array($e,$l)) {
if ($l->{IS_TO_NULL}) {
$self->pidl("NDR_CHECK(ndr_push_charset_to_null($ndr, $ndr_flags, $var_name, $length, sizeof(" . mapTypeName($nl->{DATA_TYPE}) . "), CH_$e->{PROPERTIES}->{charset}));");
} else {
$self->pidl("NDR_CHECK(ndr_push_charset($ndr, $ndr_flags, $var_name, $length, sizeof(" . mapTypeName($nl->{DATA_TYPE}) . "), CH_$e->{PROPERTIES}->{charset}));");
}
return;
} elsif (has_fast_array($e,$l)) {
$self->pidl("NDR_CHECK(ndr_push_array_$nl->{DATA_TYPE}($ndr, $ndr_flags, $var_name, $length));");
return;
}
} elsif ($l->{TYPE} eq "SWITCH") {
$self->ParseSwitchPush($e, $l, $ndr, $var_name, $env);
} elsif ($l->{TYPE} eq "DATA") {
$self->ParseDataPush($e, $l, $ndr, $var_name, $primitives, $deferred);
} elsif ($l->{TYPE} eq "TYPEDEF") {
$typefamily{$e->{DATA}->{TYPE}}->{PUSH_FN_BODY}->($self, $e->{DATA}, $ndr, $var_name);
}
}
if ($l->{TYPE} eq "POINTER" and $l->{POINTER_TYPE} eq "ignore") {
$self->pidl("/* [ignore] '$e->{NAME}' */");
} elsif ($l->{TYPE} eq "POINTER" and $deferred) {
my $rel_var_name = $var_name;
if ($l->{POINTER_TYPE} ne "ref") {
$self->pidl("if ($var_name) {");
$self->indent;
if ($l->{POINTER_TYPE} eq "relative") {
$self->pidl("NDR_CHECK(ndr_push_relative_ptr2_start($ndr, $rel_var_name));");
}
if ($l->{POINTER_TYPE} eq "relative_short") {
$self->pidl("NDR_CHECK(ndr_push_short_relative_ptr2($ndr, $var_name));");
}
}
$var_name = get_value_of($var_name);
$self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 1, 1);
if ($l->{POINTER_TYPE} ne "ref") {
if ($l->{POINTER_TYPE} eq "relative") {
$self->pidl("NDR_CHECK(ndr_push_relative_ptr2_end($ndr, $rel_var_name));");
}
$self->deindent;
$self->pidl("}");
}
} elsif ($l->{TYPE} eq "ARRAY" and not has_fast_array($e,$l) and
not is_charset_array($e, $l)) {
my $length = ParseExpr($l->{LENGTH_IS}, $env, $e->{ORIGINAL});
my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
my $array_pointless = ($length eq "0");
if ($array_pointless) {
warning($e->{ORIGINAL}, "pointless array `$e->{NAME}' will always have size 0");
}
$var_name = get_array_element($var_name, $counter);
if ((($primitives and not $l->{IS_DEFERRED}) or ($deferred and $l->{IS_DEFERRED})) and not $array_pointless) {
$self->pidl("for ($counter = 0; $counter < ($length); $counter++) {");
$self->indent;
$self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 1, 0);
$self->deindent;
$self->pidl("}");
}
if ($deferred and ContainsDeferred($e, $l) and not $array_pointless) {
$self->pidl("for ($counter = 0; $counter < ($length); $counter++) {");
$self->indent;
$self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, 0, 1);
$self->deindent;
$self->pidl("}");
}
} elsif ($l->{TYPE} eq "SWITCH") {
$self->ParseElementPushLevel($e, GetNextLevel($e, $l), $ndr, $var_name, $env, $primitives, $deferred);
}
}
#####################################################################
# parse scalars in a structure element
sub ParseElementPush($$$$$$)
{
my ($self,$e,$ndr,$env,$primitives,$deferred) = @_;
my $subndr = undef;
my $var_name = $env->{$e->{NAME}};
if (has_property($e, "skip") or has_property($e, "skip_noinit")) {
$self->pidl("/* [skip] '$var_name' */");
return;
}
return if ContainsPipe($e, $e->{LEVELS}[0]);
return unless $primitives or ($deferred and ContainsDeferred($e, $e->{LEVELS}[0]));
# Representation type is different from transmit_as
if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
$self->pidl("{");
$self->indent;
my $transmit_name = "_transmit_$e->{NAME}";
$self->pidl(mapTypeName($e->{TYPE}) ." $transmit_name;");
$self->pidl("NDR_CHECK(ndr_$e->{REPRESENTATION_TYPE}_to_$e->{TYPE}($var_name, " . get_pointer_to($transmit_name) . "));");
$var_name = $transmit_name;
}
$var_name = append_prefix($e, $var_name);
$self->start_flags($e, $ndr);
if (defined(my $value = has_property($e, "value"))) {
$var_name = ParseExpr($value, $env, $e->{ORIGINAL});
}
$self->ParseElementPushLevel($e, $e->{LEVELS}[0], $ndr, $var_name, $env, $primitives, $deferred);
$self->end_flags($e, $ndr);
if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
$self->deindent;
$self->pidl("}");
}
}
#####################################################################
# parse a pointer in a struct element or function
sub ParsePtrPush($$$$$)
{
my ($self,$e,$l,$ndr,$var_name) = @_;
if ($l->{POINTER_TYPE} eq "ref") {
if ($l->{LEVEL_INDEX} > 0) {
$self->pidl("if ($var_name == NULL) {");
$self->indent;
$self->pidl("return ndr_push_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL [ref] pointer\");");
$self->deindent;
$self->pidl("}");
}
if ($l->{LEVEL} eq "EMBEDDED") {
$self->pidl("NDR_CHECK(ndr_push_ref_ptr(ndr)); /* $var_name */");
}
} elsif ($l->{POINTER_TYPE} eq "relative") {
$self->pidl("NDR_CHECK(ndr_push_relative_ptr1($ndr, $var_name));");
} elsif ($l->{POINTER_TYPE} eq "relative_short") {
$self->pidl("NDR_CHECK(ndr_push_short_relative_ptr1($ndr, $var_name));");
} elsif ($l->{POINTER_TYPE} eq "unique") {
$self->pidl("NDR_CHECK(ndr_push_unique_ptr($ndr, $var_name));");
} elsif ($l->{POINTER_TYPE} eq "full") {
$self->pidl("NDR_CHECK(ndr_push_full_ptr($ndr, $var_name));");
} elsif ($l->{POINTER_TYPE} eq "ignore") {
# We don't want this pointer to appear on the wire at all
$self->pidl("NDR_CHECK(ndr_push_uint3264(ndr, NDR_SCALARS, 0));");
} else {
die("Unhandled pointer type $l->{POINTER_TYPE}");
}
}
sub need_pointer_to($$$)
{
my ($e, $l, $scalar_only) = @_;
my $t;
if (ref($l->{DATA_TYPE})) {
$t = "$l->{DATA_TYPE}->{TYPE}_$l->{DATA_TYPE}->{NAME}";
} else {
$t = $l->{DATA_TYPE};
}
if (not Parse::Pidl::Typelist::is_scalar($t)) {
return 1 if $scalar_only;
}
my $arrays = 0;
foreach my $tl (@{$e->{LEVELS}}) {
last if $l == $tl;
if ($tl->{TYPE} eq "ARRAY") {
$arrays++;
}
}
if (Parse::Pidl::Typelist::scalar_is_reference($t)) {
return 1 unless $arrays;
}
return 0;
}
sub ParseDataPrint($$$$$)
{
my ($self, $e, $l, $ndr, $var_name) = @_;
if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
if (need_pointer_to($e, $l, 1)) {
$var_name = get_pointer_to($var_name);
}
$self->pidl(TypeFunctionName("ndr_print", $l->{DATA_TYPE})."($ndr, \"$e->{NAME}\", $var_name);");
} else {
$self->ParseTypePrint($l->{DATA_TYPE}, $ndr, $var_name);
}
}
#####################################################################
# print scalars in a structure element
sub ParseElementPrint($$$$$)
{
my($self, $e, $ndr, $var_name, $env) = @_;
return if (has_property($e, "noprint"));
my $cur_depth = 0;
my $ignore_depth = 0xFFFF;
$self->start_flags($e, $ndr);
if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
$self->pidl("ndr_print_$e->{REPRESENTATION_TYPE}($ndr, \"$e->{NAME}\", $var_name);");
$self->end_flags($e, $ndr);
return;
}
$var_name = append_prefix($e, $var_name);
if (defined(my $value = has_property($e, "value"))) {
$var_name = "($ndr->flags & LIBNDR_PRINT_SET_VALUES)?" . ParseExpr($value,$env, $e->{ORIGINAL}) . ":$var_name";
}
foreach my $l (@{$e->{LEVELS}}) {
$cur_depth += 1;
if ($cur_depth > $ignore_depth) {
next;
}
if ($l->{TYPE} eq "POINTER") {
$self->pidl("ndr_print_ptr($ndr, \"$e->{NAME}\", $var_name);");
if ($l->{POINTER_TYPE} eq "ignore") {
$self->pidl("/* [ignore] '$e->{NAME}' */");
$ignore_depth = $cur_depth;
last;
}
$self->pidl("$ndr->depth++;");
if ($l->{POINTER_TYPE} ne "ref") {
$self->pidl("if ($var_name) {");
$self->indent;
}
$var_name = get_value_of($var_name);
} elsif ($l->{TYPE} eq "ARRAY") {
my $length;
if ($l->{IS_CONFORMANT} or $l->{IS_VARYING}) {
$var_name = get_pointer_to($var_name);
}
if ($l->{IS_ZERO_TERMINATED} and not defined($l->{LENGTH_IS})) {
$length = "ndr_string_length($var_name, sizeof(*$var_name))";
} else {
$length = ParseExprExt($l->{LENGTH_IS}, $env, $e->{ORIGINAL},
check_null_pointer($e, $env, sub { $self->pidl(shift); }, "return;"), check_fully_dereferenced($e, $env));
}
if (is_charset_array($e,$l)) {
$self->pidl("ndr_print_string($ndr, \"$e->{NAME}\", $var_name);");
last;
} elsif (has_fast_array($e, $l)) {
my $nl = GetNextLevel($e, $l);
$self->pidl("ndr_print_array_$nl->{DATA_TYPE}($ndr, \"$e->{NAME}\", $var_name, $length);");
last;
} else {
my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
$self->pidl("$ndr->print($ndr, \"\%s: ARRAY(\%d)\", \"$e->{NAME}\", (int)$length);");
$self->pidl("$ndr->depth++;");
$self->pidl("for ($counter = 0; $counter < ($length); $counter++) {");
$self->indent;
$var_name = get_array_element($var_name, $counter);
}
} elsif ($l->{TYPE} eq "DATA") {
$self->ParseDataPrint($e, $l, $ndr, $var_name);
} elsif ($l->{TYPE} eq "SWITCH") {
my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL},
check_null_pointer($e, $env, sub { $self->pidl(shift); }, "return;"), check_fully_dereferenced($e, $env));
$self->pidl("ndr_print_set_switch_value($ndr, " . get_pointer_to($var_name) . ", $switch_var);");
}
}
foreach my $l (reverse @{$e->{LEVELS}}) {
$cur_depth -= 1;
if ($cur_depth > $ignore_depth) {
next;
}
if ($l->{TYPE} eq "POINTER") {
if ($l->{POINTER_TYPE} eq "ignore") {
next;
}
if ($l->{POINTER_TYPE} ne "ref") {
$self->deindent;
$self->pidl("}");
}
$self->pidl("$ndr->depth--;");
} elsif (($l->{TYPE} eq "ARRAY")
and not is_charset_array($e,$l)
and not has_fast_array($e,$l)) {
$self->deindent;
$self->pidl("}");
$self->pidl("$ndr->depth--;");
}
}
$self->end_flags($e, $ndr);
}
#####################################################################
# parse scalars in a structure element - pull size
sub ParseSwitchPull($$$$$$)
{
my($self,$e,$l,$ndr,$var_name,$env) = @_;
my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL},
check_null_pointer($e, $env, sub { $self->pidl(shift); },
"return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for switch_is()\");"),
check_fully_dereferenced($e, $env));
$var_name = get_pointer_to($var_name);
$self->pidl("NDR_CHECK(ndr_pull_set_switch_value($ndr, $var_name, $switch_var));");
}
#####################################################################
# push switch element
sub ParseSwitchPush($$$$$$)
{
my($self,$e,$l,$ndr,$var_name,$env) = @_;
my $switch_var = ParseExprExt($l->{SWITCH_IS}, $env, $e->{ORIGINAL},
check_null_pointer($e, $env, sub { $self->pidl(shift); },
"return ndr_push_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for switch_is()\");"),
check_fully_dereferenced($e, $env));
$var_name = get_pointer_to($var_name);
$self->pidl("NDR_CHECK(ndr_push_set_switch_value($ndr, $var_name, $switch_var));");
}
sub ParseDataPull($$$$$$$)
{
my ($self,$e,$l,$ndr,$var_name,$primitives,$deferred) = @_;
if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
if (need_pointer_to($e, $l, 0)) {
$var_name = get_pointer_to($var_name);
}
$var_name = get_pointer_to($var_name);
$self->pidl("NDR_CHECK(".TypeFunctionName("ndr_pull", $l->{DATA_TYPE})."($ndr, $ndr_flags, $var_name));");
my $pl = GetPrevLevel($e, $l);
my $range = has_property($e, "range");
if ($range and $pl->{TYPE} ne "ARRAY") {
$var_name = get_value_of($var_name);
my $signed = Parse::Pidl::Typelist::is_signed($l->{DATA_TYPE});
my ($low, $high) = split(/,/, $range, 2);
if ($low < 0 and not $signed) {
warning(0, "$low is invalid for the range of an unsigned type");
}
if ($low == 0 and not $signed) {
$self->pidl("if ($var_name > $high) {");
} else {
$self->pidl("if ($var_name < $low || $var_name > $high) {");
}
$self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_RANGE, \"value out of range\");");
$self->pidl("}");
}
} else {
$self->ParseTypePull($l->{DATA_TYPE}, $ndr, $var_name, $primitives, $deferred);
}
}
sub ParseDataPush($$$$$$$)
{
my ($self,$e,$l,$ndr,$var_name,$primitives,$deferred) = @_;
if (not ref($l->{DATA_TYPE}) or defined($l->{DATA_TYPE}->{NAME})) {
my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
# strings are passed by value rather than reference
if (need_pointer_to($e, $l, 1)) {
$var_name = get_pointer_to($var_name);
}
$self->pidl("NDR_CHECK(".TypeFunctionName("ndr_push", $l->{DATA_TYPE})."($ndr, $ndr_flags, $var_name));");
} else {
$self->ParseTypePush($l->{DATA_TYPE}, $ndr, $var_name, $primitives, $deferred);
}
}
sub CalcNdrFlags($$$)
{
my ($l,$primitives,$deferred) = @_;
my $scalars = 0;
my $buffers = 0;
# Add NDR_SCALARS if this one is deferred
# and deferreds may be pushed
$scalars = 1 if ($l->{IS_DEFERRED} and $deferred);
# Add NDR_SCALARS if this one is not deferred and
# primitives may be pushed
$scalars = 1 if (!$l->{IS_DEFERRED} and $primitives);
# Add NDR_BUFFERS if this one contains deferred stuff
# and deferreds may be pushed
$buffers = 1 if ($l->{CONTAINS_DEFERRED} and $deferred);
return "NDR_SCALARS|NDR_BUFFERS" if ($scalars and $buffers);
return "NDR_SCALARS" if ($scalars);
return "NDR_BUFFERS" if ($buffers);
return undef;
}
sub ParseMemCtxPullFlags($$$$)
{
my ($self, $e, $l) = @_;
return undef unless ($l->{TYPE} eq "POINTER" or $l->{TYPE} eq "ARRAY");
return undef if (($l->{TYPE} eq "POINTER") and ($l->{POINTER_TYPE} eq "ignore"));
return undef unless ($l->{TYPE} ne "ARRAY" or ArrayDynamicallyAllocated($e,$l));
return undef if has_fast_array($e, $l);
return undef if is_charset_array($e, $l);
my $mem_flags = "0";
if (($l->{TYPE} eq "POINTER") and ($l->{POINTER_TYPE} eq "ref")) {
my $nl = GetNextLevel($e, $l);
return undef if ($nl->{TYPE} eq "PIPE");
return undef if ($nl->{TYPE} eq "ARRAY");
return undef if (($nl->{TYPE} eq "DATA") and ($nl->{DATA_TYPE} eq "string"));
if ($l->{LEVEL} eq "TOP") {
$mem_flags = "LIBNDR_FLAG_REF_ALLOC";
}
}
return $mem_flags;
}
sub ParseMemCtxPullStart($$$$$)
{
my ($self, $e, $l, $ndr, $ptr_name) = @_;
my $mem_r_ctx = "_mem_save_$e->{NAME}_$l->{LEVEL_INDEX}";
my $mem_c_ctx = $ptr_name;
my $mem_c_flags = $self->ParseMemCtxPullFlags($e, $l);
return unless defined($mem_c_flags);
$self->pidl("$mem_r_ctx = NDR_PULL_GET_MEM_CTX($ndr);");
$self->pidl("NDR_PULL_SET_MEM_CTX($ndr, $mem_c_ctx, $mem_c_flags);");
}
sub ParseMemCtxPullEnd($$$$)
{
my ($self, $e, $l, $ndr) = @_;
my $mem_r_ctx = "_mem_save_$e->{NAME}_$l->{LEVEL_INDEX}";
my $mem_r_flags = $self->ParseMemCtxPullFlags($e, $l);
return unless defined($mem_r_flags);
$self->pidl("NDR_PULL_SET_MEM_CTX($ndr, $mem_r_ctx, $mem_r_flags);");
}
sub CheckStringTerminator($$$$$)
{
my ($self,$ndr,$e,$l,$length) = @_;
my $nl = GetNextLevel($e, $l);
# Make sure last element is zero!
$self->pidl("NDR_CHECK(ndr_check_string_terminator($ndr, $length, sizeof($nl->{DATA_TYPE}_t)));");
}
sub ParseElementPullLevel
{
my($self,$e,$l,$ndr,$var_name,$env,$primitives,$deferred) = @_;
my $ndr_flags = CalcNdrFlags($l, $primitives, $deferred);
my $array_length = undef;
if (has_property($e, "skip") or has_property($e, "skip_noinit")) {
$self->pidl("/* [skip] '$var_name' */");
if (not has_property($e, "skip_noinit")) {
$self->pidl("ZERO_STRUCT($var_name);");
}
return;
}
if ($l->{TYPE} eq "ARRAY" and ($l->{IS_VARYING} or $l->{IS_CONFORMANT})) {
$var_name = get_pointer_to($var_name);
}
# Only pull something if there's actually something to be pulled
if (defined($ndr_flags)) {
if ($l->{TYPE} eq "SUBCONTEXT") {
my $subndr = $self->ParseSubcontextPullStart($e, $l, $ndr, $env);
$self->ParseElementPullLevel($e, GetNextLevel($e,$l), $subndr, $var_name, $env, 1, 1);
$self->ParseSubcontextPullEnd($e, $l, $ndr, $env);
} elsif ($l->{TYPE} eq "ARRAY") {
my $length = $self->ParseArrayPullHeader($e, $l, $ndr, $var_name, $env);
$array_length = $length;
my $nl = GetNextLevel($e, $l);
if (is_charset_array($e,$l)) {
if ($l->{IS_ZERO_TERMINATED}) {
$self->CheckStringTerminator($ndr, $e, $l, $length);
}
if ($l->{IS_TO_NULL}) {
$self->pidl("NDR_CHECK(ndr_pull_charset_to_null($ndr, $ndr_flags, ".get_pointer_to($var_name).", $length, sizeof(" . mapTypeName($nl->{DATA_TYPE}) . "), CH_$e->{PROPERTIES}->{charset}));");
} else {
$self->pidl("NDR_CHECK(ndr_pull_charset($ndr, $ndr_flags, ".get_pointer_to($var_name).", $length, sizeof(" . mapTypeName($nl->{DATA_TYPE}) . "), CH_$e->{PROPERTIES}->{charset}));");
}
return;
} elsif (has_fast_array($e, $l)) {
if ($l->{IS_ZERO_TERMINATED}) {
$self->CheckStringTerminator($ndr,$e,$l,$length);
}
$self->pidl("NDR_CHECK(ndr_pull_array_$nl->{DATA_TYPE}($ndr, $ndr_flags, $var_name, $length));");
return;
}
} elsif ($l->{TYPE} eq "POINTER") {
$self->ParsePtrPull($e, $l, $ndr, $var_name);
} elsif ($l->{TYPE} eq "SWITCH") {
$self->ParseSwitchPull($e, $l, $ndr, $var_name, $env);
} elsif ($l->{TYPE} eq "DATA") {
$self->ParseDataPull($e, $l, $ndr, $var_name, $primitives, $deferred);
} elsif ($l->{TYPE} eq "TYPEDEF") {
$typefamily{$e->{DATA}->{TYPE}}->{PULL_FN_BODY}->($self, $e->{DATA}, $ndr, $var_name);
}
}
# add additional constructions
if ($l->{TYPE} eq "POINTER" and $l->{POINTER_TYPE} eq "ignore") {
$self->pidl("/* [ignore] '$e->{NAME}' */");
} elsif ($l->{TYPE} eq "POINTER" and $deferred) {
if ($l->{POINTER_TYPE} ne "ref") {
$self->pidl("if ($var_name) {");
$self->indent;
if ($l->{POINTER_TYPE} eq "relative" or $l->{POINTER_TYPE} eq "relative_short") {
$self->pidl("uint32_t _relative_save_offset;");
$self->pidl("_relative_save_offset = $ndr->offset;");
$self->pidl("NDR_CHECK(ndr_pull_relative_ptr2($ndr, $var_name));");
}
}
$self->ParseMemCtxPullStart($e, $l, $ndr, $var_name);
$var_name = get_value_of($var_name);
$self->ParseElementPullLevel($e, GetNextLevel($e,$l), $ndr, $var_name, $env, 1, 1);
$self->ParseMemCtxPullEnd($e, $l, $ndr);
if ($l->{POINTER_TYPE} ne "ref") {
if ($l->{POINTER_TYPE} eq "relative" or $l->{POINTER_TYPE} eq "relative_short") {
$self->pidl("if ($ndr->offset > $ndr->relative_highest_offset) {");
$self->indent;
$self->pidl("$ndr->relative_highest_offset = $ndr->offset;");
$self->deindent;
$self->pidl("}");
$self->pidl("$ndr->offset = _relative_save_offset;");
}
$self->deindent;
$self->pidl("}");
}
} elsif ($l->{TYPE} eq "ARRAY" and
not has_fast_array($e,$l) and not is_charset_array($e, $l)) {
my $length = $array_length;
my $counter = "cntr_$e->{NAME}_$l->{LEVEL_INDEX}";
my $array_name = $var_name;
if (not defined($length)) {
$length = $self->ParseArrayPullGetLength($e, $l, $ndr, $var_name, $env);
}
$var_name = get_array_element($var_name, $counter);
$self->ParseMemCtxPullStart($e, $l, $ndr, $array_name);
if (($primitives and not $l->{IS_DEFERRED}) or ($deferred and $l->{IS_DEFERRED})) {
my $nl = GetNextLevel($e,$l);
if ($l->{IS_ZERO_TERMINATED}) {
$self->CheckStringTerminator($ndr,$e,$l,$length);
}
$self->pidl("for ($counter = 0; $counter < ($length); $counter++) {");
$self->indent;
$self->ParseElementPullLevel($e, $nl, $ndr, $var_name, $env, 1, 0);
$self->deindent;
$self->pidl("}");
}
if ($deferred and ContainsDeferred($e, $l)) {
$self->pidl("for ($counter = 0; $counter < ($length); $counter++) {");
$self->indent;
$self->ParseElementPullLevel($e,GetNextLevel($e,$l), $ndr, $var_name, $env, 0, 1);
$self->deindent;
$self->pidl("}");
}
$self->ParseMemCtxPullEnd($e, $l, $ndr);
} elsif ($l->{TYPE} eq "SWITCH") {
$self->ParseElementPullLevel($e, GetNextLevel($e,$l), $ndr, $var_name, $env, $primitives, $deferred);
}
}
#####################################################################
# parse scalars in a structure element - pull size
sub ParseElementPull($$$$$$)
{
my($self,$e,$ndr,$env,$primitives,$deferred) = @_;
my $var_name = $env->{$e->{NAME}};
my $represent_name;
my $transmit_name;
return if ContainsPipe($e, $e->{LEVELS}[0]);
return unless $primitives or ($deferred and ContainsDeferred($e, $e->{LEVELS}[0]));
if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
$self->pidl("{");
$self->indent;
$represent_name = $var_name;
$transmit_name = "_transmit_$e->{NAME}";
$var_name = $transmit_name;
$self->pidl(mapTypeName($e->{TYPE})." $var_name;");
}
$var_name = append_prefix($e, $var_name);
$self->start_flags($e, $ndr);
$self->ParseElementPullLevel($e,$e->{LEVELS}[0],$ndr,$var_name,$env,$primitives,$deferred);
$self->end_flags($e, $ndr);
# Representation type is different from transmit_as
if ($e->{REPRESENTATION_TYPE} ne $e->{TYPE}) {
$self->pidl("NDR_CHECK(ndr_$e->{TYPE}_to_$e->{REPRESENTATION_TYPE}($transmit_name, ".get_pointer_to($represent_name)."));");
$self->deindent;
$self->pidl("}");
}
}
#####################################################################
# parse a pointer in a struct element or function
sub ParsePtrPull($$$$$)
{
my($self, $e,$l,$ndr,$var_name) = @_;
my $nl = GetNextLevel($e, $l);
my $next_is_array = ($nl->{TYPE} eq "ARRAY");
my $next_is_string = (($nl->{TYPE} eq "DATA") and
($nl->{DATA_TYPE} eq "string"));
if ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "TOP") {
if (!$next_is_array and !$next_is_string) {
$self->pidl("if ($ndr->flags & LIBNDR_FLAG_REF_ALLOC) {");
$self->pidl("\tNDR_PULL_ALLOC($ndr, $var_name);");
$self->pidl("}");
}
return;
} elsif ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "EMBEDDED") {
$self->pidl("NDR_CHECK(ndr_pull_ref_ptr($ndr, &_ptr_$e->{NAME}));");
} elsif (($l->{POINTER_TYPE} eq "unique") or
($l->{POINTER_TYPE} eq "relative") or
($l->{POINTER_TYPE} eq "full")) {
$self->pidl("NDR_CHECK(ndr_pull_generic_ptr($ndr, &_ptr_$e->{NAME}));");
} elsif ($l->{POINTER_TYPE} eq "relative_short") {
$self->pidl("NDR_CHECK(ndr_pull_relative_ptr_short($ndr, &_ptr_$e->{NAME}));");
} elsif ($l->{POINTER_TYPE} eq "ignore") {
#We want to consume the pointer bytes, but ignore the pointer value
$self->pidl("NDR_CHECK(ndr_pull_uint3264(ndr, NDR_SCALARS, &_ptr_$e->{NAME}));");
$self->pidl("_ptr_$e->{NAME} = 0;");
} else {
die("Unhandled pointer type $l->{POINTER_TYPE}");
}
$self->pidl("if (_ptr_$e->{NAME}) {");
$self->indent;
if ($l->{POINTER_TYPE} eq "ignore") {
# Don't do anything, we don't want to do the
# allocation, as we forced it to NULL just above, and
# we may not know the declared type anyway.
} else {
# Don't do this for arrays, they're allocated at the actual level
# of the array
unless ($next_is_array or $next_is_string) {
$self->pidl("NDR_PULL_ALLOC($ndr, $var_name);");
} else {
# FIXME: Yes, this is nasty.
# We allocate an array twice
# - once just to indicate that it's there,
# - then the real allocation...
$self->pidl("NDR_PULL_ALLOC($ndr, $var_name);");
}
}
#$self->pidl("memset($var_name, 0, sizeof($var_name));");
if ($l->{POINTER_TYPE} eq "relative" or $l->{POINTER_TYPE} eq "relative_short") {
$self->pidl("NDR_CHECK(ndr_pull_relative_ptr1($ndr, $var_name, _ptr_$e->{NAME}));");
}
$self->deindent;
$self->pidl("} else {");
$self->pidl("\t$var_name = NULL;");
$self->pidl("}");
}
sub CheckRefPtrs($$$$)
{
my ($self,$e,$ndr,$env) = @_;
return if ContainsPipe($e, $e->{LEVELS}[0]);
return if ($e->{LEVELS}[0]->{TYPE} ne "POINTER");
return if ($e->{LEVELS}[0]->{POINTER_TYPE} ne "ref");
my $var_name = $env->{$e->{NAME}};
$var_name = append_prefix($e, $var_name);
$self->pidl("if ($var_name == NULL) {");
$self->indent;
$self->pidl("return ndr_push_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL [ref] pointer\");");
$self->deindent;
$self->pidl("}");
}
sub ParseStructPushPrimitives($$$$$)
{
my ($self, $struct, $ndr, $varname, $env) = @_;
$self->CheckRefPtrs($_, $ndr, $env) foreach (@{$struct->{ELEMENTS}});
# see if the structure contains a conformant array. If it
# does, then it must be the last element of the structure, and
# we need to push the conformant length early, as it fits on
# the wire before the structure (and even before the structure
# alignment)
if (defined($struct->{SURROUNDING_ELEMENT})) {
my $e = $struct->{SURROUNDING_ELEMENT};
if (defined($e->{LEVELS}[0]) and
$e->{LEVELS}[0]->{TYPE} eq "ARRAY") {
my $size;
if ($e->{LEVELS}[0]->{IS_ZERO_TERMINATED}) {
if (has_property($e, "charset")) {
$size = "ndr_charset_length($varname->$e->{NAME}, CH_$e->{PROPERTIES}->{charset})";
} else {
$size = "ndr_string_length($varname->$e->{NAME}, sizeof(*$varname->$e->{NAME}))";
}
if (defined($e->{LEVELS}[0]->{SIZE_IS})) {
$size = ParseExpr($e->{LEVELS}[0]->{SIZE_IS}, $env, $e->{ORIGINAL});
}
} else {
$size = ParseExpr($e->{LEVELS}[0]->{SIZE_IS}, $env, $e->{ORIGINAL});
}
$self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, $size));");
} else {
$self->pidl("NDR_CHECK(ndr_push_uint3264($ndr, NDR_SCALARS, ndr_string_array_size($ndr, $varname->$e->{NAME})));");
}
}
$self->pidl("NDR_CHECK(ndr_push_align($ndr, $struct->{ALIGN}));");
if (defined($struct->{PROPERTIES}{relative_base})) {
# set the current offset as base for relative pointers
# and store it based on the toplevel struct/union
$self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
}
$self->ParseElementPush($_, $ndr, $env, 1, 0) foreach (@{$struct->{ELEMENTS}});
$self->pidl("NDR_CHECK(ndr_push_trailer_align($ndr, $struct->{ALIGN}));");
}
sub ParseStructPushDeferred($$$$)
{
my ($self, $struct, $ndr, $varname, $env) = @_;
if (defined($struct->{PROPERTIES}{relative_base})) {
# retrieve the current offset as base for relative pointers
# based on the toplevel struct/union
$self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset2($ndr, $varname));");
}
$self->ParseElementPush($_, $ndr, $env, 0, 1) foreach (@{$struct->{ELEMENTS}});
}
#####################################################################
# parse a struct
sub ParseStructPush($$$$)
{
my ($self, $struct, $ndr, $varname) = @_;
return unless defined($struct->{ELEMENTS});
my $env = GenerateStructEnv($struct, $varname);
EnvSubstituteValue($env, $struct);
$self->DeclareArrayVariablesNoZero($_, $env) foreach (@{$struct->{ELEMENTS}});
$self->start_flags($struct, $ndr);
$self->pidl("NDR_PUSH_CHECK_FLAGS(ndr, ndr_flags);");
$self->pidl("if (ndr_flags & NDR_SCALARS) {");
$self->indent;
$self->ParseStructPushPrimitives($struct, $ndr, $varname, $env);
$self->deindent;
$self->pidl("}");
$self->pidl("if (ndr_flags & NDR_BUFFERS) {");
$self->indent;
$self->ParseStructPushDeferred($struct, $ndr, $varname, $env);
$self->deindent;
$self->pidl("}");
$self->end_flags($struct, $ndr);
}
#####################################################################
# generate a push function for an enum
sub ParseEnumPush($$$$)
{
my($self,$enum,$ndr,$varname) = @_;
my($type_fn) = $enum->{BASE_TYPE};
$self->start_flags($enum, $ndr);
$self->pidl("NDR_CHECK(ndr_push_enum_$type_fn($ndr, NDR_SCALARS, $varname));");
$self->end_flags($enum, $ndr);
}
#####################################################################
# generate a pull function for an enum
sub ParseEnumPull($$$$)
{
my($self,$enum,$ndr,$varname) = @_;
my($type_fn) = $enum->{BASE_TYPE};
my($type_v_decl) = mapTypeName($type_fn);
$self->pidl("$type_v_decl v;");
$self->start_flags($enum, $ndr);
$self->pidl("NDR_CHECK(ndr_pull_enum_$type_fn($ndr, NDR_SCALARS, &v));");
$self->pidl("*$varname = v;");
$self->end_flags($enum, $ndr);
}
#####################################################################
# generate a print function for an enum
sub ParseEnumPrint($$$$$)
{
my($self,$enum,$ndr,$name,$varname) = @_;
$self->pidl("const char *val = NULL;");
$self->pidl("");
$self->start_flags($enum, $ndr);
$self->pidl("switch ($varname) {");
$self->indent;
my $els = \@{$enum->{ELEMENTS}};
foreach my $i (0 .. $#{$els}) {
my $e = ${$els}[$i];
chomp $e;
if ($e =~ /^(.*)=/) {
$e = $1;
}
$self->pidl("case $e: val = \"$e\"; break;");
}
$self->deindent;
$self->pidl("}");
$self->pidl("ndr_print_enum($ndr, name, \"$enum->{TYPE}\", val, $varname);");
$self->end_flags($enum, $ndr);
}
sub DeclEnum($$$$)
{
my ($e,$t,$name,$varname) = @_;
return "enum $name " .
($t eq "pull"?"*":"") . $varname;
}
$typefamily{ENUM} = {
DECL => \&DeclEnum,
PUSH_FN_BODY => \&ParseEnumPush,
PULL_FN_BODY => \&ParseEnumPull,
PRINT_FN_BODY => \&ParseEnumPrint,
};
#####################################################################
# generate a push function for a bitmap
sub ParseBitmapPush($$$$)
{
my($self,$bitmap,$ndr,$varname) = @_;
my($type_fn) = $bitmap->{BASE_TYPE};
$self->start_flags($bitmap, $ndr);
$self->pidl("NDR_CHECK(ndr_push_$type_fn($ndr, NDR_SCALARS, $varname));");
$self->end_flags($bitmap, $ndr);
}
#####################################################################
# generate a pull function for an bitmap
sub ParseBitmapPull($$$$)
{
my($self,$bitmap,$ndr,$varname) = @_;
my $type_fn = $bitmap->{BASE_TYPE};
my($type_decl) = mapTypeName($bitmap->{BASE_TYPE});
$self->pidl("$type_decl v;");
$self->start_flags($bitmap, $ndr);
$self->pidl("NDR_CHECK(ndr_pull_$type_fn($ndr, NDR_SCALARS, &v));");
$self->pidl("*$varname = v;");
$self->end_flags($bitmap, $ndr);
}
#####################################################################
# generate a print function for an bitmap
sub ParseBitmapPrintElement($$$$$$)
{
my($self,$e,$bitmap,$ndr,$name,$varname) = @_;
my($type_decl) = mapTypeName($bitmap->{BASE_TYPE});
my($type_fn) = $bitmap->{BASE_TYPE};
my($flag);
if ($e =~ /^(\w+) .*$/) {
$flag = "$1";
} else {
die "Bitmap: \"$name\" invalid Flag: \"$e\"";
}
$self->pidl("ndr_print_bitmap_flag($ndr, sizeof($type_decl), \"$flag\", $flag, $varname);");
}
#####################################################################
# generate a print function for an bitmap
sub ParseBitmapPrint($$$$$)
{
my($self,$bitmap,$ndr,$name,$varname) = @_;
my($type_decl) = mapTypeName($bitmap->{TYPE});
my($type_fn) = $bitmap->{BASE_TYPE};
$self->start_flags($bitmap, $ndr);
$self->pidl("ndr_print_$type_fn($ndr, name, $varname);");
$self->pidl("$ndr->depth++;");
foreach my $e (@{$bitmap->{ELEMENTS}}) {
$self->ParseBitmapPrintElement($e, $bitmap, $ndr, $name, $varname);
}
$self->pidl("$ndr->depth--;");
$self->end_flags($bitmap, $ndr);
}
sub DeclBitmap($$$$)
{
my ($e,$t,$name,$varname) = @_;
return mapTypeName(Parse::Pidl::Typelist::bitmap_type_fn($e)) .
($t eq "pull"?" *":" ") . $varname;
}
$typefamily{BITMAP} = {
DECL => \&DeclBitmap,
PUSH_FN_BODY => \&ParseBitmapPush,
PULL_FN_BODY => \&ParseBitmapPull,
PRINT_FN_BODY => \&ParseBitmapPrint,
};
#####################################################################
# generate a struct print function
sub ParseStructPrint($$$$$)
{
my($self,$struct,$ndr,$name,$varname) = @_;
return unless defined $struct->{ELEMENTS};
my $env = GenerateStructEnv($struct, $varname);
$self->DeclareArrayVariables($_) foreach (@{$struct->{ELEMENTS}});
$self->pidl("ndr_print_struct($ndr, name, \"$name\");");
$self->pidl("if (r == NULL) { ndr_print_null($ndr); return; }");
$self->start_flags($struct, $ndr);
$self->pidl("$ndr->depth++;");
$self->ParseElementPrint($_, $ndr, $env->{$_->{NAME}}, $env)
foreach (@{$struct->{ELEMENTS}});
$self->pidl("$ndr->depth--;");
$self->end_flags($struct, $ndr);
}
sub DeclarePtrVariables($$)
{
my ($self,$e) = @_;
if (has_property($e, "skip") or has_property($e, "skip_noinit")) {
return;
}
foreach my $l (@{$e->{LEVELS}}) {
my $size = 32;
if ($l->{TYPE} eq "POINTER" and
not ($l->{POINTER_TYPE} eq "ref" and $l->{LEVEL} eq "TOP")) {
if ($l->{POINTER_TYPE} eq "relative_short") {
$size = 16;
}
$self->pidl("uint${size}_t _ptr_$e->{NAME};");
last;
}
}
}
sub DeclareArrayVariables($$;$)
{
my ($self,$e,$pull) = @_;
if (has_property($e, "skip") or has_property($e, "skip_noinit")) {
return;
}
foreach my $l (@{$e->{LEVELS}}) {
next if ($l->{TYPE} ne "ARRAY");
if (defined($pull)) {
$self->pidl("uint32_t size_$e->{NAME}_$l->{LEVEL_INDEX} = 0;");
if ($l->{IS_VARYING}) {
$self->pidl("uint32_t length_$e->{NAME}_$l->{LEVEL_INDEX} = 0;");
}
}
next if has_fast_array($e,$l);
next if is_charset_array($e,$l);
$self->pidl("uint32_t cntr_$e->{NAME}_$l->{LEVEL_INDEX};");
}
}
sub DeclareArrayVariablesNoZero($$$)
{
my ($self,$e,$env) = @_;
if (has_property($e, "skip") or has_property($e, "skip_noinit")) {
return;
}
foreach my $l (@{$e->{LEVELS}}) {
next if ($l->{TYPE} ne "ARRAY");
next if has_fast_array($e,$l);
next if is_charset_array($e,$l);
my $length = ParseExpr($l->{LENGTH_IS}, $env, $e->{ORIGINAL});
if ($length eq "0") {
warning($e->{ORIGINAL}, "pointless array cntr: 'cntr_$e->{NAME}_$l->{LEVEL_INDEX}': length=$length");
} else {
$self->pidl("uint32_t cntr_$e->{NAME}_$l->{LEVEL_INDEX};");
}
}
}
sub DeclareMemCtxVariables($$)
{
my ($self,$e) = @_;
if (has_property($e, "skip") or has_property($e, "skip_noinit")) {
return;
}
foreach my $l (@{$e->{LEVELS}}) {
my $mem_flags = $self->ParseMemCtxPullFlags($e, $l);
if (($l->{TYPE} eq "POINTER") and ($l->{POINTER_TYPE} eq "ignore")) {
last;
}
if (defined($mem_flags)) {
$self->pidl("TALLOC_CTX *_mem_save_$e->{NAME}_$l->{LEVEL_INDEX} = NULL;");
}
}
}
sub ParseStructPullPrimitives($$$$$)
{
my($self,$struct,$ndr,$varname,$env) = @_;
if (defined $struct->{SURROUNDING_ELEMENT}) {
$self->pidl("NDR_CHECK(ndr_pull_array_size($ndr, &$varname->$struct->{SURROUNDING_ELEMENT}->{NAME}));");
}
$self->pidl("NDR_CHECK(ndr_pull_align($ndr, $struct->{ALIGN}));");
if (defined($struct->{PROPERTIES}{relative_base})) {
# set the current offset as base for relative pointers
# and store it based on the toplevel struct/union
$self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
}
$self->ParseElementPull($_, $ndr, $env, 1, 0) foreach (@{$struct->{ELEMENTS}});
$self->add_deferred();
$self->pidl("NDR_CHECK(ndr_pull_trailer_align($ndr, $struct->{ALIGN}));");
}
sub ParseStructPullDeferred($$$$$)
{
my ($self,$struct,$ndr,$varname,$env) = @_;
if (defined($struct->{PROPERTIES}{relative_base})) {
# retrieve the current offset as base for relative pointers
# based on the toplevel struct/union
$self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset2($ndr, $varname));");
}
foreach my $e (@{$struct->{ELEMENTS}}) {
$self->ParseElementPull($e, $ndr, $env, 0, 1);
}
$self->add_deferred();
}
#####################################################################
# parse a struct - pull side
sub ParseStructPull($$$$)
{
my($self,$struct,$ndr,$varname) = @_;
return unless defined $struct->{ELEMENTS};
# declare any internal pointers we need
foreach my $e (@{$struct->{ELEMENTS}}) {
$self->DeclarePtrVariables($e);
$self->DeclareArrayVariables($e, "pull");
$self->DeclareMemCtxVariables($e);
}
$self->start_flags($struct, $ndr);
my $env = GenerateStructEnv($struct, $varname);
$self->pidl("NDR_PULL_CHECK_FLAGS(ndr, ndr_flags);");
$self->pidl("if (ndr_flags & NDR_SCALARS) {");
$self->indent;
$self->ParseStructPullPrimitives($struct,$ndr,$varname,$env);
$self->deindent;
$self->pidl("}");
$self->pidl("if (ndr_flags & NDR_BUFFERS) {");
$self->indent;
$self->ParseStructPullDeferred($struct,$ndr,$varname,$env);
$self->deindent;
$self->pidl("}");
$self->end_flags($struct, $ndr);
}
#####################################################################
# calculate size of ndr struct
sub ParseStructNdrSize($$$$)
{
my ($self,$t, $name, $varname) = @_;
my $sizevar;
if (my $flags = has_property($t, "flag")) {
$self->pidl("flags |= $flags;");
}
$self->pidl("return ndr_size_struct($varname, flags, (ndr_push_flags_fn_t)ndr_push_$name);");
}
sub DeclStruct($$$$)
{
my ($e,$t,$name,$varname) = @_;
return ($t ne "pull"?"const ":"") . "struct $name *$varname";
}
sub ArgsStructNdrSize($$$)
{
my ($d, $name, $varname) = @_;
return "const struct $name *$varname, int flags";
}
$typefamily{STRUCT} = {
PUSH_FN_BODY => \&ParseStructPush,
DECL => \&DeclStruct,
PULL_FN_BODY => \&ParseStructPull,
PRINT_FN_BODY => \&ParseStructPrint,
SIZE_FN_BODY => \&ParseStructNdrSize,
SIZE_FN_ARGS => \&ArgsStructNdrSize,
};
#####################################################################
# calculate size of ndr struct
sub ParseUnionNdrSize($$$)
{
my ($self, $t, $name, $varname) = @_;
my $sizevar;
if (my $flags = has_property($t, "flag")) {
$self->pidl("flags |= $flags;");
}
$self->pidl("return ndr_size_union($varname, flags, level, (ndr_push_flags_fn_t)ndr_push_$name);");
}
sub ParseUnionPushPrimitives($$$$)
{
my ($self, $e, $ndr ,$varname) = @_;
my $have_default = 0;
$self->pidl("uint32_t level = ndr_push_get_switch_value($ndr, $varname);");
if (defined($e->{SWITCH_TYPE})) {
if (defined($e->{ALIGN})) {
$self->pidl("NDR_CHECK(ndr_push_union_align($ndr, $e->{ALIGN}));");
}
$self->pidl("NDR_CHECK(ndr_push_$e->{SWITCH_TYPE}($ndr, NDR_SCALARS, level));");
}
if (defined($e->{ALIGN})) {
if ($e->{IS_MS_UNION}) {
$self->pidl("/* ms_union is always aligned to the largest union arm*/");
$self->pidl("NDR_CHECK(ndr_push_align($ndr, $e->{ALIGN}));");
} else {
$self->pidl("NDR_CHECK(ndr_push_union_align($ndr, $e->{ALIGN}));");
}
}
$self->pidl("switch (level) {");
$self->indent;
foreach my $el (@{$e->{ELEMENTS}}) {
if ($el->{CASE} eq "default") {
$have_default = 1;
}
$self->pidl("$el->{CASE}: {");
if ($el->{TYPE} ne "EMPTY") {
$self->indent;
if (defined($e->{PROPERTIES}{relative_base})) {
$self->pidl("NDR_CHECK(ndr_push_align($ndr, $el->{ALIGN}));");
# set the current offset as base for relative pointers
# and store it based on the toplevel struct/union
$self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
}
$self->DeclareArrayVariables($el);
my $el_env = {$el->{NAME} => "$varname->$el->{NAME}"};
$self->CheckRefPtrs($el, $ndr, $el_env);
$self->ParseElementPush($el, $ndr, $el_env, 1, 0);
$self->deindent;
}
$self->pidl("break; }");
$self->pidl("");
}
if (! $have_default) {
$self->pidl("default:");
$self->pidl("\treturn ndr_push_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
}
$self->deindent;
$self->pidl("}");
}
sub ParseUnionPushDeferred($$$$)
{
my ($self,$e,$ndr,$varname) = @_;
my $have_default = 0;
$self->pidl("uint32_t level = ndr_push_get_switch_value($ndr, $varname);");
if (defined($e->{PROPERTIES}{relative_base})) {
# retrieve the current offset as base for relative pointers
# based on the toplevel struct/union
$self->pidl("NDR_CHECK(ndr_push_setup_relative_base_offset2($ndr, $varname));");
}
$self->pidl("switch (level) {");
$self->indent;
foreach my $el (@{$e->{ELEMENTS}}) {
if ($el->{CASE} eq "default") {
$have_default = 1;
}
$self->pidl("$el->{CASE}:");
if ($el->{TYPE} ne "EMPTY") {
$self->indent;
$self->ParseElementPush($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 0, 1);
$self->deindent;
}
$self->pidl("break;");
$self->pidl("");
}
if (! $have_default) {
$self->pidl("default:");
$self->pidl("\treturn ndr_push_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
}
$self->deindent;
$self->pidl("}");
}
#####################################################################
# parse a union - push side
sub ParseUnionPush($$$$)
{
my ($self,$e,$ndr,$varname) = @_;
my $have_default = 0;
$self->start_flags($e, $ndr);
$self->pidl("NDR_PUSH_CHECK_FLAGS(ndr, ndr_flags);");
$self->pidl("if (ndr_flags & NDR_SCALARS) {");
$self->indent;
$self->ParseUnionPushPrimitives($e, $ndr, $varname);
$self->deindent;
$self->pidl("}");
if (is_deferred_switch_non_empty($e)) {
$self->pidl("if (ndr_flags & NDR_BUFFERS) {");
$self->indent;
$self->ParseUnionPushDeferred($e, $ndr, $varname);
$self->deindent;
$self->pidl("}");
}
$self->end_flags($e, $ndr);
}
#####################################################################
# print a union
sub ParseUnionPrint($$$$$)
{
my ($self,$e,$ndr,$name,$varname) = @_;
my $have_default = 0;
$self->pidl("uint32_t level;");
foreach my $el (@{$e->{ELEMENTS}}) {
$self->DeclareArrayVariables($el);
}
$self->start_flags($e, $ndr);
$self->pidl("level = ndr_print_get_switch_value($ndr, $varname);");
$self->pidl("ndr_print_union($ndr, name, level, \"$name\");");
$self->pidl("switch (level) {");
$self->indent;
foreach my $el (@{$e->{ELEMENTS}}) {
if ($el->{CASE} eq "default") {
$have_default = 1;
}
$self->pidl("$el->{CASE}:");
if ($el->{TYPE} ne "EMPTY") {
$self->indent;
$self->ParseElementPrint($el, $ndr, "$varname->$el->{NAME}", {});
$self->deindent;
}
$self->pidl("break;");
$self->pidl("");
}
if (! $have_default) {
$self->pidl("default:");
$self->pidl("\tndr_print_bad_level($ndr, name, level);");
}
$self->deindent;
$self->pidl("}");
$self->end_flags($e, $ndr);
}
sub ParseUnionPullPrimitives($$$$$)
{
my ($self,$e,$ndr,$varname,$switch_type) = @_;
my $have_default = 0;
if (defined($switch_type)) {
if (defined($e->{ALIGN})) {
$self->pidl("NDR_CHECK(ndr_pull_union_align($ndr, $e->{ALIGN}));");
}
$self->pidl("NDR_CHECK(ndr_pull_$switch_type($ndr, NDR_SCALARS, &_level));");
$self->pidl("if (_level != level) {");
$self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value %u for $varname at \%s\", _level, __location__);");
$self->pidl("}");
}
if (defined($e->{ALIGN})) {
if ($e->{IS_MS_UNION}) {
$self->pidl("/* ms_union is always aligned to the largest union arm*/");
$self->pidl("NDR_CHECK(ndr_pull_align($ndr, $e->{ALIGN}));");
} else {
$self->pidl("NDR_CHECK(ndr_pull_union_align($ndr, $e->{ALIGN}));");
}
}
$self->pidl("switch (level) {");
$self->indent;
foreach my $el (@{$e->{ELEMENTS}}) {
if ($el->{CASE} eq "default") {
$have_default = 1;
}
$self->pidl("$el->{CASE}: {");
if ($el->{TYPE} ne "EMPTY") {
$self->indent;
if (defined($e->{PROPERTIES}{relative_base})) {
$self->pidl("NDR_CHECK(ndr_pull_align($ndr, $el->{ALIGN}));");
# set the current offset as base for relative pointers
# and store it based on the toplevel struct/union
$self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset1($ndr, $varname, $ndr->offset));");
}
$self->ParseElementPull($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 1, 0);
$self->deindent;
}
$self->pidl("break; }");
$self->pidl("");
}
if (! $have_default) {
$self->pidl("default:");
$self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
}
$self->deindent;
$self->pidl("}");
}
sub ParseUnionPullDeferred($$$$)
{
my ($self,$e,$ndr,$varname) = @_;
my $have_default = 0;
if (defined($e->{PROPERTIES}{relative_base})) {
# retrieve the current offset as base for relative pointers
# based on the toplevel struct/union
$self->pidl("NDR_CHECK(ndr_pull_setup_relative_base_offset2($ndr, $varname));");
}
$self->pidl("switch (level) {");
$self->indent;
foreach my $el (@{$e->{ELEMENTS}}) {
if ($el->{CASE} eq "default") {
$have_default = 1;
}
$self->pidl("$el->{CASE}:");
if ($el->{TYPE} ne "EMPTY") {
$self->indent;
$self->ParseElementPull($el, $ndr, {$el->{NAME} => "$varname->$el->{NAME}"}, 0, 1);
$self->deindent;
}
$self->pidl("break;");
$self->pidl("");
}
if (! $have_default) {
$self->pidl("default:");
$self->pidl("\treturn ndr_pull_error($ndr, NDR_ERR_BAD_SWITCH, \"Bad switch value \%u at \%s\", level, __location__);");
}
$self->deindent;
$self->pidl("}");
}
#####################################################################
# parse a union - pull side
sub ParseUnionPull($$$$)
{
my ($self,$e,$ndr,$varname) = @_;
my $switch_type = $e->{SWITCH_TYPE};
my $needs_deferred_switch = is_deferred_switch_non_empty($e);
$self->pidl("uint32_t level;");
if (defined($switch_type)) {
if (Parse::Pidl::Typelist::typeIs($switch_type, "ENUM")) {
$switch_type = Parse::Pidl::Typelist::enum_type_fn(getType($switch_type)->{DATA});
}
$self->pidl(mapTypeName($switch_type) . " _level;");
}
my %double_cases = ();
foreach my $el (@{$e->{ELEMENTS}}) {
next if ($el->{TYPE} eq "EMPTY");
next if ($double_cases{"$el->{NAME}"});
$self->DeclareMemCtxVariables($el);
$self->DeclarePtrVariables($el);
$self->DeclareArrayVariables($el, "pull");
$double_cases{"$el->{NAME}"} = 1;
}
$self->start_flags($e, $ndr);
$self->pidl("NDR_PULL_CHECK_FLAGS(ndr, ndr_flags);");
$self->pidl("if (ndr_flags & NDR_SCALARS) {");
$self->indent;
if (! $needs_deferred_switch) {
$self->pidl("/* This token is not used again */");
$self->pidl("level = ndr_pull_steal_switch_value($ndr, $varname);");
} else {
$self->pidl("level = ndr_pull_get_switch_value($ndr, $varname);");
}
$self->ParseUnionPullPrimitives($e,$ndr,$varname,$switch_type);
$self->deindent;
$self->pidl("}");
if ($needs_deferred_switch) {
$self->pidl("if (ndr_flags & NDR_BUFFERS) {");
$self->indent;
$self->pidl("/* The token is not needed after this. */");
$self->pidl("level = ndr_pull_steal_switch_value($ndr, $varname);");
$self->ParseUnionPullDeferred($e,$ndr,$varname);
$self->deindent;
$self->pidl("}");
}
$self->add_deferred();
$self->end_flags($e, $ndr);
}
sub DeclUnion($$$$)
{
my ($e,$t,$name,$varname) = @_;
return ($t ne "pull"?"const ":"") . "union $name *$varname";
}
sub ArgsUnionNdrSize($$)
{
my ($d,$name) = @_;
return "const union $name *r, uint32_t level, int flags";
}
$typefamily{UNION} = {
PUSH_FN_BODY => \&ParseUnionPush,
DECL => \&DeclUnion,
PULL_FN_BODY => \&ParseUnionPull,
PRINT_FN_BODY => \&ParseUnionPrint,
SIZE_FN_ARGS => \&ArgsUnionNdrSize,
SIZE_FN_BODY => \&ParseUnionNdrSize,
};
#####################################################################
# parse a typedef - push side
sub ParseTypedefPush($$$$)
{
my($self,$e,$ndr,$varname) = @_;
my $env;
$env->{$e->{NAME}} = $varname;
$self->ParseElementPushLevel($e, $e->{LEVELS}[0], $ndr, $varname, $env, 1, 1);
}
#####################################################################
# parse a typedef - pull side
sub ParseTypedefPull($$$$)
{
my($self,$e,$ndr,$varname) = @_;
my $env;
$env->{$e->{NAME}} = $varname;
$self->ParseElementPullLevel($e, $e->{LEVELS}[0], $ndr, $varname, $env, 1, 1);
}
#####################################################################
# parse a typedef - print side
sub ParseTypedefPrint($$$$$)
{
my($self,$e,$ndr,$name,$varname) = @_;
$typefamily{$e->{DATA}->{TYPE}}->{PRINT_FN_BODY}->($self, $e->{DATA}, $ndr, $name, $varname);
}
#####################################################################
## calculate the size of a structure
sub ParseTypedefNdrSize($$$$)
{
my($self,$t,$name,$varname) = @_;
$typefamily{$t->{DATA}->{TYPE}}->{SIZE_FN_BODY}->($self, $t->{DATA}, $name, $varname);
}
sub DeclTypedef($$$$)
{
my ($e, $t, $name, $varname) = @_;
return $typefamily{$e->{DATA}->{TYPE}}->{DECL}->($e->{DATA}, $t, $name, $varname);
}
sub ArgsTypedefNdrSize($$$)
{
my ($d, $name, $varname) = @_;
return $typefamily{$d->{DATA}->{TYPE}}->{SIZE_FN_ARGS}->($d->{DATA}, $name, $varname);
}
$typefamily{TYPEDEF} = {
PUSH_FN_BODY => \&ParseTypedefPush,
DECL => \&DeclTypedef,
PULL_FN_BODY => \&ParseTypedefPull,
PRINT_FN_BODY => \&ParseTypedefPrint,
SIZE_FN_ARGS => \&ArgsTypedefNdrSize,
SIZE_FN_BODY => \&ParseTypedefNdrSize,
};
sub ParsePipePushChunk($$)
{
my ($self, $t) = @_;
my $pipe = $t;
$pipe = $t->{DATA} if ($t->{TYPE} eq "TYPEDEF");
my $struct = $pipe->{DATA};
my $name = "$struct->{NAME}";
my $ndr = "ndr";
my $varname = "r";
my $args = $typefamily{$struct->{TYPE}}->{DECL}->($struct, "push", $name, $varname);
$self->fn_declare("push", $struct, "enum ndr_err_code ndr_push_$name(struct ndr_push *$ndr, int ndr_flags, $args)") or return;
return if has_property($t, "nopush");
$self->pidl("{");
$self->indent;
$self->ParseStructPush($struct, $ndr, $varname);
$self->pidl("");
$self->pidl("NDR_CHECK(ndr_push_pipe_chunk_trailer(ndr, ndr_flags, $varname->count));");
$self->pidl("");
$self->pidl("return NDR_ERR_SUCCESS;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParsePipePullChunk($$)
{
my ($self, $t) = @_;
my $pipe = $t;
$pipe = $t->{DATA} if ($t->{TYPE} eq "TYPEDEF");
my $struct = $pipe->{DATA};
my $name = "$struct->{NAME}";
my $ndr = "ndr";
my $varname = "r";
my $args = $typefamily{$struct->{TYPE}}->{DECL}->($struct, "pull", $name, $varname);
$self->fn_declare("pull", $struct, "enum ndr_err_code ndr_pull_$name(struct ndr_pull *$ndr, int ndr_flags, $args)") or return;
return if has_property($struct, "nopull");
$self->pidl("{");
$self->indent;
$self->ParseStructPull($struct, $ndr, $varname);
$self->pidl("");
$self->pidl("NDR_CHECK(ndr_check_pipe_chunk_trailer($ndr, ndr_flags, $varname->count));");
$self->pidl("");
$self->pidl("return NDR_ERR_SUCCESS;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParsePipePrintChunk($$)
{
my ($self, $t) = @_;
my $pipe = $t;
$pipe = $t->{DATA} if ($t->{TYPE} eq "TYPEDEF");
my $struct = $pipe->{DATA};
my $name = "$struct->{NAME}";
my $ndr = "ndr";
my $varname = "r";
my $args = $typefamily{$struct->{TYPE}}->{DECL}->($struct, "print", $name, $varname);
$self->pidl_hdr("void ndr_print_$name(struct ndr_print *ndr, const char *name, $args);");
return if (has_property($t, "noprint"));
$self->pidl("_PUBLIC_ void ndr_print_$name(struct ndr_print *$ndr, const char *name, $args)");
$self->pidl("{");
$self->indent;
$self->ParseTypePrint($struct, $ndr, $varname);
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
#####################################################################
# parse a function - print side
sub ParseFunctionPrint($$)
{
my($self, $fn) = @_;
my $ndr = "ndr";
$self->pidl_hdr("void ndr_print_$fn->{NAME}(struct ndr_print *$ndr, const char *name, int flags, const struct $fn->{NAME} *r);");
return if has_property($fn, "noprint");
$self->pidl("_PUBLIC_ void ndr_print_$fn->{NAME}(struct ndr_print *$ndr, const char *name, int flags, const struct $fn->{NAME} *r)");
$self->pidl("{");
$self->indent;
foreach my $e (@{$fn->{ELEMENTS}}) {
$self->DeclareArrayVariables($e);
}
$self->pidl("ndr_print_struct($ndr, name, \"$fn->{NAME}\");");
$self->pidl("if (r == NULL) { ndr_print_null($ndr); return; }");
$self->pidl("$ndr->depth++;");
$self->pidl("if (flags & NDR_SET_VALUES) {");
$self->pidl("\t$ndr->flags |= LIBNDR_PRINT_SET_VALUES;");
$self->pidl("}");
$self->pidl("if (flags & NDR_IN) {");
$self->indent;
$self->pidl("ndr_print_struct($ndr, \"in\", \"$fn->{NAME}\");");
$self->pidl("$ndr->depth++;");
my $env = GenerateFunctionInEnv($fn);
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep(/in/,@{$e->{DIRECTION}})) {
$self->ParseElementPrint($e, $ndr, $env->{$e->{NAME}}, $env);
}
}
$self->pidl("$ndr->depth--;");
$self->deindent;
$self->pidl("}");
$self->pidl("if (flags & NDR_OUT) {");
$self->indent;
$self->pidl("ndr_print_struct($ndr, \"out\", \"$fn->{NAME}\");");
$self->pidl("$ndr->depth++;");
$env = GenerateFunctionOutEnv($fn);
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep(/out/,@{$e->{DIRECTION}})) {
$self->ParseElementPrint($e, $ndr, $env->{$e->{NAME}}, $env);
}
}
if ($fn->{RETURN_TYPE}) {
$self->pidl("ndr_print_$fn->{RETURN_TYPE}($ndr, \"result\", r->out.result);");
}
$self->pidl("$ndr->depth--;");
$self->deindent;
$self->pidl("}");
$self->pidl("$ndr->depth--;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
#####################################################################
# parse a function
sub ParseFunctionPush($$)
{
my($self, $fn) = @_;
my $ndr = "ndr";
$self->fn_declare("push", $fn, "enum ndr_err_code ndr_push_$fn->{NAME}(struct ndr_push *$ndr, int flags, const struct $fn->{NAME} *r)") or return;
return if has_property($fn, "nopush");
$self->pidl("{");
$self->indent;
foreach my $e (@{$fn->{ELEMENTS}}) {
$self->DeclareArrayVariables($e);
}
$self->pidl("NDR_PUSH_CHECK_FN_FLAGS(ndr, flags);");
$self->pidl("if (flags & NDR_IN) {");
$self->indent;
my $env = GenerateFunctionInEnv($fn);
EnvSubstituteValue($env, $fn);
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep(/in/,@{$e->{DIRECTION}})) {
$self->CheckRefPtrs($e, $ndr, $env);
}
}
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep(/in/,@{$e->{DIRECTION}})) {
$self->ParseElementPush($e, $ndr, $env, 1, 1);
}
}
$self->deindent;
$self->pidl("}");
$self->pidl("if (flags & NDR_OUT) {");
$self->indent;
$env = GenerateFunctionOutEnv($fn);
EnvSubstituteValue($env, $fn);
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep(/out/,@{$e->{DIRECTION}})) {
$self->CheckRefPtrs($e, $ndr, $env);
}
}
foreach my $e (@{$fn->{ELEMENTS}}) {
if (grep(/out/,@{$e->{DIRECTION}})) {
$self->ParseElementPush($e, $ndr, $env, 1, 1);
}
}
if ($fn->{RETURN_TYPE}) {
$self->pidl("NDR_CHECK(ndr_push_$fn->{RETURN_TYPE}($ndr, NDR_SCALARS, r->out.result));");
}
$self->deindent;
$self->pidl("}");
$self->pidl("return NDR_ERR_SUCCESS;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub AllocateArrayLevel($$$$$$)
{
my ($self,$e,$l,$ndr,$var,$size) = @_;
my $pl = GetPrevLevel($e, $l);
if (defined($pl) and
$pl->{TYPE} eq "POINTER" and
$pl->{POINTER_TYPE} eq "ref"
and not $l->{IS_ZERO_TERMINATED}) {
$self->pidl("if ($ndr->flags & LIBNDR_FLAG_REF_ALLOC) {");
$self->pidl("\tNDR_PULL_ALLOC_N($ndr, $var, $size);");
$self->pidl("}");
if (grep(/in/,@{$e->{DIRECTION}}) and
grep(/out/,@{$e->{DIRECTION}})) {
$self->pidl("memcpy(r->out.$e->{NAME}, r->in.$e->{NAME}, ($size) * sizeof(*r->in.$e->{NAME}));");
}
return;
}
$self->pidl("NDR_PULL_ALLOC_N($ndr, $var, $size);");
}
#####################################################################
# parse a function
sub ParseFunctionPull($$)
{
my($self,$fn) = @_;
my $ndr = "ndr";
# pull function args
$self->fn_declare("pull", $fn, "enum ndr_err_code ndr_pull_$fn->{NAME}(struct ndr_pull *$ndr, int flags, struct $fn->{NAME} *r)") or return;
$self->pidl("{");
$self->indent;
# declare any internal pointers we need
foreach my $e (@{$fn->{ELEMENTS}}) {
$self->DeclarePtrVariables($e);
$self->DeclareArrayVariables($e, "pull");
}
my %double_cases = ();
foreach my $e (@{$fn->{ELEMENTS}}) {
next if ($e->{TYPE} eq "EMPTY");
next if ($double_cases{"$e->{NAME}"});
$self->DeclareMemCtxVariables($e);
$double_cases{"$e->{NAME}"} = 1;
}
$self->pidl("NDR_PULL_CHECK_FN_FLAGS(ndr, flags);");
$self->pidl("if (flags & NDR_IN) {");
$self->indent;
# auto-init the out section of a structure. I originally argued that
# this was a bad idea as it hides bugs, but coping correctly
# with initialisation and not wiping ref vars is turning
# out to be too tricky (tridge)
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless grep(/out/, @{$e->{DIRECTION}});
$self->pidl("ZERO_STRUCT(r->out);");
$self->pidl("");
last;
}
my $env = GenerateFunctionInEnv($fn);
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless (grep(/in/, @{$e->{DIRECTION}}));
$self->ParseElementPull($e, $ndr, $env, 1, 1);
}
# allocate the "simple" out ref variables. FIXME: Shouldn't this have it's
# own flag rather than be in NDR_IN ?
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless (grep(/out/, @{$e->{DIRECTION}}));
next unless ($e->{LEVELS}[0]->{TYPE} eq "POINTER" and
$e->{LEVELS}[0]->{POINTER_TYPE} eq "ref");
next if (($e->{LEVELS}[1]->{TYPE} eq "DATA") and
($e->{LEVELS}[1]->{DATA_TYPE} eq "string"));
next if ($e->{LEVELS}[1]->{TYPE} eq "PIPE");
next if (($e->{LEVELS}[1]->{TYPE} eq "ARRAY")
and $e->{LEVELS}[1]->{IS_ZERO_TERMINATED});
if ($e->{LEVELS}[1]->{TYPE} eq "ARRAY") {
my $size = ParseExprExt($e->{LEVELS}[1]->{SIZE_IS}, $env, $e->{ORIGINAL},
check_null_pointer($e, $env, sub { $self->pidl(shift); },
"return ndr_pull_error($ndr, NDR_ERR_INVALID_POINTER, \"NULL Pointer for size_is()\");"),
check_fully_dereferenced($e, $env));
$self->pidl("NDR_PULL_ALLOC_N($ndr, r->out.$e->{NAME}, $size);");
if (grep(/in/, @{$e->{DIRECTION}})) {
$self->pidl("memcpy(r->out.$e->{NAME}, r->in.$e->{NAME}, ($size) * sizeof(*r->in.$e->{NAME}));");
} else {
$self->pidl("memset(r->out.$e->{NAME}, 0, ($size) * sizeof(*r->out.$e->{NAME}));");
}
} elsif ($e->{LEVELS}[1]->{TYPE} eq "ARRAY") {
if (grep(/in/, @{$e->{DIRECTION}})) {
$self->pidl("r->out.$e->{NAME} = r->in.$e->{NAME};");
} else {
$self->pidl("r->out.$e->{NAME} = NULL;");
}
} else {
$self->pidl("NDR_PULL_ALLOC($ndr, r->out.$e->{NAME});");
if (grep(/in/, @{$e->{DIRECTION}})) {
$self->pidl("*r->out.$e->{NAME} = *r->in.$e->{NAME};");
} else {
$self->pidl("ZERO_STRUCTP(r->out.$e->{NAME});");
}
}
}
$self->add_deferred();
$self->deindent;
$self->pidl("}");
$self->pidl("if (flags & NDR_OUT) {");
$self->indent;
$env = GenerateFunctionOutEnv($fn);
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless grep(/out/, @{$e->{DIRECTION}});
$self->ParseElementPull($e, $ndr, $env, 1, 1);
}
if ($fn->{RETURN_TYPE}) {
$self->pidl("NDR_CHECK(ndr_pull_$fn->{RETURN_TYPE}($ndr, NDR_SCALARS, &r->out.result));");
}
$self->add_deferred();
$self->deindent;
$self->pidl("}");
$self->pidl("return NDR_ERR_SUCCESS;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub AuthServiceStruct($$$)
{
my ($self, $ifacename, $authservice) = @_;
my @a = split /,/, $authservice;
my $authservice_count = $#a + 1;
$self->pidl("static const char * const $ifacename\_authservice_strings[] = {");
foreach my $ap (@a) {
$self->pidl("\t$ap, ");
}
$self->pidl("};");
$self->pidl("");
$self->pidl("static const struct ndr_interface_string_array $ifacename\_authservices = {");
$self->pidl("\t.count\t= $authservice_count,");
$self->pidl("\t.names\t= $ifacename\_authservice_strings");
$self->pidl("};");
$self->pidl("");
}
sub ParseGeneratePipeArray($$$)
{
my ($self, $fn, $direction) = @_;
$self->pidl("static const struct ndr_interface_call_pipe $fn->{NAME}\_$direction\_pipes[] = {");
$self->indent;
foreach my $e (@{$fn->{ELEMENTS}}) {
next unless ContainsPipe($e, $e->{LEVELS}[0]);
next unless (grep(/$direction/, @{$e->{DIRECTION}}));
my $cname = "$e->{TYPE}_chunk";
$self->pidl("{");
$self->indent;
$self->pidl("\"$direction.$e->{NAME}\",");
$self->pidl("\"$cname\",");
$self->pidl("sizeof(struct $cname),");
$self->pidl("(ndr_push_flags_fn_t) ndr_push_$cname,");
$self->pidl("(ndr_pull_flags_fn_t) ndr_pull_$cname,");
$self->pidl("(ndr_print_fn_t) ndr_print_$cname,");
$self->deindent;
$self->pidl("},");
}
$self->pidl("{ NULL, NULL, 0, NULL, NULL, NULL }");
$self->deindent;
$self->pidl("};");
$self->pidl("");
}
sub FunctionCallPipes($$)
{
my ($self, $d) = @_;
return if not defined($d->{OPNUM});
my $in_pipes = 0;
my $out_pipes = 0;
foreach my $e (@{$d->{ELEMENTS}}) {
next unless ContainsPipe($e, $e->{LEVELS}[0]);
if (grep(/in/, @{$e->{DIRECTION}})) {
$in_pipes++;
}
if (grep(/out/, @{$e->{DIRECTION}})) {
$out_pipes++;
}
}
if ($in_pipes) {
$self->ParseGeneratePipeArray($d, "in");
}
if ($out_pipes) {
$self->ParseGeneratePipeArray($d, "out");
}
}
sub FunctionCallEntry($$)
{
my ($self, $d) = @_;
return 0 if not defined($d->{OPNUM});
my $in_pipes = 0;
my $out_pipes = 0;
foreach my $e (@{$d->{ELEMENTS}}) {
next unless ContainsPipe($e, $e->{LEVELS}[0]);
if (grep(/in/, @{$e->{DIRECTION}})) {
$in_pipes++;
}
if (grep(/out/, @{$e->{DIRECTION}})) {
$out_pipes++;
}
}
my $in_pipes_ptr = "NULL";
my $out_pipes_ptr = "NULL";
if ($in_pipes) {
$in_pipes_ptr = "$d->{NAME}_in_pipes";
}
if ($out_pipes) {
$out_pipes_ptr = "$d->{NAME}_out_pipes";
}
$self->pidl("\t{");
$self->pidl("\t\t\"$d->{NAME}\",");
$self->pidl("\t\tsizeof(struct $d->{NAME}),");
$self->pidl("\t\t(ndr_push_flags_fn_t) ndr_push_$d->{NAME},");
$self->pidl("\t\t(ndr_pull_flags_fn_t) ndr_pull_$d->{NAME},");
$self->pidl("\t\t(ndr_print_function_t) ndr_print_$d->{NAME},");
$self->pidl("\t\t{ $in_pipes, $in_pipes_ptr },");
$self->pidl("\t\t{ $out_pipes, $out_pipes_ptr },");
$self->pidl("\t},");
return 1;
}
#####################################################################
# produce a function call table
sub FunctionTable($$)
{
my($self,$interface) = @_;
my $count = 0;
my $uname = uc $interface->{NAME};
return if ($#{$interface->{FUNCTIONS}}+1 == 0);
return unless defined ($interface->{PROPERTIES}->{uuid});
foreach my $d (@{$interface->{INHERITED_FUNCTIONS}},@{$interface->{FUNCTIONS}}) {
$self->FunctionCallPipes($d);
}
$self->pidl("static const struct ndr_interface_call $interface->{NAME}\_calls[] = {");
foreach my $d (@{$interface->{INHERITED_FUNCTIONS}},@{$interface->{FUNCTIONS}}) {
$count += $self->FunctionCallEntry($d);
}
$self->pidl("\t{ NULL, 0, NULL, NULL, NULL }");
$self->pidl("};");
$self->pidl("");
$self->pidl("static const char * const $interface->{NAME}\_endpoint_strings[] = {");
foreach my $ep (@{$interface->{ENDPOINTS}}) {
$self->pidl("\t$ep, ");
}
my $endpoint_count = $#{$interface->{ENDPOINTS}}+1;
$self->pidl("};");
$self->pidl("");
$self->pidl("static const struct ndr_interface_string_array $interface->{NAME}\_endpoints = {");
$self->pidl("\t.count\t= $endpoint_count,");
$self->pidl("\t.names\t= $interface->{NAME}\_endpoint_strings");
$self->pidl("};");
$self->pidl("");
if (! defined $interface->{PROPERTIES}->{authservice}) {
$interface->{PROPERTIES}->{authservice} = "\"host\"";
}
$self->AuthServiceStruct($interface->{NAME},
$interface->{PROPERTIES}->{authservice});
$self->pidl("\nconst struct ndr_interface_table ndr_table_$interface->{NAME} = {");
$self->pidl("\t.name\t\t= \"$interface->{NAME}\",");
$self->pidl("\t.syntax_id\t= {");
$self->pidl("\t\t" . print_uuid($interface->{UUID}) .",");
$self->pidl("\t\tNDR_$uname\_VERSION");
$self->pidl("\t},");
$self->pidl("\t.helpstring\t= NDR_$uname\_HELPSTRING,");
$self->pidl("\t.num_calls\t= $count,");
$self->pidl("\t.calls\t\t= $interface->{NAME}\_calls,");
$self->pidl("\t.endpoints\t= &$interface->{NAME}\_endpoints,");
$self->pidl("\t.authservices\t= &$interface->{NAME}\_authservices");
$self->pidl("};");
$self->pidl("");
}
#####################################################################
# generate include statements for imported idl files
sub HeaderImport
{
my $self = shift;
my @imports = @_;
foreach (@imports) {
$_ = unmake_str($_);
s/\.idl$//;
$self->pidl(choose_header("librpc/gen_ndr/ndr_$_\.h", "gen_ndr/ndr_$_.h"));
}
}
#####################################################################
# generate include statements for included header files
sub HeaderInclude
{
my $self = shift;
my @includes = @_;
foreach (@includes) {
$self->pidl_hdr("#include $_");
}
}
#####################################################################
# generate prototypes and defines for the interface definitions
# FIXME: these prototypes are for the DCE/RPC client functions, not the
# NDR parser and so do not belong here, technically speaking
sub HeaderInterface($$$)
{
my($self,$interface,$needed) = @_;
my $count = 0;
if ($needed->{"compression"}) {
$self->pidl(choose_header("librpc/ndr/ndr_compression.h", "ndr/compression.h"));
}
if (has_property($interface, "object")) {
$self->pidl(choose_header("librpc/gen_ndr/ndr_orpc.h", "ndr/orpc.h"));
}
if (defined $interface->{PROPERTIES}->{helper}) {
$self->HeaderInclude(split /,/, $interface->{PROPERTIES}->{helper});
}
if (defined $interface->{PROPERTIES}->{uuid}) {
my $name = uc $interface->{NAME};
$self->pidl_hdr("#define NDR_$name\_UUID " .
Parse::Pidl::Util::make_str(lc($interface->{UUID})));
$self->pidl_hdr("#define NDR_$name\_VERSION $interface->{VERSION}");
$self->pidl_hdr("#define NDR_$name\_NAME \"$interface->{NAME}\"");
if(!defined $interface->{PROPERTIES}->{helpstring}) { $interface->{PROPERTIES}->{helpstring} = "NULL"; }
$self->pidl_hdr("#define NDR_$name\_HELPSTRING $interface->{PROPERTIES}->{helpstring}");
$self->pidl_hdr("extern const struct ndr_interface_table ndr_table_$interface->{NAME};");
}
foreach (@{$interface->{FUNCTIONS}}) {
next if has_property($_, "noopnum");
next if grep(/^$_->{NAME}$/,@{$interface->{INHERITED_FUNCTIONS}});
my $u_name = uc $_->{NAME};
my $val = sprintf("0x%02x", $count);
if (defined($interface->{BASE})) {
$val .= " + NDR_" . uc $interface->{BASE} . "_CALL_COUNT";
}
$self->pidl_hdr("#define NDR_$u_name ($val)");
$self->pidl_hdr("");
$count++;
}
my $val = $count;
if (defined($interface->{BASE})) {
$val .= " + NDR_" . uc $interface->{BASE} . "_CALL_COUNT";
}
$self->pidl_hdr("#define NDR_" . uc $interface->{NAME} . "_CALL_COUNT ($val)");
}
sub ParseTypePush($$$$$$)
{
my ($self,$e, $ndr, $varname, $primitives, $deferred) = @_;
# save the old relative_base_offset
$self->pidl("uint32_t _save_relative_base_offset = ndr_push_get_relative_base_offset($ndr);") if defined(has_property($e, "relative_base"));
$typefamily{$e->{TYPE}}->{PUSH_FN_BODY}->($self, $e, $ndr, $varname);
# restore the old relative_base_offset
$self->pidl("ndr_push_restore_relative_base_offset($ndr, _save_relative_base_offset);") if defined(has_property($e, "relative_base"));
}
sub ParseTypePushFunction($$$)
{
my ($self, $e, $varname) = @_;
my $ndr = "ndr";
my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "push", $e->{NAME}, $varname);
$self->fn_declare("push", $e, "enum ndr_err_code ".TypeFunctionName("ndr_push", $e)."(struct ndr_push *$ndr, int ndr_flags, $args)") or return;
$self->pidl("{");
$self->indent;
$self->ParseTypePush($e, $ndr, $varname, 1, 1);
$self->pidl("return NDR_ERR_SUCCESS;");
$self->deindent;
$self->pidl("}");
$self->pidl("");;
}
sub ParseTypePull($$$$$$)
{
my ($self, $e, $ndr, $varname, $primitives, $deferred) = @_;
# save the old relative_base_offset
$self->pidl("uint32_t _save_relative_base_offset = ndr_pull_get_relative_base_offset($ndr);") if defined(has_property($e, "relative_base"));
$typefamily{$e->{TYPE}}->{PULL_FN_BODY}->($self, $e, $ndr, $varname);
# restore the old relative_base_offset
$self->pidl("ndr_pull_restore_relative_base_offset($ndr, _save_relative_base_offset);") if defined(has_property($e, "relative_base"));
}
sub ParseTypePullFunction($$)
{
my ($self, $e, $varname) = @_;
my $ndr = "ndr";
my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "pull", $e->{NAME}, $varname);
$self->fn_declare("pull", $e, "enum ndr_err_code ".TypeFunctionName("ndr_pull", $e)."(struct ndr_pull *$ndr, int ndr_flags, $args)") or return;
$self->pidl("{");
$self->indent;
$self->ParseTypePull($e, $ndr, $varname, 1, 1);
$self->pidl("return NDR_ERR_SUCCESS;");
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseTypePrint($$$$)
{
my ($self, $e, $ndr, $varname) = @_;
$typefamily{$e->{TYPE}}->{PRINT_FN_BODY}->($self, $e, $ndr, $e->{NAME}, $varname);
}
sub ParseTypePrintFunction($$$)
{
my ($self, $e, $varname) = @_;
my $ndr = "ndr";
my $args = $typefamily{$e->{TYPE}}->{DECL}->($e, "print", $e->{NAME}, $varname);
$self->pidl_hdr("void ".TypeFunctionName("ndr_print", $e)."(struct ndr_print *ndr, const char *name, $args);");
return if (has_property($e, "noprint"));
$self->pidl("_PUBLIC_ void ".TypeFunctionName("ndr_print", $e)."(struct ndr_print *$ndr, const char *name, $args)");
$self->pidl("{");
$self->indent;
$self->ParseTypePrint($e, $ndr, $varname);
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
sub ParseTypeNdrSize($$)
{
my ($self,$t) = @_;
my $varname = "r";
my $tf = $typefamily{$t->{TYPE}};
my $args = $tf->{SIZE_FN_ARGS}->($t, $t->{NAME}, $varname);
$self->fn_declare("size", $t, "size_t ndr_size_$t->{NAME}($args)") or return;
$self->pidl("{");
$self->indent;
$typefamily{$t->{TYPE}}->{SIZE_FN_BODY}->($self,$t, $t->{NAME}, $varname);
$self->deindent;
$self->pidl("}");
$self->pidl("");
}
#####################################################################
# parse the interface definitions
sub ParseInterface($$$)
{
my($self,$interface,$needed) = @_;
$self->pidl_hdr("#ifndef _HEADER_NDR_$interface->{NAME}");
$self->pidl_hdr("#define _HEADER_NDR_$interface->{NAME}");
$self->pidl_hdr("");
$self->HeaderInterface($interface, $needed);
# Typedefs
foreach my $d (@{$interface->{TYPES}}) {
if (Parse::Pidl::Typelist::typeIs($d, "PIPE")) {
($needed->{TypeFunctionName("ndr_push", $d)}) &&
$self->ParsePipePushChunk($d);
($needed->{TypeFunctionName("ndr_pull", $d)}) &&
$self->ParsePipePullChunk($d);
($needed->{TypeFunctionName("ndr_print", $d)}) &&
$self->ParsePipePrintChunk($d);
$needed->{TypeFunctionName("ndr_pull", $d)} = 0;
$needed->{TypeFunctionName("ndr_push", $d)} = 0;
$needed->{TypeFunctionName("ndr_print", $d)} = 0;
next;
}
next unless(typeHasBody($d));
($needed->{TypeFunctionName("ndr_push", $d)}) && $self->ParseTypePushFunction($d, "r");
($needed->{TypeFunctionName("ndr_pull", $d)}) && $self->ParseTypePullFunction($d, "r");
($needed->{TypeFunctionName("ndr_print", $d)}) && $self->ParseTypePrintFunction($d, "r");
# Make sure we don't generate a function twice...
$needed->{TypeFunctionName("ndr_push", $d)} =
$needed->{TypeFunctionName("ndr_pull", $d)} =
$needed->{TypeFunctionName("ndr_print", $d)} = 0;
($needed->{"ndr_size_$d->{NAME}"}) && $self->ParseTypeNdrSize($d);
}
# Functions
foreach my $d (@{$interface->{FUNCTIONS}}) {
($needed->{"ndr_push_$d->{NAME}"}) && $self->ParseFunctionPush($d);
($needed->{"ndr_pull_$d->{NAME}"}) && $self->ParseFunctionPull($d);
($needed->{"ndr_print_$d->{NAME}"}) && $self->ParseFunctionPrint($d);
}
$self->FunctionTable($interface);
$self->pidl_hdr("#endif /* _HEADER_NDR_$interface->{NAME} */");
}
sub GenerateIncludes($)
{
my ($self) = @_;
if (is_intree()) {
$self->pidl("#include \"includes.h\"");
} else {
$self->pidl("#ifndef _GNU_SOURCE");
$self->pidl("#define _GNU_SOURCE");
$self->pidl("#endif");
$self->pidl("#include <stdint.h>");
$self->pidl("#include <stdlib.h>");
$self->pidl("#include <stdio.h>");
$self->pidl("#include <stdbool.h>");
$self->pidl("#include <stdarg.h>");
$self->pidl("#include <string.h>");
}
}
#####################################################################
# parse a parsed IDL structure back into an IDL file
sub Parse($$$$)
{
my($self, $ndr,$gen_header,$ndr_header) = @_;
$self->pidl_hdr("/* header auto-generated by pidl */");
$self->pidl_hdr("");
$self->pidl_hdr(choose_header("librpc/ndr/libndr.h", "ndr.h"));
$self->pidl_hdr("#include \"$gen_header\"") if ($gen_header);
$self->pidl_hdr("");
$self->pidl("/* parser auto-generated by pidl */");
$self->pidl("");
$self->GenerateIncludes();
$self->pidl("#include \"$ndr_header\"") if ($ndr_header);
$self->pidl("");
my %needed = ();
foreach (@{$ndr}) {
($_->{TYPE} eq "INTERFACE") && NeededInterface($_, \%needed);
}
foreach (@{$ndr}) {
($_->{TYPE} eq "INTERFACE") && $self->ParseInterface($_, \%needed);
($_->{TYPE} eq "IMPORT") && $self->HeaderImport(@{$_->{PATHS}});
($_->{TYPE} eq "INCLUDE") && $self->HeaderInclude(@{$_->{PATHS}});
}
return ($self->{res_hdr}, $self->{res});
}
sub NeededElement($$$)
{
my ($e, $dir, $needed) = @_;
return if ($e->{TYPE} eq "EMPTY");
return if (ref($e->{TYPE}) eq "HASH" and
not defined($e->{TYPE}->{NAME}));
my ($t, $rt);
if (ref($e->{TYPE}) eq "HASH") {
$t = $e->{TYPE}->{TYPE}."_".$e->{TYPE}->{NAME};
} else {
$t = $e->{TYPE};
}
if (ref($e->{REPRESENTATION_TYPE}) eq "HASH") {
$rt = $e->{REPRESENTATION_TYPE}->{TYPE}."_".$e->{REPRESENTATION_TYPE}->{NAME};
} else {
$rt = $e->{REPRESENTATION_TYPE};
}
die ("$e->{NAME} $t, $rt FOO") unless ($rt ne "");
my @fn = ();
if ($dir eq "print") {
push(@fn, TypeFunctionName("ndr_print", $e->{REPRESENTATION_TYPE}));
} elsif ($dir eq "pull") {
push (@fn, TypeFunctionName("ndr_pull", $e->{TYPE}));
push (@fn, "ndr_$t\_to_$rt")
if ($rt ne $t);
} elsif ($dir eq "push") {
push (@fn, TypeFunctionName("ndr_push", $e->{TYPE}));
push (@fn, "ndr_$rt\_to_$t")
if ($rt ne $t);
} else {
die("invalid direction `$dir'");
}
foreach (@fn) {
unless (defined($needed->{$_})) {
$needed->{$_} = 1;
}
}
}
sub NeededFunction($$)
{
my ($fn,$needed) = @_;
$needed->{"ndr_pull_$fn->{NAME}"} = 1;
$needed->{"ndr_push_$fn->{NAME}"} = 1;
$needed->{"ndr_print_$fn->{NAME}"} = 1;
foreach my $e (@{$fn->{ELEMENTS}}) {
$e->{PARENT} = $fn;
NeededElement($e, $_, $needed) foreach ("pull", "push", "print");
}
}
sub NeededType($$$)
{
sub NeededType($$$);
my ($t,$needed,$req) = @_;
NeededType($t->{DATA}, $needed, $req) if ($t->{TYPE} eq "TYPEDEF");
NeededType($t->{DATA}, $needed, $req) if ($t->{TYPE} eq "PIPE");
if ($t->{TYPE} eq "STRUCT" or $t->{TYPE} eq "UNION") {
return unless defined($t->{ELEMENTS});
for my $e (@{$t->{ELEMENTS}}) {
$e->{PARENT} = $t;
if (has_property($e, "compression")) {
$needed->{"compression"} = 1;
}
NeededElement($e, $req, $needed);
NeededType($e->{TYPE}, $needed, $req) if (ref($e->{TYPE}) eq "HASH");
}
}
}
#####################################################################
# work out what parse functions are needed
sub NeededInterface($$)
{
my ($interface,$needed) = @_;
NeededFunction($_, $needed) foreach (@{$interface->{FUNCTIONS}});
foreach (reverse @{$interface->{TYPES}}) {
if (has_property($_, "public")) {
$needed->{TypeFunctionName("ndr_pull", $_)} = $needed->{TypeFunctionName("ndr_push", $_)} =
$needed->{TypeFunctionName("ndr_print", $_)} = 1;
}
NeededType($_, $needed, "pull") if ($needed->{TypeFunctionName("ndr_pull", $_)});
NeededType($_, $needed, "push") if ($needed->{TypeFunctionName("ndr_push", $_)});
NeededType($_, $needed, "print") if ($needed->{TypeFunctionName("ndr_print", $_)});
if (has_property($_, "gensize")) {
$needed->{"ndr_size_$_->{NAME}"} = 1;
}
}
}
sub TypeFunctionName($$)
{
my ($prefix, $t) = @_;
return "$prefix\_$t->{NAME}" if (ref($t) eq "HASH" and
$t->{TYPE} eq "TYPEDEF");
return "$prefix\_$t->{TYPE}_$t->{NAME}" if (ref($t) eq "HASH");
return "$prefix\_$t";
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Samba4/NDR/Server.pm | ###################################################
# server boilerplate generator
# Copyright [email protected] 2003
# Copyright [email protected] 2004
# released under the GNU GPL
package Parse::Pidl::Samba4::NDR::Server;
use strict;
use Parse::Pidl::Util;
use vars qw($VERSION);
$VERSION = '0.01';
my($res);
sub pidl($)
{
$res .= shift;
}
#####################################################
# generate the switch statement for function dispatch
sub gen_dispatch_switch($)
{
my $interface = shift;
foreach my $fn (@{$interface->{FUNCTIONS}}) {
next if not defined($fn->{OPNUM});
pidl "\tcase $fn->{OPNUM}: {\n";
pidl "\t\tstruct $fn->{NAME} *r2 = (struct $fn->{NAME} *)r;\n";
pidl "\t\tif (DEBUGLEVEL >= 10) {\n";
pidl "\t\t\tNDR_PRINT_FUNCTION_DEBUG($fn->{NAME}, NDR_IN, r2);\n";
pidl "\t\t}\n";
if ($fn->{RETURN_TYPE} && $fn->{RETURN_TYPE} ne "void") {
pidl "\t\tr2->out.result = dcesrv_$fn->{NAME}(dce_call, mem_ctx, r2);\n";
} else {
pidl "\t\tdcesrv_$fn->{NAME}(dce_call, mem_ctx, r2);\n";
}
pidl "\t\tif (dce_call->state_flags & DCESRV_CALL_STATE_FLAG_ASYNC) {\n";
pidl "\t\t\tDEBUG(5,(\"function $fn->{NAME} will reply async\\n\"));\n";
pidl "\t\t}\n";
pidl "\t\tbreak;\n\t}\n";
}
}
#####################################################
# generate the switch statement for function reply
sub gen_reply_switch($)
{
my $interface = shift;
foreach my $fn (@{$interface->{FUNCTIONS}}) {
next if not defined($fn->{OPNUM});
pidl "\tcase $fn->{OPNUM}: {\n";
pidl "\t\tstruct $fn->{NAME} *r2 = (struct $fn->{NAME} *)r;\n";
pidl "\t\tif (dce_call->state_flags & DCESRV_CALL_STATE_FLAG_ASYNC) {\n";
pidl "\t\t\tDEBUG(5,(\"function $fn->{NAME} replied async\\n\"));\n";
pidl "\t\t}\n";
pidl "\t\tif (DEBUGLEVEL >= 10 && dce_call->fault_code == 0) {\n";
pidl "\t\t\tNDR_PRINT_FUNCTION_DEBUG($fn->{NAME}, NDR_OUT | NDR_SET_VALUES, r2);\n";
pidl "\t\t}\n";
pidl "\t\tif (dce_call->fault_code != 0) {\n";
pidl "\t\t\tDEBUG(2,(\"dcerpc_fault %s in $fn->{NAME}\\n\", dcerpc_errstr(mem_ctx, dce_call->fault_code)));\n";
pidl "\t\t}\n";
pidl "\t\tbreak;\n\t}\n";
}
}
#####################################################################
# produce boilerplate code for a interface
sub Boilerplate_Iface($)
{
my($interface) = shift;
my $name = $interface->{NAME};
my $uname = uc $name;
my $uuid = lc($interface->{UUID});
my $if_version = $interface->{VERSION};
pidl "
static NTSTATUS $name\__op_bind(struct dcesrv_call_state *dce_call, const struct dcesrv_interface *iface, uint32_t if_version)
{
#ifdef DCESRV_INTERFACE_$uname\_BIND
return DCESRV_INTERFACE_$uname\_BIND(dce_call,iface);
#else
return NT_STATUS_OK;
#endif
}
static void $name\__op_unbind(struct dcesrv_connection_context *context, const struct dcesrv_interface *iface)
{
#ifdef DCESRV_INTERFACE_$uname\_UNBIND
DCESRV_INTERFACE_$uname\_UNBIND(context, iface);
#else
return;
#endif
}
static NTSTATUS $name\__op_ndr_pull(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, struct ndr_pull *pull, void **r)
{
enum ndr_err_code ndr_err;
uint16_t opnum = dce_call->pkt.u.request.opnum;
dce_call->fault_code = 0;
if (opnum >= ndr_table_$name.num_calls) {
dce_call->fault_code = DCERPC_FAULT_OP_RNG_ERROR;
return NT_STATUS_NET_WRITE_FAULT;
}
*r = talloc_named(mem_ctx,
ndr_table_$name.calls[opnum].struct_size,
\"struct %s\",
ndr_table_$name.calls[opnum].name);
NT_STATUS_HAVE_NO_MEMORY(*r);
/* unravel the NDR for the packet */
ndr_err = ndr_table_$name.calls[opnum].ndr_pull(pull, NDR_IN, *r);
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
dcerpc_log_packet(dce_call->conn->packet_log_dir,
&ndr_table_$name, opnum, NDR_IN,
&dce_call->pkt.u.request.stub_and_verifier);
dce_call->fault_code = DCERPC_FAULT_NDR;
return NT_STATUS_NET_WRITE_FAULT;
}
return NT_STATUS_OK;
}
static NTSTATUS $name\__op_dispatch(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, void *r)
{
uint16_t opnum = dce_call->pkt.u.request.opnum;
switch (opnum) {
";
gen_dispatch_switch($interface);
pidl "
default:
dce_call->fault_code = DCERPC_FAULT_OP_RNG_ERROR;
break;
}
if (dce_call->fault_code != 0) {
dcerpc_log_packet(dce_call->conn->packet_log_dir,
&ndr_table_$name, opnum, NDR_IN,
&dce_call->pkt.u.request.stub_and_verifier);
return NT_STATUS_NET_WRITE_FAULT;
}
return NT_STATUS_OK;
}
static NTSTATUS $name\__op_reply(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, void *r)
{
uint16_t opnum = dce_call->pkt.u.request.opnum;
switch (opnum) {
";
gen_reply_switch($interface);
pidl "
default:
dce_call->fault_code = DCERPC_FAULT_OP_RNG_ERROR;
break;
}
if (dce_call->fault_code != 0) {
dcerpc_log_packet(dce_call->conn->packet_log_dir,
&ndr_table_$name, opnum, NDR_IN,
&dce_call->pkt.u.request.stub_and_verifier);
return NT_STATUS_NET_WRITE_FAULT;
}
return NT_STATUS_OK;
}
static NTSTATUS $name\__op_ndr_push(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx, struct ndr_push *push, const void *r)
{
enum ndr_err_code ndr_err;
uint16_t opnum = dce_call->pkt.u.request.opnum;
ndr_err = ndr_table_$name.calls[opnum].ndr_push(push, NDR_OUT, r);
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
dce_call->fault_code = DCERPC_FAULT_NDR;
return NT_STATUS_NET_WRITE_FAULT;
}
return NT_STATUS_OK;
}
static const struct dcesrv_interface dcesrv\_$name\_interface = {
.name = \"$name\",
.syntax_id = {".print_uuid($uuid).",$if_version},
.bind = $name\__op_bind,
.unbind = $name\__op_unbind,
.ndr_pull = $name\__op_ndr_pull,
.dispatch = $name\__op_dispatch,
.reply = $name\__op_reply,
.ndr_push = $name\__op_ndr_push,
#ifdef DCESRV_INTERFACE_$uname\_FLAGS
.flags = DCESRV_INTERFACE_$uname\_FLAGS
#else
.flags = 0
#endif
};
";
}
#####################################################################
# produce boilerplate code for an endpoint server
sub Boilerplate_Ep_Server($)
{
my($interface) = shift;
my $name = $interface->{NAME};
my $uname = uc $name;
pidl "
static NTSTATUS $name\__op_init_server(struct dcesrv_context *dce_ctx, const struct dcesrv_endpoint_server *ep_server)
{
int i;
for (i=0;i<ndr_table_$name.endpoints->count;i++) {
NTSTATUS ret;
const char *name = ndr_table_$name.endpoints->names[i];
ret = dcesrv_interface_register(dce_ctx, name, &dcesrv_$name\_interface, NULL);
if (!NT_STATUS_IS_OK(ret)) {
DEBUG(1,(\"$name\_op_init_server: failed to register endpoint \'%s\'\\n\",name));
return ret;
}
}
return NT_STATUS_OK;
}
static bool $name\__op_interface_by_uuid(struct dcesrv_interface *iface, const struct GUID *uuid, uint32_t if_version)
{
if (dcesrv_$name\_interface.syntax_id.if_version == if_version &&
GUID_equal(\&dcesrv\_$name\_interface.syntax_id.uuid, uuid)) {
memcpy(iface,&dcesrv\_$name\_interface, sizeof(*iface));
return true;
}
return false;
}
static bool $name\__op_interface_by_name(struct dcesrv_interface *iface, const char *name)
{
if (strcmp(dcesrv_$name\_interface.name, name)==0) {
memcpy(iface, &dcesrv_$name\_interface, sizeof(*iface));
return true;
}
return false;
}
NTSTATUS dcerpc_server_$name\_init(TALLOC_CTX *ctx)
{
NTSTATUS ret;
static const struct dcesrv_endpoint_server ep_server = {
/* fill in our name */
.name = \"$name\",
/* fill in all the operations */
#ifdef DCESRV_INTERFACE_$uname\_INIT_SERVER
.init_server = DCESRV_INTERFACE_$uname\_INIT_SERVER,
#else
.init_server = $name\__op_init_server,
#endif
.interface_by_uuid = $name\__op_interface_by_uuid,
.interface_by_name = $name\__op_interface_by_name
};
/* register ourselves with the DCERPC subsystem. */
ret = dcerpc_register_ep_server(&ep_server);
if (!NT_STATUS_IS_OK(ret)) {
DEBUG(0,(\"Failed to register \'$name\' endpoint server!\\n\"));
return ret;
}
return ret;
}
";
}
#####################################################################
# dcerpc server boilerplate from a parsed IDL structure
sub ParseInterface($)
{
my($interface) = shift;
my $count = 0;
$res .= "NTSTATUS dcerpc_server_$interface->{NAME}\_init(TALLOC_CTX *);\n";
$res .= "\n";
if (!defined $interface->{PROPERTIES}->{uuid}) {
return $res;
}
if (!defined $interface->{PROPERTIES}->{version}) {
$interface->{PROPERTIES}->{version} = "0.0";
}
foreach my $fn (@{$interface->{FUNCTIONS}}) {
if (defined($fn->{OPNUM})) { $count++; }
}
if ($count == 0) {
return $res;
}
$res .= "/* $interface->{NAME} - dcerpc server boilerplate generated by pidl */\n\n";
Boilerplate_Iface($interface);
Boilerplate_Ep_Server($interface);
return $res;
}
sub Parse($$)
{
my($ndr,$header) = @_;
$res = "";
$res .= "/* server functions auto-generated by pidl */\n";
$res .= "#include \"$header\"\n";
$res .= "#include <util/debug.h>\n";
$res .= "\n";
foreach my $x (@{$ndr}) {
ParseInterface($x) if ($x->{TYPE} eq "INTERFACE" and not defined($x->{PROPERTIES}{object}));
}
return $res;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Wireshark/Conformance.pm | ###################################################
# parse an Wireshark conformance file
# Copyright [email protected] 2005
# released under the GNU GPL
=pod
=head1 NAME
Parse::Pidl::Wireshark::Conformance - Conformance file parser for Wireshark
=head1 DESCRIPTION
This module supports parsing Wireshark conformance files (*.cnf).
=head1 FILE FORMAT
Pidl needs additional data for Wireshark output. This data is read from
so-called conformance files. This section describes the format of these
files.
Conformance files are simple text files with a single command on each line.
Empty lines and lines starting with a '#' character are ignored.
Arguments to commands are separated by spaces.
The following commands are currently supported:
=over 4
=item I<TYPE> name dissector ft_type base_type mask valsstring alignment
Register new data type with specified name, what dissector function to call
and what properties to give header fields for elements of this type.
=item I<NOEMIT> type
Suppress emitting a dissect_type function for the specified type
=item I<PARAM_VALUE> type param
Set parameter to specify to dissector function for given type.
=item I<HF_FIELD> hf title filter ft_type base_type valsstring mask description
Generate a custom header field with specified properties.
=item I<HF_RENAME> old_hf_name new_hf_name
Force the use of new_hf_name when the parser generator was going to
use old_hf_name.
This can be used in conjunction with HF_FIELD in order to make more than
one element use the same filter name.
=item I<ETT_FIELD> ett
Register a custom ett field
=item I<STRIP_PREFIX> prefix
Remove the specified prefix from all function names (if present).
=item I<PROTOCOL> longname shortname filtername
Change the short-, long- and filter-name for the current interface in
Wireshark.
=item I<FIELD_DESCRIPTION> field desc
Change description for the specified header field. `field' is the hf name of the field.
=item I<IMPORT> dissector code...
Code to insert when generating the specified dissector. @HF@ and
@PARAM@ will be substituted.
=item I<INCLUDE> filename
Include conformance data from the specified filename in the dissector.
=item I<TFS> hf_name "true string" "false string"
Override the text shown when a bitmap boolean value is enabled or disabled.
=item I<MANUAL> fn_name
Force pidl to not generate a particular function but allow the user
to write a function manually. This can be used to remove the function
for only one level for a particular element rather than all the functions and
ett/hf variables for a particular element as the NOEMIT command does.
=item I<CODE START>/I<CODE END>
Begin and end a section of code to be put directly into the generated
source file for the dissector.
=item I<HEADER START>/I<HEADER END>
Begin and end a section of code to be put directly into the generated
header file for the dissector.
=back
=head1 EXAMPLE
INFO_KEY OpenKey.Ke
=cut
package Parse::Pidl::Wireshark::Conformance;
require Exporter;
use vars qw($VERSION);
$VERSION = '0.01';
@ISA = qw(Exporter);
@EXPORT_OK = qw(ReadConformance ReadConformanceFH valid_ft_type valid_base_type);
use strict;
use Parse::Pidl qw(fatal warning error);
use Parse::Pidl::Util qw(has_property);
use Parse::Pidl::Typelist qw(addType);
sub handle_type($$$$$$$$$$)
{
my ($pos,$data,$name,$dissectorname,$ft_type,$base_type,$mask,$valsstring,$alignment) = @_;
unless(defined($alignment)) {
error($pos, "incomplete TYPE command");
return;
}
unless ($dissectorname =~ /.*dissect_.*/) {
warning($pos, "dissector name does not contain `dissect'");
}
unless(valid_ft_type($ft_type)) {
warning($pos, "invalid FT_TYPE `$ft_type'");
}
unless (valid_base_type($base_type)) {
warning($pos, "invalid BASE_TYPE `$base_type'");
}
$dissectorname =~ s/^\"(.*)\"$/$1/g;
if (not ($dissectorname =~ /;$/)) {
warning($pos, "missing semicolon");
}
$data->{types}->{$name} = {
NAME => $name,
POS => $pos,
USED => 0,
DISSECTOR_NAME => $dissectorname,
FT_TYPE => $ft_type,
BASE_TYPE => $base_type,
MASK => $mask,
VALSSTRING => $valsstring,
ALIGNMENT => $alignment
};
addType({
NAME => $name,
TYPE => "CONFORMANCE",
BASEFILE => "conformance file",
DATA => {
NAME => $name,
TYPE => "CONFORMANCE",
ALIGN => $alignment
}
});
}
sub handle_tfs($$$$$)
{
my ($pos,$data,$hf,$trues,$falses) = @_;
unless(defined($falses)) {
error($pos, "incomplete TFS command");
return;
}
$data->{tfs}->{$hf} = {
TRUE_STRING => $trues,
FALSE_STRING => $falses
};
}
sub handle_hf_rename($$$$)
{
my ($pos,$data,$old,$new) = @_;
unless(defined($new)) {
warning($pos, "incomplete HF_RENAME command");
return;
}
$data->{hf_renames}->{$old} = {
OLDNAME => $old,
NEWNAME => $new,
POS => $pos,
USED => 0
};
}
sub handle_param_value($$$$)
{
my ($pos,$data,$dissector_name,$value) = @_;
unless(defined($value)) {
error($pos, "incomplete PARAM_VALUE command");
return;
}
$data->{dissectorparams}->{$dissector_name} = {
DISSECTOR => $dissector_name,
PARAM => $value,
POS => $pos,
USED => 0
};
}
sub valid_base_type($)
{
my $t = shift;
return 0 unless($t =~ /^BASE_.*/);
return 1;
}
sub valid_ft_type($)
{
my $t = shift;
return 0 unless($t =~ /^FT_.*/);
return 1;
}
sub handle_hf_field($$$$$$$$$$)
{
my ($pos,$data,$index,$name,$filter,$ft_type,$base_type,$valsstring,$mask,$blurb) = @_;
unless(defined($blurb)) {
error($pos, "incomplete HF_FIELD command");
return;
}
unless(valid_ft_type($ft_type)) {
warning($pos, "invalid FT_TYPE `$ft_type'");
}
unless(valid_base_type($base_type)) {
warning($pos, "invalid BASE_TYPE `$base_type'");
}
$data->{header_fields}->{$index} = {
INDEX => $index,
POS => $pos,
USED => 0,
NAME => $name,
FILTER => $filter,
FT_TYPE => $ft_type,
BASE_TYPE => $base_type,
VALSSTRING => $valsstring,
MASK => $mask,
BLURB => $blurb
};
}
sub handle_strip_prefix($$$)
{
my ($pos,$data,$x) = @_;
push (@{$data->{strip_prefixes}}, $x);
}
sub handle_noemit($$$)
{
my ($pos,$data,$type) = @_;
if (defined($type)) {
$data->{noemit}->{$type} = 1;
} else {
$data->{noemit_dissector} = 1;
}
}
sub handle_manual($$$)
{
my ($pos,$data,$fn) = @_;
unless(defined($fn)) {
warning($pos, "incomplete MANUAL command");
return;
}
$data->{manual}->{$fn} = 1;
}
sub handle_protocol($$$$$$)
{
my ($pos, $data, $name, $longname, $shortname, $filtername) = @_;
$data->{protocols}->{$name} = {
LONGNAME => $longname,
SHORTNAME => $shortname,
FILTERNAME => $filtername
};
}
sub handle_fielddescription($$$$)
{
my ($pos,$data,$field,$desc) = @_;
unless(defined($desc)) {
warning($pos, "incomplete FIELD_DESCRIPTION command");
return;
}
$data->{fielddescription}->{$field} = {
DESCRIPTION => $desc,
POS => $pos,
USED => 0
};
}
sub handle_import
{
my $pos = shift @_;
my $data = shift @_;
my $dissectorname = shift @_;
unless(defined($dissectorname)) {
error($pos, "no dissectorname specified");
return;
}
$data->{imports}->{$dissectorname} = {
NAME => $dissectorname,
DATA => join(' ', @_),
USED => 0,
POS => $pos
};
}
sub handle_ett_field
{
my $pos = shift @_;
my $data = shift @_;
my $ett = shift @_;
unless(defined($ett)) {
error($pos, "incomplete ETT_FIELD command");
return;
}
push (@{$data->{ett}}, $ett);
}
sub handle_include
{
my $pos = shift @_;
my $data = shift @_;
my $fn = shift @_;
unless(defined($fn)) {
error($pos, "incomplete INCLUDE command");
return;
}
ReadConformance($fn, $data);
}
my %field_handlers = (
TYPE => \&handle_type,
NOEMIT => \&handle_noemit,
MANUAL => \&handle_manual,
PARAM_VALUE => \&handle_param_value,
HF_FIELD => \&handle_hf_field,
HF_RENAME => \&handle_hf_rename,
ETT_FIELD => \&handle_ett_field,
TFS => \&handle_tfs,
STRIP_PREFIX => \&handle_strip_prefix,
PROTOCOL => \&handle_protocol,
FIELD_DESCRIPTION => \&handle_fielddescription,
IMPORT => \&handle_import,
INCLUDE => \&handle_include
);
sub ReadConformance($$)
{
my ($f,$data) = @_;
my $ret;
open(IN,"<$f") or return undef;
$ret = ReadConformanceFH(*IN, $data, $f);
close(IN);
return $ret;
}
sub ReadConformanceFH($$$)
{
my ($fh,$data,$f) = @_;
my $incodeblock = 0;
my $inheaderblock = 0;
my $ln = 0;
foreach (<$fh>) {
$ln++;
next if (/^#.*$/);
next if (/^$/);
s/[\r\n]//g;
if ($_ eq "CODE START") {
if ($incodeblock) {
warning({ FILE => $f, LINE => $ln },
"CODE START inside CODE section");
}
if ($inheaderblock) {
error({ FILE => $f, LINE => $ln },
"CODE START inside HEADER section");
return undef;
}
$incodeblock = 1;
next;
} elsif ($_ eq "CODE END") {
if (!$incodeblock) {
warning({ FILE => $f, LINE => $ln },
"CODE END outside CODE section");
}
if ($inheaderblock) {
error({ FILE => $f, LINE => $ln },
"CODE END inside HEADER section");
return undef;
}
$incodeblock = 0;
next;
} elsif ($incodeblock) {
if (exists $data->{override}) {
$data->{override}.="$_\n";
} else {
$data->{override} = "$_\n";
}
next;
} elsif ($_ eq "HEADER START") {
if ($inheaderblock) {
warning({ FILE => $f, LINE => $ln },
"HEADER START inside HEADER section");
}
if ($incodeblock) {
error({ FILE => $f, LINE => $ln },
"HEADER START inside CODE section");
return undef;
}
$inheaderblock = 1;
next;
} elsif ($_ eq "HEADER END") {
if (!$inheaderblock) {
warning({ FILE => $f, LINE => $ln },
"HEADER END outside HEADER section");
}
if ($incodeblock) {
error({ FILE => $f, LINE => $ln },
"CODE END inside HEADER section");
return undef;
}
$inheaderblock = 0;
next;
} elsif ($inheaderblock) {
if (exists $data->{header}) {
$data->{header}.="$_\n";
} else {
$data->{header} = "$_\n";
}
next;
}
my @fields = /([^ "]+|"[^"]+")/g;
my $cmd = $fields[0];
shift @fields;
my $pos = { FILE => $f, LINE => $ln };
next unless(defined($cmd));
if (not defined($field_handlers{$cmd})) {
warning($pos, "Unknown command `$cmd'");
next;
}
$field_handlers{$cmd}($pos, $data, @fields);
}
if ($incodeblock) {
warning({ FILE => $f, LINE => $ln },
"Expecting CODE END");
return undef;
}
return 1;
}
1; |
|
wireshark/tools/pidl/lib/Parse/Pidl/Wireshark/NDR.pm | ##################################################
# Wireshark NDR parser generator for IDL structures
# Copyright [email protected] 2000-2003
# Copyright [email protected] 2001,2005
# Copyright [email protected] 2004-2007
# Portions based on idl2eth.c by Ronnie Sahlberg
# released under the GNU GPL
=pod
=head1 NAME
Parse::Pidl::Wireshark::NDR - Parser generator for Wireshark
=cut
package Parse::Pidl::Wireshark::NDR;
use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(field2name %res PrintIdl StripPrefixes RegisterInterfaceHandoff register_hf_field CheckUsed ProcessImport ProcessInclude find_type DumpEttList DumpEttDeclaration DumpHfList DumpHfDeclaration DumpFunctionTable register_type register_ett);
use strict;
use Parse::Pidl qw(error warning);
use Parse::Pidl::Typelist qw(getType);
use Parse::Pidl::Util qw(has_property property_matches make_str);
use Parse::Pidl::NDR qw(ContainsString GetNextLevel);
use Parse::Pidl::Dump qw(DumpType DumpFunction);
use Parse::Pidl::Wireshark::Conformance qw(ReadConformance);
use File::Basename;
use vars qw($VERSION);
$VERSION = '0.01';
my %return_types = ();
my %dissector_used = ();
my %ptrtype_mappings = (
"unique" => "NDR_POINTER_UNIQUE",
"ref" => "NDR_POINTER_REF",
"ptr" => "NDR_POINTER_PTR"
);
sub StripPrefixes($$)
{
my ($s, $prefixes) = @_;
foreach (@$prefixes) {
$s =~ s/^$_\_//g;
}
return $s;
}
# Convert a IDL structure field name (e.g access_mask) to a prettier
# string like 'Access Mask'.
sub field2name($)
{
my($field) = shift;
$field =~ s/^(_)*//g; # Remove any starting underscores
$field =~ s/_/ /g; # Replace underscores with spaces
$field =~ s/(\w+)/\u$1/g; # Capitalise each word
return $field;
}
sub new($)
{
my ($class) = @_;
my $self = {res => {hdr => "", def => "", code => ""}, tabs => "", cur_fn => undef,
hf_used => {}, ett => [], conformance => undef
};
bless($self, $class);
}
sub pidl_fn_start($$)
{
my ($self, $fn) = @_;
$self->{cur_fn} = $fn;
}
sub pidl_fn_end($$)
{
my ($self, $fn) = @_;
die("Inconsistent state: $fn != $self->{cur_fn}") if ($fn ne $self->{cur_fn});
$self->{cur_fn} = undef;
}
sub pidl_code($$)
{
my ($self, $d) = @_;
return if (defined($self->{cur_fn}) and defined($self->{conformance}->{manual}->{$self->{cur_fn}}));
if ($d) {
$self->{res}->{code} .= $self->{tabs};
$self->{res}->{code} .= $d;
}
$self->{res}->{code} .="\n";
}
sub pidl_hdr($$) { my ($self,$x) = @_; $self->{res}->{hdr} .= "$x\n"; }
sub pidl_def($$) { my ($self,$x) = @_; $self->{res}->{def} .= "$x\n"; }
sub indent($)
{
my ($self) = @_;
$self->{tabs} .= "\t";
}
sub deindent($)
{
my ($self) = @_;
$self->{tabs} = substr($self->{tabs}, 0, -1);
}
sub PrintIdl($$)
{
my ($self, $idl) = @_;
foreach (split /\n/, $idl) {
$self->pidl_code("/* IDL: $_ */");
}
$self->pidl_code("");
}
#####################################################################
# parse the interface definitions
sub Interface($$)
{
my($self, $interface) = @_;
$self->Const($_,$interface->{NAME}) foreach (@{$interface->{CONSTS}});
$self->Type($_, $_->{NAME}, $interface->{NAME}) foreach (@{$interface->{TYPES}});
$self->Function($_,$interface->{NAME}) foreach (@{$interface->{FUNCTIONS}});
}
sub Enum($$$$)
{
my ($self, $e,$name,$ifname) = @_;
my $valsstring = "$ifname\_$name\_vals";
my $dissectorname = "$ifname\_dissect\_enum\_".StripPrefixes($name, $self->{conformance}->{strip_prefixes});
return if (defined($self->{conformance}->{noemit}->{StripPrefixes($name, $self->{conformance}->{strip_prefixes})}));
foreach (@{$e->{ELEMENTS}}) {
if (/([^=]*)=(.*)/) {
$self->pidl_hdr("#define $1 ($2)");
}
}
$self->pidl_hdr("extern const value_string $valsstring\[];");
$self->pidl_hdr("int $dissectorname(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, g$e->{BASE_TYPE} *param _U_);");
$self->pidl_def("const value_string ".$valsstring."[] = {");
foreach (@{$e->{ELEMENTS}}) {
next unless (/([^=]*)=(.*)/);
$self->pidl_def("\t{ $1, \"$1\" },");
}
$self->pidl_def("{ 0, NULL }");
$self->pidl_def("};");
$self->pidl_fn_start($dissectorname);
$self->pidl_code("int");
$self->pidl_code("$dissectorname(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, g$e->{BASE_TYPE} *param _U_)");
$self->pidl_code("{");
$self->indent;
$self->pidl_code("g$e->{BASE_TYPE} parameter=0;");
$self->pidl_code("if (param) {");
$self->indent;
$self->pidl_code("parameter = *param;");
$self->deindent;
$self->pidl_code("}");
$self->pidl_code("offset = dissect_ndr_$e->{BASE_TYPE}(tvb, offset, pinfo, tree, di, drep, hf_index, ¶meter);");
$self->pidl_code("if (param) {");
$self->indent;
$self->pidl_code("*param = parameter;");
$self->deindent;
$self->pidl_code("}");
$self->pidl_code("return offset;");
$self->deindent;
$self->pidl_code("}\n");
$self->pidl_fn_end($dissectorname);
my $enum_size = $e->{BASE_TYPE};
$enum_size =~ s/uint//g;
$self->register_type($name, "offset = $dissectorname(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);", "FT_UINT$enum_size", "BASE_DEC", "0", "VALS($valsstring)", $enum_size / 8);
}
sub Pipe($$$$)
{
my ($self,$e,$name,$ifname) = @_;
error($e->{ORIGINAL}, "Pipe not yet supported");
return;
}
sub Bitmap($$$$)
{
my ($self,$e,$name,$ifname) = @_;
my $dissectorname = "$ifname\_dissect\_bitmap\_".StripPrefixes($name, $self->{conformance}->{strip_prefixes});
my $element_count = 0;
my $total_ev = 0;
$self->register_ett("ett_$ifname\_$name");
$self->pidl_hdr("int $dissectorname(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);");
$self->pidl_fn_start($dissectorname);
$self->pidl_code("int");
$self->pidl_code("$dissectorname(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_)");
$self->pidl_code("{");
$self->indent;
foreach (@{$e->{ELEMENTS}}) {
next unless (/([^ ]*) (.*)/);
$element_count++;
}
if ($element_count > 0) {
$self->pidl_code("proto_item *item;");
$self->pidl_code("static int * const $ifname\_$name\_fields[] = {");
$self->indent;
foreach (@{$e->{ELEMENTS}}) {
next unless (/([^ ]*) (.*)/);
my ($en,$ev) = ($1,$2);
my $hf_bitname = "hf_$ifname\_$name\_$1";
$ev =~ s/[()\s]//g;
if (hex($ev) != 0) {
$total_ev += hex($ev);
$self->pidl_code("&$hf_bitname,");
}
}
$self->pidl_code("NULL");
$self->deindent;
$self->pidl_code("};");
}
$self->pidl_code("g$e->{BASE_TYPE} flags;");
if ($e->{ALIGN} > 1) {
$self->pidl_code("ALIGN_TO_$e->{ALIGN}_BYTES;");
}
$self->pidl_code("");
if ($element_count > 0) {
$self->pidl_code("item = proto_tree_add_bitmask_with_flags(parent_tree, tvb, offset, hf_index,");
$self->pidl_code("\t\t\tett_$ifname\_$name, $ifname\_$name\_fields, DREP_ENC_INTEGER(drep), BMT_NO_FALSE);");
$self->pidl_code("");
$self->pidl_code("offset = dissect_ndr_$e->{BASE_TYPE}(tvb, offset, pinfo, parent_tree, di, drep, -1, &flags);");
$self->pidl_code("");
$self->pidl_code("if (!flags)");
$self->pidl_code("\tproto_item_append_text(item, \": (No values set)\");\n");
} else {
$self->pidl_code("proto_tree_add_item(parent_tree, hf_index, tvb, offset, $e->{ALIGN}, DREP_ENC_INTEGER(drep));");
$self->pidl_code("");
$self->pidl_code("offset = dissect_ndr_$e->{BASE_TYPE}(tvb, offset, pinfo, parent_tree, di, drep, -1, &flags);");
$self->pidl_code("");
}
foreach (@{$e->{ELEMENTS}}) {
next unless (/([^ ]*) (.*)/);
my ($en,$ev) = ($1,$2);
my $hf_bitname = "hf_$ifname\_$name\_$en";
my $filtername = "$ifname\.$name\.$en";
$self->{hf_used}->{$hf_bitname} = 1;
$ev =~ s/[()\s]//g;
if (hex($ev) != 0) {
$self->register_hf_field($hf_bitname, field2name($en), $filtername, "FT_BOOLEAN", $e->{ALIGN} * 8, "TFS(&$name\_$en\_tfs)", "( $ev )", "");
$self->pidl_def("static const true_false_string $name\_$en\_tfs = {");
if (defined($self->{conformance}->{tfs}->{$hf_bitname})) {
$self->pidl_def(" $self->{conformance}->{tfs}->{$hf_bitname}->{TRUE_STRING},");
$self->pidl_def(" $self->{conformance}->{tfs}->{$hf_bitname}->{FALSE_STRING},");
$self->{conformance}->{tfs}->{$hf_bitname}->{USED} = 1;
} else {
$self->pidl_def(" \"$en is SET\",");
$self->pidl_def(" \"$en is NOT SET\",");
}
$self->pidl_def("};");
}
}
if ($element_count > 0) {
my $total_ev_hex = sprintf("0x%08x", $total_ev);
$self->pidl_code("if (flags & (~$total_ev_hex)) {");
$self->pidl_code("\tflags &= (~$total_ev_hex);");
$self->pidl_code("\tproto_item_append_text(item, \"Unknown bitmap value 0x%x\", flags);");
$self->pidl_code("}\n");
}
$self->pidl_code("return offset;");
$self->deindent;
$self->pidl_code("}\n");
$self->pidl_fn_end($dissectorname);
my $size = $e->{BASE_TYPE};
$size =~ s/uint//g;
$self->register_type($name, "offset = $dissectorname(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);", "FT_UINT$size", "BASE_HEX", "0", "NULL", $size/8);
}
sub ElementLevel($$$$$$$$)
{
my ($self,$e,$l,$hf,$myname,$pn,$ifname,$param) = @_;
if (defined($self->{conformance}->{dissectorparams}->{$myname})) {
$param = $self->{conformance}->{dissectorparams}->{$myname}->{PARAM};
}
if ($l->{TYPE} eq "POINTER") {
my $type;
if ($l->{LEVEL} eq "TOP") {
$type = "toplevel";
} elsif ($l->{LEVEL} eq "EMBEDDED") {
$type = "embedded";
}
$self->pidl_code("offset = dissect_ndr_$type\_pointer(tvb, offset, pinfo, tree, di, drep, $myname\_, $ptrtype_mappings{$l->{POINTER_TYPE}}, \"Pointer to ".field2name(StripPrefixes($e->{NAME}, $self->{conformance}->{strip_prefixes})) . " ($e->{TYPE})\",$hf);");
} elsif ($l->{TYPE} eq "ARRAY") {
if ($l->{IS_INLINE}) {
error($e->{ORIGINAL}, "Inline arrays not supported");
} elsif ($l->{IS_FIXED}) {
$self->pidl_code("int i;");
$self->pidl_code("for (i = 0; i < $l->{SIZE_IS}; i++)");
$self->pidl_code("\toffset = $myname\_(tvb, offset, pinfo, tree, di, drep);");
} else {
my $type = "";
$type .= "c" if ($l->{IS_CONFORMANT});
$type .= "v" if ($l->{IS_VARYING});
unless ($l->{IS_ZERO_TERMINATED}) {
$self->pidl_code("offset = dissect_ndr_u" . $type . "array(tvb, offset, pinfo, tree, di, drep, $myname\_);");
} else {
my $nl = GetNextLevel($e,$l);
$self->pidl_code("char *data;");
$self->pidl_code("");
$self->pidl_code("offset = dissect_ndr_$type" . "string(tvb, offset, pinfo, tree, di, drep, sizeof(g$nl->{DATA_TYPE}), $hf, FALSE, &data);");
$self->pidl_code("proto_item_append_text(tree, \": %s\", data);");
}
}
} elsif ($l->{TYPE} eq "DATA") {
if ($l->{DATA_TYPE} eq "string") {
my $bs = 2; # Byte size defaults to that of UCS2
($bs = 1) if (property_matches($e, "flag", ".*LIBNDR_FLAG_STR_ASCII.*"));
if (property_matches($e, "flag", ".*LIBNDR_FLAG_STR_SIZE4.*") and property_matches($e, "flag", ".*LIBNDR_FLAG_STR_LEN4.*")) {
$self->pidl_code("char *data;\n");
$self->pidl_code("offset = dissect_ndr_cvstring(tvb, offset, pinfo, tree, di, drep, $bs, $hf, FALSE, &data);");
$self->pidl_code("proto_item_append_text(tree, \": %s\", data);");
} elsif (property_matches($e, "flag", ".*LIBNDR_FLAG_STR_SIZE4.*")) {
$self->pidl_code("offset = dissect_ndr_vstring(tvb, offset, pinfo, tree, di, drep, $bs, $hf, FALSE, NULL);");
} elsif (property_matches($e, "flag", ".*STR_NULLTERM.*")) {
if ($bs == 2) {
$self->pidl_code("offset = dissect_null_term_wstring(tvb, offset, pinfo, tree, drep, $hf , 0);")
} else {
$self->pidl_code("offset = dissect_null_term_string(tvb, offset, pinfo, tree, drep, $hf , 0);")
}
} else {
warn("Unable to handle string with flags $e->{PROPERTIES}->{flag}");
}
} elsif ($l->{DATA_TYPE} eq "DATA_BLOB") {
my $remain = 0;
$remain = 1 if (property_matches($e->{ORIGINAL}, "flag", ".*LIBNDR_FLAG_REMAINING.*"));
$self->pidl_code("offset = dissect_ndr_datablob(tvb, offset, pinfo, tree, di, drep, $hf, $remain);");
} else {
my $call;
if ($self->{conformance}->{imports}->{$l->{DATA_TYPE}}) {
$call = $self->{conformance}->{imports}->{$l->{DATA_TYPE}}->{DATA};
$self->{conformance}->{imports}->{$l->{DATA_TYPE}}->{USED} = 1;
} elsif (defined($self->{conformance}->{imports}->{"$pn.$e->{NAME}"})) {
$call = $self->{conformance}->{imports}->{"$pn.$e->{NAME}"}->{DATA};
$self->{conformance}->{imports}->{"$pn.$e->{NAME}"}->{USED} = 1;
} elsif (defined($self->{conformance}->{types}->{$l->{DATA_TYPE}})) {
$call= $self->{conformance}->{types}->{$l->{DATA_TYPE}}->{DISSECTOR_NAME};
$self->{conformance}->{types}->{$l->{DATA_TYPE}}->{USED} = 1;
} else {
my $t;
if (ref($l->{DATA_TYPE}) eq "HASH" ) {
$t = "$l->{DATA_TYPE}->{TYPE}_$l->{DATA_TYPE}->{NAME}";
} else {
$t = $l->{DATA_TYPE};
}
$self->pidl_code("offset = $ifname\_dissect_struct_" . $t . "(tvb,offset,pinfo,tree,di,drep,$hf,$param);");
return;
}
$call =~ s/\@HF\@/$hf/g;
$call =~ s/\@PARAM\@/$param/g;
$self->pidl_code($call);
}
} elsif ($_->{TYPE} eq "SUBCONTEXT") {
my $varswitch;
if (has_property($e, "switch_is")) {
$varswitch = $e->{PROPERTIES}->{switch_is};
}
my $num_bits = ($l->{HEADER_SIZE}*8);
my $hf2 = $self->register_hf_field($hf."_", "Subcontext length", "$ifname.$pn.$_->{NAME}subcontext", "FT_UINT$num_bits", "BASE_HEX", "NULL", 0, "");
$num_bits = 3264 if ($num_bits == 32);
$self->{hf_used}->{$hf2} = 1;
$self->pidl_code("guint$num_bits size;");
$self->pidl_code("int conformant = di->conformant_run;");
$self->pidl_code("tvbuff_t *subtvb;");
$self->pidl_code("");
# We need to be able to dissect the length of the context in every case
# and conformant run skips the dissections of scalars ...
$self->pidl_code("if (!conformant) {");
$self->indent;
$self->pidl_code("guint32 saved_flags = di->call_data->flags;");
$self->pidl_code("offset = dissect_ndr_uint$num_bits(tvb, offset, pinfo, tree, di, drep, $hf2, &size);");
# This is a subcontext, there is normally no such thing as
# 64 bit NDR is subcontext so we clear the flag so that we can
# continue to dissect handmarshalled stuff with pidl
$self->pidl_code("di->call_data->flags &= ~DCERPC_IS_NDR64;");
$self->pidl_code("subtvb = tvb_new_subset_length_caplen(tvb, offset, (const gint)size, -1);");
if ($param ne 0) {
$self->pidl_code("$myname\_(subtvb, 0, pinfo, tree, di, drep, $param);");
} else {
$self->pidl_code("$myname\_(subtvb, 0, pinfo, tree, di, drep);");
}
$self->pidl_code("offset += (int)size;");
$self->pidl_code("di->call_data->flags = saved_flags;");
$self->deindent;
$self->pidl_code("}");
} elsif ($_->{TYPE} eq "PIPE") {
error($e->{ORIGINAL}, "Type PIPE not yet supported");
} else {
die("Unknown type `$_->{TYPE}'");
}
}
sub SwitchType($$;$)
{
my ($e, $type, $nodiscriminant) = @_;
my $switch_dt = getType($type);
my $switch_type = undef;
if ($switch_dt->{DATA}->{TYPE} eq "ENUM") {
$switch_type = Parse::Pidl::Typelist::enum_type_fn($switch_dt->{DATA});
} elsif ($switch_dt->{DATA}->{TYPE} eq "BITMAP") {
$switch_type = Parse::Pidl::Typelist::bitmap_type_fn($switch_dt->{DATA});
} elsif ($switch_dt->{DATA}->{TYPE} eq "SCALAR") {
if (defined $e->{SWITCH_TYPE}) {
$switch_type = "$e->{SWITCH_TYPE}";
} else {
$switch_type = "$switch_dt->{DATA}->{NAME}";
}
} elsif (not defined $e->{SWITCH_TYPE}) {
$switch_type = $nodiscriminant;
}
return $switch_type
}
sub Element($$$$$$)
{
my ($self,$e,$pn,$ifname,$isoruseswitch,%switchvars) = @_;
my $dissectorname = "$ifname\_dissect\_element\_".StripPrefixes($pn, $self->{conformance}->{strip_prefixes})."\_".StripPrefixes($e->{NAME}, $self->{conformance}->{strip_prefixes});
my ($call_code, $moreparam);
my $param = 0;
if (defined $isoruseswitch) {
my $type = $isoruseswitch->[0];
my $name = $isoruseswitch->[1];
my $switch_dt = getType($type);
my $switch_raw_type = SwitchType($e, $type, "uint32");
if (not defined($switch_raw_type)) {
die("Unknown type[$type]\n");
}
my $switch_type = "g${switch_raw_type}";
if ($name ne "") {
$moreparam = ", $switch_type *".$name;
} else {
$moreparam = "";
}
if (($e->{PROPERTIES}->{switch_is} eq "") && ($switchvars{$name}) &&
#not a "native" type
(!($type =~ /^uint(8|16|1632|32|3264|64)/))) {
$param = $name;
} elsif ( $switch_dt->{DATA}->{TYPE} eq "ENUM") {
$param = $name;
} elsif ($name ne "") {
$param = "*".$name;
}
if ($name ne "") {
$call_code = "offset = $dissectorname(tvb, offset, pinfo, tree, di, drep, &$name);";
} else {
$call_code = "offset = $dissectorname(tvb, offset, pinfo, tree, di, drep);";
}
} else {
$moreparam = "";
$call_code = "offset = $dissectorname(tvb, offset, pinfo, tree, di, drep);";
}
my $type = $self->find_type($e->{TYPE});
if (not defined($type)) {
# default settings
$type = {
MASK => 0,
VALSSTRING => "NULL",
FT_TYPE => "FT_NONE",
BASE_TYPE => "BASE_NONE"
};
}
if (ContainsString($e)) {
$type = {
MASK => 0,
VALSSTRING => "NULL",
FT_TYPE => "FT_STRING",
BASE_TYPE => "BASE_NONE"
};
}
if (property_matches($e, "flag", ".*LIBNDR_FLAG_ALIGN.*")) {
my $align_flag = $e->{PROPERTIES}->{flag};
if ($align_flag =~ m/LIBNDR_FLAG_ALIGN(\d+)/) {
$call_code = "ALIGN_TO_$1_BYTES; ".$call_code;
}
}
my $hf = $self->register_hf_field("hf_$ifname\_$pn\_$e->{NAME}", field2name($e->{NAME}), "$ifname.$pn.$e->{NAME}", $type->{FT_TYPE}, $type->{BASE_TYPE}, $type->{VALSSTRING}, $type->{MASK}, "");
$self->{hf_used}->{$hf} = 1;
my $eltname = StripPrefixes($pn, $self->{conformance}->{strip_prefixes}) . ".$e->{NAME}";
if (defined($self->{conformance}->{noemit}->{$eltname})) {
return $call_code;
}
my $add = "";
my $oldparam = undef;
foreach (@{$e->{LEVELS}}) {
if (defined $_->{SWITCH_IS}) {
$oldparam = $param;
if (($param ne "0") && (!($param =~ /\*/))) {
$param = "*$param";
}
}
next if ($_->{TYPE} eq "SWITCH");
next if (defined($self->{conformance}->{noemit}->{"$dissectorname$add"}));
$self->pidl_def("static int $dissectorname$add(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_$moreparam);");
$self->pidl_fn_start("$dissectorname$add");
$self->pidl_code("static int");
$self->pidl_code("$dissectorname$add(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_$moreparam)");
$self->pidl_code("{");
$self->indent;
$self->ElementLevel($e,$_,$hf,$dissectorname.$add,$pn,$ifname,$param);
if (defined $oldparam) {
$param = $oldparam;
}
$self->pidl_code("");
$self->pidl_code("return offset;");
$self->deindent;
$self->pidl_code("}\n");
$self->pidl_fn_end("$dissectorname$add");
$add.="_";
last if ($_->{TYPE} eq "ARRAY" and $_->{IS_ZERO_TERMINATED});
}
return $call_code;
}
sub Function($$$)
{
my ($self, $fn,$ifname) = @_;
my %dissectornames;
foreach (@{$fn->{ELEMENTS}}) {
$dissectornames{$_->{NAME}} = $self->Element($_, $fn->{NAME}, $ifname, undef, undef) if not defined($dissectornames{$_->{NAME}});
}
my $fn_name = $_->{NAME};
$fn_name =~ s/^${ifname}_//;
$self->PrintIdl(DumpFunction($fn->{ORIGINAL}));
$self->pidl_fn_start("$ifname\_dissect\_$fn_name\_response");
$self->pidl_code("static int");
$self->pidl_code("$ifname\_dissect\_${fn_name}_response(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_)");
$self->pidl_code("{");
$self->indent;
if ( not defined($fn->{RETURN_TYPE})) {
} elsif ($fn->{RETURN_TYPE} eq "NTSTATUS" or $fn->{RETURN_TYPE} eq "WERROR" or $fn->{RETURN_TYPE} eq "HRESULT")
{
$self->pidl_code("guint32 status;\n");
} elsif (my $type = getType($fn->{RETURN_TYPE})) {
if ($type->{DATA}->{TYPE} eq "ENUM") {
$self->pidl_code("g".Parse::Pidl::Typelist::enum_type_fn($type->{DATA}) . " status;\n");
} elsif ($type->{DATA}->{TYPE} eq "SCALAR") {
$self->pidl_code("g$fn->{RETURN_TYPE} status;\n");
} else {
error($fn, "return type `$fn->{RETURN_TYPE}' not yet supported");
}
} else {
error($fn, "unknown return type `$fn->{RETURN_TYPE}'");
}
$self->pidl_code("di->dcerpc_procedure_name=\"${fn_name}\";");
foreach (@{$fn->{ELEMENTS}}) {
if (grep(/out/,@{$_->{DIRECTION}})) {
$self->pidl_code("$dissectornames{$_->{NAME}}");
$self->pidl_code("offset = dissect_deferred_pointers(pinfo, tvb, offset, di, drep);");
$self->pidl_code("");
}
}
if (not defined($fn->{RETURN_TYPE})) {
} elsif ($fn->{RETURN_TYPE} eq "NTSTATUS") {
$self->pidl_code("offset = dissect_ntstatus(tvb, offset, pinfo, tree, di, drep, hf\_$ifname\_status, &status);\n");
$self->pidl_code("if (status != 0)");
$self->pidl_code("\tcol_append_fstr(pinfo->cinfo, COL_INFO, \", Error: %s\", val_to_str(status, NT_errors, \"Unknown NT status 0x%08x\"));\n");
$return_types{$ifname}->{"status"} = ["NTSTATUS", "NT Error"];
} elsif ($fn->{RETURN_TYPE} eq "WERROR") {
$self->pidl_code("offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep, hf\_$ifname\_werror, &status);\n");
$self->pidl_code("if (status != 0)");
$self->pidl_code("\tcol_append_fstr(pinfo->cinfo, COL_INFO, \", Error: %s\", val_to_str(status, WERR_errors, \"Unknown DOS error 0x%08x\"));\n");
$return_types{$ifname}->{"werror"} = ["WERROR", "Windows Error"];
} elsif ($fn->{RETURN_TYPE} eq "HRESULT") {
$self->pidl_code("offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep, hf\_$ifname\_hresult, &status);\n");
$self->pidl_code("if (status != 0)");
$self->pidl_code("\tcol_append_fstr(pinfo->cinfo, COL_INFO, \", Error: %s\", val_to_str(status, HRES_errors, \"Unknown HRES error 0x%08x\"));\n");
$return_types{$ifname}->{"hresult"} = ["HRESULT", "HRES Windows Error"];
} elsif (my $type = getType($fn->{RETURN_TYPE})) {
if ($type->{DATA}->{TYPE} eq "ENUM") {
my $return_type = "g".Parse::Pidl::Typelist::enum_type_fn($type->{DATA});
my $return_dissect = "dissect_ndr_" .Parse::Pidl::Typelist::enum_type_fn($type->{DATA});
$self->pidl_code("offset = $return_dissect(tvb, offset, pinfo, tree, di, drep, hf\_$ifname\_$fn->{RETURN_TYPE}_status, &status);");
$self->pidl_code("if (status != 0)");
$self->pidl_code("\tcol_append_fstr(pinfo->cinfo, COL_INFO, \", Status: %s\", val_to_str(status, $ifname\_$fn->{RETURN_TYPE}\_vals, \"Unknown " . $fn->{RETURN_TYPE} . " error 0x%08x\"));\n");
$return_types{$ifname}->{$fn->{RETURN_TYPE}."_status"} = [$fn->{RETURN_TYPE}, $fn->{RETURN_TYPE}];
} elsif ($type->{DATA}->{TYPE} eq "SCALAR") {
$self->pidl_code("offset = dissect_ndr_$fn->{RETURN_TYPE}(tvb, offset, pinfo, tree, di, drep, hf\_$ifname\_$fn->{RETURN_TYPE}_status, &status);");
$self->pidl_code("if (status != 0)");
$self->pidl_code("\tcol_append_fstr(pinfo->cinfo, COL_INFO, \", Status: %d\", status);\n");
$return_types{$ifname}->{$fn->{RETURN_TYPE}."_status"} = [$fn->{RETURN_TYPE}, $fn->{RETURN_TYPE}];
}
}
$self->pidl_code("return offset;");
$self->deindent;
$self->pidl_code("}\n");
$self->pidl_fn_end("$ifname\_dissect\_$fn_name\_response");
$self->pidl_fn_start("$ifname\_dissect\_$fn_name\_request");
$self->pidl_code("static int");
$self->pidl_code("$ifname\_dissect\_${fn_name}_request(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_)");
$self->pidl_code("{");
$self->indent;
$self->pidl_code("di->dcerpc_procedure_name=\"${fn_name}\";");
foreach (@{$fn->{ELEMENTS}}) {
if (grep(/in/,@{$_->{DIRECTION}})) {
$self->pidl_code("$dissectornames{$_->{NAME}}");
$self->pidl_code("offset = dissect_deferred_pointers(pinfo, tvb, offset, di, drep);");
}
}
$self->pidl_code("return offset;");
$self->deindent;
$self->pidl_code("}\n");
$self->pidl_fn_end("$ifname\_dissect\_$fn_name\_request");
}
sub Struct($$$$)
{
my ($self,$e,$name,$ifname) = @_;
my $dissectorname = "$ifname\_dissect\_struct\_".StripPrefixes($name, $self->{conformance}->{strip_prefixes});
return if (defined($self->{conformance}->{noemit}->{StripPrefixes($name, $self->{conformance}->{strip_prefixes})}));
$self->register_ett("ett_$ifname\_$name");
my $res = "";
my $varswitchs = {};
# will contain the switch var declaration;
my $vars = [];
my %switch_hash;
foreach (@{$e->{ELEMENTS}}) {
if (has_property($_, "switch_is")) {
$varswitchs->{$_->{PROPERTIES}->{switch_is}} = [];
$switch_hash{ $_->{PROPERTIES}->{switch_is}} = $_->{PROPERTIES}->{switch_is};
}
}
foreach (@{$e->{ELEMENTS}}) {
my $switch_info = undef;
my $v = $_->{NAME};
if (scalar(grep {/^$v$/} keys(%$varswitchs)) == 1) {
# This element is one of the switch attribute
my $switch_raw_type = SwitchType($e, $_->{TYPE}, "uint32");
if (not defined($switch_raw_type)) {
die("Unknown type[$_->{TYPE}]\n");
}
my $switch_type = "g${switch_raw_type}";
if ($switch_type ne "") {
push @$vars, "$switch_type $v = 0;";
}
$switch_info = [ $_->{TYPE}, $v ];
$varswitchs->{$v} = $switch_info;
}
if (has_property($_, "switch_is")) {
my $varswitch = $_->{PROPERTIES}->{switch_is};
$switch_info = $varswitchs->{$varswitch};
}
$res.="\t".$self->Element($_, $name, $ifname, $switch_info, %switch_hash)."\n\n";
}
my $doalign = undef;
if ($e->{ALIGN} > 1 and not property_matches($e, "flag", ".*LIBNDR_FLAG_NOALIGN.*")) {
$doalign = 1;
} elsif (property_matches($e, "flag", ".*LIBNDR_FLAG_NOALIGN.*")) {
$doalign = 0;
}
$self->pidl_hdr("int $dissectorname(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);");
$self->pidl_fn_start($dissectorname);
$self->pidl_code("int");
$self->pidl_code("$dissectorname(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_)");
$self->pidl_code("{");
$self->indent;
$self->pidl_code($_) foreach (@$vars);
$self->pidl_code("proto_item *item = NULL;");
if($res) {
$self->pidl_code("proto_tree *tree = NULL;");
}
if (defined($doalign) and $doalign == 0) {
$self->pidl_code("gboolean oldalign = di->no_align;");
}
$self->pidl_code("int old_offset;");
$self->pidl_code("");
if (defined($doalign)) {
if ($doalign == 1) {
$self->pidl_code("ALIGN_TO_$e->{ALIGN}_BYTES;");
}
if ($doalign == 0) {
$self->pidl_code("di->no_align = TRUE;");
}
$self->pidl_code("");
}
$self->pidl_code("old_offset = offset;");
$self->pidl_code("");
$self->pidl_code("if (parent_tree) {");
$self->indent;
$self->pidl_code("item = proto_tree_add_item(parent_tree, hf_index, tvb, offset, -1, ENC_NA);");
if($res) {
$self->pidl_code("tree = proto_item_add_subtree(item, ett_$ifname\_$name);");
}
$self->deindent;
$self->pidl_code("}");
$self->pidl_code("");
$self->deindent;
$self->pidl_code("$res");
$self->indent;
$self->pidl_code("proto_item_set_len(item, offset-old_offset);\n");
if (defined($doalign) and $doalign == 1) {
$self->pidl_code("");
$self->pidl_code("if (di->call_data->flags & DCERPC_IS_NDR64) {");
$self->indent;
$self->pidl_code("ALIGN_TO_$e->{ALIGN}_BYTES;");
$self->deindent;
$self->pidl_code("}");
}
if (defined($doalign) and $doalign == 0) {
$self->pidl_code("");
$self->pidl_code("di->no_align = oldalign;");
}
$self->pidl_code("");
$self->pidl_code("return offset;");
$self->deindent;
$self->pidl_code("}\n");
$self->pidl_fn_end($dissectorname);
$self->register_type($name, "offset = $dissectorname(tvb,offset,pinfo,tree,di,drep,\@HF\@,\@PARAM\@);", "FT_NONE", "BASE_NONE", 0, "NULL", 0);
}
sub Union($$$$)
{
my ($self,$e,$name,$ifname) = @_;
my $dissectorname = "$ifname\_dissect_".StripPrefixes($name, $self->{conformance}->{strip_prefixes});
return if (defined($self->{conformance}->{noemit}->{StripPrefixes($name, $self->{conformance}->{strip_prefixes})}));
$self->register_ett("ett_$ifname\_$name");
my $res = "";
foreach (@{$e->{ELEMENTS}}) {
$res.="\n\t\t$_->{CASE}:\n";
if ($_->{TYPE} ne "EMPTY") {
$res.="\t\t\t".$self->Element($_, $name, $ifname, undef, undef)."\n";
}
$res.="\t\tbreak;\n";
}
my $switch_type = undef;
my $switch_dissect = undef;
my $switch_raw_type = SwitchType($e, $e->{SWITCH_TYPE});
if (defined($switch_raw_type)) {
$switch_type = "g${switch_raw_type}";
$switch_dissect = "dissect_ndr_${switch_raw_type}";
}
$self->pidl_fn_start($dissectorname);
$self->pidl_code("static int");
$self->pidl_code("$dissectorname(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_)");
$self->pidl_code("{");
$self->indent;
$self->pidl_code("proto_item *item = NULL;");
$self->pidl_code("proto_tree *tree = NULL;");
$self->pidl_code("int old_offset;");
if (!defined $switch_type) {
$self->pidl_code("guint32 level = param;");
} else {
$self->pidl_code("$switch_type level;");
}
$self->pidl_code("");
$self->pidl_code("old_offset = offset;");
$self->pidl_code("if (parent_tree) {");
$self->indent;
$self->pidl_code("tree = proto_tree_add_subtree(parent_tree, tvb, offset, -1, ett_$ifname\_$name, &item, \"$name\");");
$self->deindent;
$self->pidl_code("}");
$self->pidl_code("");
if (defined $switch_type) {
$self->pidl_code("offset = $switch_dissect(tvb, offset, pinfo, tree, di, drep, hf_index, &level);");
if ($e->{ALIGN} > 1) {
$self->pidl_code("ALIGN_TO_$e->{ALIGN}_BYTES;");
$self->pidl_code("");
}
}
$self->pidl_code("switch(level) {$res\t}");
$self->pidl_code("proto_item_set_len(item, offset-old_offset);\n");
$self->pidl_code("");
$self->pidl_code("return offset;");
$self->deindent;
$self->pidl_code("}");
$self->pidl_fn_end($dissectorname);
$self->register_type($name, "offset = $dissectorname(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);", "FT_NONE", "BASE_NONE", 0, "NULL", 0);
}
sub Const($$$)
{
my ($self,$const,$ifname) = @_;
if (!defined($const->{ARRAY_LEN}[0])) {
$self->pidl_hdr("#define $const->{NAME}\t( $const->{VALUE} )\n");
} else {
$self->pidl_hdr("#define $const->{NAME}\t $const->{VALUE}\n");
}
}
sub Typedef($$$$)
{
my ($self,$e,$name,$ifname) = @_;
$self->Type($e->{DATA}, $name, $ifname);
}
sub Type($$$$)
{
my ($self, $e, $name, $ifname) = @_;
$self->PrintIdl(DumpType($e->{ORIGINAL}));
{
ENUM => \&Enum,
STRUCT => \&Struct,
UNION => \&Union,
BITMAP => \&Bitmap,
TYPEDEF => \&Typedef,
PIPE => \&Pipe
}->{$e->{TYPE}}->($self, $e, $name, $ifname);
}
sub RegisterInterface($$)
{
my ($self, $x) = @_;
$self->pidl_fn_start("proto_register_dcerpc_$x->{NAME}");
$self->pidl_code("void proto_register_dcerpc_$x->{NAME}(void)");
$self->pidl_code("{");
$self->indent;
$self->{res}->{headers} .= "void proto_register_dcerpc_$x->{NAME}(void);\n";
$self->{res}->{code}.=$self->DumpHfList()."\n";
$self->{res}->{code}.="\n".DumpEttList($self->{ett})."\n";
if (defined($x->{UUID})) {
# These can be changed to non-pidl_code names if the old
# dissectors in epan/dissectors are deleted.
my $name = uc($x->{NAME}) . " (pidl)";
my $short_name = uc($x->{NAME});
my $filter_name = $x->{NAME};
if (has_property($x, "helpstring")) {
$name = $x->{PROPERTIES}->{helpstring};
}
if (defined($self->{conformance}->{protocols}->{$x->{NAME}})) {
$short_name = $self->{conformance}->{protocols}->{$x->{NAME}}->{SHORTNAME};
$name = $self->{conformance}->{protocols}->{$x->{NAME}}->{LONGNAME};
$filter_name = $self->{conformance}->{protocols}->{$x->{NAME}}->{FILTERNAME};
}
$self->pidl_code("proto_dcerpc_$x->{NAME} = proto_register_protocol(".make_str($name).", ".make_str($short_name).", ".make_str($filter_name).");");
$self->pidl_code("proto_register_field_array(proto_dcerpc_$x->{NAME}, hf, array_length (hf));");
$self->pidl_code("proto_register_subtree_array(ett, array_length(ett));");
} else {
$self->pidl_code("proto_dcerpc = proto_get_id_by_filter_name(\"dcerpc\");");
$self->pidl_code("proto_register_field_array(proto_dcerpc, hf, array_length(hf));");
$self->pidl_code("proto_register_subtree_array(ett, array_length(ett));");
}
$self->deindent;
$self->pidl_code("}\n");
$self->pidl_fn_end("proto_register_dcerpc_$x->{NAME}");
}
sub RegisterInterfaceHandoff($$)
{
my ($self,$x) = @_;
if (defined($x->{UUID})) {
$self->pidl_fn_start("proto_reg_handoff_dcerpc_$x->{NAME}");
$self->pidl_code("void proto_reg_handoff_dcerpc_$x->{NAME}(void)");
$self->pidl_code("{");
$self->indent;
$self->pidl_code("dcerpc_init_uuid(proto_dcerpc_$x->{NAME}, ett_dcerpc_$x->{NAME},");
$self->pidl_code("\t&uuid_dcerpc_$x->{NAME}, ver_dcerpc_$x->{NAME},");
$self->pidl_code("\t$x->{NAME}_dissectors, hf_$x->{NAME}_opnum);");
$self->deindent;
$self->pidl_code("}");
$self->pidl_fn_end("proto_reg_handoff_dcerpc_$x->{NAME}");
$self->{res}->{headers} .= "void proto_reg_handoff_dcerpc_$x->{NAME}(void);\n";
$self->{hf_used}->{"hf_$x->{NAME}_opnum"} = 1;
}
}
sub ProcessInclude
{
my $self = shift;
my @includes = @_;
foreach (@includes) {
$self->pidl_hdr("#include \"$_\"");
}
$self->pidl_hdr("");
}
sub ProcessImport
{
my $self = shift;
my @imports = @_;
foreach (@imports) {
next if($_ eq "security");
s/^\"//;
s/\.idl"?$//;
s/^.*\///;
$self->pidl_hdr("#include \"packet-dcerpc-$_\.h\"");
}
$self->pidl_hdr("");
}
sub ProcessInterface($$)
{
my ($self, $x) = @_;
push(@{$self->{conformance}->{strip_prefixes}}, $x->{NAME});
my $define = "__PACKET_DCERPC_" . uc($_->{NAME}) . "_H";
$self->pidl_hdr("#ifndef $define");
$self->pidl_hdr("#define $define");
$self->pidl_hdr("");
$self->pidl_def("static gint proto_dcerpc_$x->{NAME} = -1;");
$self->register_ett("ett_dcerpc_$x->{NAME}");
$self->register_hf_field("hf_$x->{NAME}_opnum", "Operation", "$x->{NAME}.opnum", "FT_UINT16", "BASE_DEC", "NULL", 0, "");
if (defined($x->{UUID})) {
my $if_uuid = $x->{UUID};
$self->pidl_def("/* Version information */\n\n");
$self->pidl_def("static e_guid_t uuid_dcerpc_$x->{NAME} = {");
$self->pidl_def("\t0x" . substr($if_uuid, 1, 8)
. ", 0x" . substr($if_uuid, 10, 4)
. ", 0x" . substr($if_uuid, 15, 4) . ",");
$self->pidl_def("\t{ 0x" . substr($if_uuid, 20, 2)
. ", 0x" . substr($if_uuid, 22, 2)
. ", 0x" . substr($if_uuid, 25, 2)
. ", 0x" . substr($if_uuid, 27, 2)
. ", 0x" . substr($if_uuid, 29, 2)
. ", 0x" . substr($if_uuid, 31, 2)
. ", 0x" . substr($if_uuid, 33, 2)
. ", 0x" . substr($if_uuid, 35, 2) . " }");
$self->pidl_def("};");
my $maj = 0x0000FFFF & $x->{VERSION};
$maj =~ s/\.(.*)$//g;
$self->pidl_def("static guint16 ver_dcerpc_$x->{NAME} = $maj;");
$self->pidl_def("");
}
$return_types{$x->{NAME}} = {};
$self->Interface($x);
$self->pidl_code("\n".DumpFunctionTable($x));
foreach (sort(keys %{$return_types{$x->{NAME}}})) {
my ($type, $desc) = @{$return_types{$x->{NAME}}->{$_}};
my $dt = $self->find_type($type);
$dt or die("Unable to find information about return type `$type'");
$self->register_hf_field("hf_$x->{NAME}_$_", $desc, "$x->{NAME}.$_", $dt->{FT_TYPE}, "BASE_HEX", $dt->{VALSSTRING}, 0, "");
$self->{hf_used}->{"hf_$x->{NAME}_$_"} = 1;
}
$self->RegisterInterface($x);
$self->RegisterInterfaceHandoff($x);
if (exists ($self->{conformance}->{header})) {
$self->pidl_hdr($self->{conformance}->{header});
}
$self->pidl_hdr("#endif /* $define */");
}
sub find_type($$)
{
my ($self, $n) = @_;
return $self->{conformance}->{types}->{$n};
}
sub register_type($$$$$$$$)
{
my ($self, $type,$call,$ft,$base,$mask,$vals,$length) = @_;
return if (defined($self->{conformance}->{types}->{$type}));
$self->{conformance}->{types}->{$type} = {
NAME => $type,
DISSECTOR_NAME => $call,
FT_TYPE => $ft,
BASE_TYPE => $base,
MASK => $mask,
VALSSTRING => $vals,
ALIGNMENT => $length
};
}
# Loads the default types
sub Initialize($$)
{
my ($self, $cnf_file) = @_;
$self->{conformance} = {
imports => {},
header_fields=> {}
};
ReadConformance($cnf_file, $self->{conformance}) or print STDERR "warning: No conformance file `$cnf_file'\n";
foreach my $bytes (qw(1 2 4 8)) {
my $bits = $bytes * 8;
$self->register_type("uint$bits", "offset = PIDL_dissect_uint$bits(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);", "FT_UINT$bits", "BASE_DEC", 0, "NULL", $bytes);
$self->register_type("int$bits", "offset = PIDL_dissect_uint$bits(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);", "FT_INT$bits", "BASE_DEC", 0, "NULL", $bytes);
}
$self->register_type("uint3264", "offset = dissect_ndr_uint3264(tvb, offset, pinfo, tree, di, drep, \@HF\@, NULL);", "FT_UINT32", "BASE_DEC", 0, "NULL", 8);
$self->register_type("hyper", "offset = dissect_ndr_uint64(tvb, offset, pinfo, tree, di, drep, \@HF\@, NULL);", "FT_UINT64", "BASE_DEC", 0, "NULL", 8);
$self->register_type("udlong", "offset = dissect_ndr_duint32(tvb, offset, pinfo, tree, di, drep, \@HF\@, NULL);", "FT_UINT64", "BASE_DEC", 0, "NULL", 4);
$self->register_type("bool8", "offset = PIDL_dissect_uint8(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);","FT_INT8", "BASE_DEC", 0, "NULL", 1);
$self->register_type("char", "offset = PIDL_dissect_uint8(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);","FT_INT8", "BASE_DEC", 0, "NULL", 1);
$self->register_type("long", "offset = PIDL_dissect_uint32(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);","FT_INT32", "BASE_DEC", 0, "NULL", 4);
$self->register_type("dlong", "offset = dissect_ndr_duint32(tvb, offset, pinfo, tree, di, drep, \@HF\@, NULL);","FT_INT64", "BASE_DEC", 0, "NULL", 8);
$self->register_type("GUID", "offset = dissect_ndr_uuid_t(tvb, offset, pinfo, tree, di, drep, \@HF\@, NULL);","FT_GUID", "BASE_NONE", 0, "NULL", 4);
$self->register_type("policy_handle", "offset = PIDL_dissect_policy_hnd(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);","FT_BYTES", "BASE_NONE", 0, "NULL", 4);
$self->register_type("NTTIME", "offset = dissect_ndr_nt_NTTIME(tvb, offset, pinfo, tree, di, drep, \@HF\@);","FT_ABSOLUTE_TIME", "ABSOLUTE_TIME_LOCAL", 0, "NULL", 4);
$self->register_type("NTTIME_hyper", "offset = dissect_ndr_nt_NTTIME(tvb, offset, pinfo, tree, di, drep, \@HF\@);","FT_ABSOLUTE_TIME", "ABSOLUTE_TIME_LOCAL", 0, "NULL", 4);
$self->register_type("time_t", "offset = dissect_ndr_time_t(tvb, offset, pinfo,tree, di, drep, \@HF\@, NULL);","FT_ABSOLUTE_TIME", "ABSOLUTE_TIME_LOCAL", 0, "NULL", 4);
$self->register_type("NTTIME_1sec", "offset = dissect_ndr_nt_NTTIME(tvb, offset, pinfo, tree, di, drep, \@HF\@);", "FT_ABSOLUTE_TIME", "ABSOLUTE_TIME_LOCAL", 0, "NULL", 4);
$self->register_type("dom_sid28",
"offset = dissect_ndr_nt_SID28(tvb, offset, pinfo, tree, di, drep, \@HF\@);", "FT_STRING", "BASE_NONE", 0, "NULL", 4);
$self->register_type("SID",
"offset = dissect_ndr_nt_SID_with_options(tvb, offset, pinfo, tree, di, drep, param, \@HF\@);","FT_STRING", "BASE_NONE", 0, "NULL", 4);
$self->register_type("WERROR",
"offset = PIDL_dissect_uint32(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);","FT_UINT32", "BASE_DEC", 0, "VALS(WERR_errors)", 4);
$self->register_type("NTSTATUS",
"offset = PIDL_dissect_uint32(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);","FT_UINT32", "BASE_DEC", 0, "VALS(NT_errors)", 4);
$self->register_type("HRESULT",
"offset = PIDL_dissect_uint32(tvb, offset, pinfo, tree, di, drep, \@HF\@, \@PARAM\@);","FT_UINT32", "BASE_DEC", 0, "VALS(HRES_errors)", 4);
$self->register_type("ipv6address", "proto_tree_add_item(tree, \@HF\@, tvb, offset, 16, ENC_NA); offset += 16;", "FT_IPv6", "BASE_NONE", 0, "NULL", 16);
$self->register_type("ipv4address", "proto_tree_add_item(tree, \@HF\@, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4;", "FT_IPv4", "BASE_NONE", 0, "NULL", 4);
}
#####################################################################
# Generate Wireshark parser and header code
sub Parse($$$$$)
{
my($self,$ndr,$idl_file,$h_filename,$cnf_file) = @_;
$self->Initialize($cnf_file);
return (undef, undef) if defined($self->{conformance}->{noemit_dissector});
my $notice =
"/* DO NOT EDIT
This file was automatically generated by Pidl
from $idl_file and $cnf_file.
Pidl is a perl based IDL compiler for DCE/RPC idl files.
It is maintained by the Samba team, not the Wireshark team.
Instructions on how to download and install Pidl can be
found at https://gitlab.com/wireshark/wireshark/-/wikis/Pidl
*/
";
$self->{res}->{headers} = "\n";
$self->{res}->{headers} .= "#include \"config.h\"\n";
$self->{res}->{headers} .= "#include <glib.h>\n";
$self->{res}->{headers} .= "#include <string.h>\n";
$self->{res}->{headers} .= "#include <epan/packet.h>\n\n";
$self->{res}->{headers} .= "#include \"packet-dcerpc.h\"\n";
$self->{res}->{headers} .= "#include \"packet-dcerpc-nt.h\"\n";
$self->{res}->{headers} .= "#include \"packet-windows-common.h\"\n";
my $h_basename = basename($h_filename);
$self->{res}->{headers} .= "#include \"$h_basename\"\n";
$self->pidl_code("");
if (defined($self->{conformance}->{ett})) {
register_ett($self,$_) foreach(@{$self->{conformance}->{ett}})
}
# Wireshark protocol registration
foreach (@$ndr) {
$self->ProcessInterface($_) if ($_->{TYPE} eq "INTERFACE");
$self->ProcessImport(@{$_->{PATHS}}) if ($_->{TYPE} eq "IMPORT");
$self->ProcessInclude(@{$_->{PATHS}}) if ($_->{TYPE} eq "INCLUDE");
}
$self->{res}->{ett} = DumpEttDeclaration($self->{ett});
$self->{res}->{hf} = $self->DumpHfDeclaration();
my $parser = $notice;
$parser.= $self->{res}->{headers};
$parser.=$self->{res}->{ett};
$parser.=$self->{res}->{hf};
$parser.=$self->{res}->{def};
if (exists ($self->{conformance}->{override})) {
$parser.=$self->{conformance}->{override};
}
$parser.=$self->{res}->{code};
my $header = $notice;
$header.=$self->{res}->{hdr};
$self->CheckUsed($self->{conformance});
return ($parser,$header);
}
###############################################################################
# ETT
###############################################################################
sub register_ett($$)
{
my ($self, $name) = @_;
push (@{$self->{ett}}, $name);
}
sub DumpEttList
{
my ($ett) = @_;
my $res = "\tstatic gint *ett[] = {\n";
foreach (@$ett) {
$res .= "\t\t&$_,\n";
}
return "$res\t};\n";
}
sub DumpEttDeclaration
{
my ($ett) = @_;
my $res = "\n/* Ett declarations */\n";
foreach (@$ett) {
$res .= "static gint $_ = -1;\n";
}
return "$res\n";
}
###############################################################################
# HF
###############################################################################
sub register_hf_field($$$$$$$$$)
{
my ($self,$index,$name,$filter_name,$ft_type,$base_type,$valsstring,$mask,$blurb) = @_;
if (defined ($self->{conformance}->{hf_renames}->{$index})) {
$self->{conformance}->{hf_renames}->{$index}->{USED} = 1;
return $self->{conformance}->{hf_renames}->{$index}->{NEWNAME};
}
$self->{conformance}->{header_fields}->{$index} = {
INDEX => $index,
NAME => $name,
FILTER => $filter_name,
FT_TYPE => $ft_type,
BASE_TYPE => $base_type,
VALSSTRING => $valsstring,
MASK => $mask,
BLURB => $blurb
};
if ((not defined($blurb) or $blurb eq "") and
defined($self->{conformance}->{fielddescription}->{$index})) {
$self->{conformance}->{header_fields}->{$index}->{BLURB} =
$self->{conformance}->{fielddescription}->{$index}->{DESCRIPTION};
$self->{conformance}->{fielddescription}->{$index}->{USED} = 1;
}
return $index;
}
sub change_hf_field_type($$$$)
{
my ($self,$index,$ft_type,$base_type) = @_;
if (defined ($self->{conformance}->{hf_renames}->{$index})) {
print "Field $index has been renamed to ".$self->{conformance}->{hf_renames}->{$index}->{NEWNAME}." you can't change it's type";
return 0;
}
if (!defined ($self->{conformance}->{header_fields}->{$index})) {
print "Field $index doesn't exists";
return 0;
}
$self->{conformance}->{header_fields}->{$index}->{FT_TYPE} = $ft_type;
$self->{conformance}->{header_fields}->{$index}->{BASE_TYPE} = $base_type;
return 1;
}
sub DumpHfDeclaration($)
{
my ($self) = @_;
my $res = "";
$res = "\n/* Header field declarations */\n";
foreach (sort(keys %{$self->{conformance}->{header_fields}}))
{
$res .= "static gint $_ = -1;\n";
}
return "$res\n";
}
sub make_str_or_null($)
{
my $str = shift;
if (substr($str, 0, 1) eq "\"") {
$str = substr($str, 1, length($str)-2);
}
$str =~ s/^\s*//;
$str =~ s/\s*$//;
if ($str eq "") {
return "NULL";
}
return make_str($str);
}
sub DumpHfList($)
{
my ($self) = @_;
my $res = "\tstatic hf_register_info hf[] = {\n";
foreach (sort {$a->{INDEX} cmp $b->{INDEX}} values %{$self->{conformance}->{header_fields}})
{
$res .= "\t{ &$_->{INDEX},\n".
"\t { ".make_str($_->{NAME}).", ".make_str($_->{FILTER}).", $_->{FT_TYPE}, $_->{BASE_TYPE}, $_->{VALSSTRING}, $_->{MASK}, ".make_str_or_null($_->{BLURB}).", HFILL }},\n";
}
return $res."\t};\n";
}
###############################################################################
# Function table
###############################################################################
sub DumpFunctionTable($)
{
my $if = shift;
my $res = "static dcerpc_sub_dissector $if->{NAME}\_dissectors[] = {\n";
foreach (@{$if->{FUNCTIONS}}) {
my $fn_name = $_->{NAME};
$fn_name =~ s/^$if->{NAME}_//;
$res.= "\t{ $_->{OPNUM}, \"$fn_name\",\n";
$res.= "\t $if->{NAME}_dissect_${fn_name}_request, $if->{NAME}_dissect_${fn_name}_response},\n";
}
$res .= "\t{ 0, NULL, NULL, NULL }\n";
return "$res};\n";
}
sub CheckUsed($$)
{
my ($self, $conformance) = @_;
foreach (values %{$conformance->{header_fields}}) {
if (not defined($self->{hf_used}->{$_->{INDEX}})) {
warning($_->{POS}, "hf field `$_->{INDEX}' not used");
}
}
foreach (values %{$conformance->{hf_renames}}) {
if (not $_->{USED}) {
warning($_->{POS}, "hf field `$_->{OLDNAME}' not used");
}
}
foreach (values %{$conformance->{dissectorparams}}) {
if (not $_->{USED}) {
warning($_->{POS}, "dissector param never used");
}
}
foreach (values %{$conformance->{imports}}) {
if (not $_->{USED}) {
warning($_->{POS}, "import never used");
}
}
foreach (values %{$conformance->{types}}) {
if (not $_->{USED} and defined($_->{POS})) {
warning($_->{POS}, "type never used");
}
}
foreach (values %{$conformance->{fielddescription}}) {
if (not $_->{USED}) {
warning($_->{POS}, "description never used");
}
}
foreach (values %{$conformance->{tfs}}) {
if (not $_->{USED}) {
warning($_->{POS}, "True/False description never used");
}
}
}
1; |
|
wireshark/tools/pidl/lib/Parse/Yapp/Driver.pm | #
# Module Parse::Yapp::Driver
#
# This module is part of the Parse::Yapp package available on your
# nearest CPAN
#
# Any use of this module in a standalone parser make the included
# text under the same copyright as the Parse::Yapp module itself.
#
# This notice should remain unchanged.
#
# (c) Copyright 1998-2001 Francois Desarmenien, all rights reserved.
# (see the pod text in Parse::Yapp module for use and distribution rights)
#
package Parse::Yapp::Driver;
require 5.004;
use strict;
use vars qw ( $VERSION $COMPATIBLE $FILENAME );
$VERSION = '1.05';
$COMPATIBLE = '0.07';
$FILENAME=__FILE__;
use Carp;
#Known parameters, all starting with YY (leading YY will be discarded)
my(%params)=(YYLEX => 'CODE', 'YYERROR' => 'CODE', YYVERSION => '',
YYRULES => 'ARRAY', YYSTATES => 'ARRAY', YYDEBUG => '');
#Mandatory parameters
my(@params)=('LEX','RULES','STATES');
sub new {
my($class)=shift;
my($errst,$nberr,$token,$value,$check,$dotpos);
my($self)={ ERROR => \&_Error,
ERRST => \$errst,
NBERR => \$nberr,
TOKEN => \$token,
VALUE => \$value,
DOTPOS => \$dotpos,
STACK => [],
DEBUG => 0,
CHECK => \$check };
_CheckParams( [], \%params, \@_, $self );
exists($$self{VERSION})
and $$self{VERSION} < $COMPATIBLE
and croak "Yapp driver version $VERSION ".
"incompatible with version $$self{VERSION}:\n".
"Please recompile parser module.";
ref($class)
and $class=ref($class);
bless($self,$class);
}
sub YYParse {
my($self)=shift;
my($retval);
_CheckParams( \@params, \%params, \@_, $self );
if($$self{DEBUG}) {
_DBLoad();
$retval = eval '$self->_DBParse()';#Do not create stab entry on compile
$@ and die $@;
}
else {
$retval = $self->_Parse();
}
$retval
}
sub YYData {
my($self)=shift;
exists($$self{USER})
or $$self{USER}={};
$$self{USER};
}
sub YYErrok {
my($self)=shift;
${$$self{ERRST}}=0;
undef;
}
sub YYNberr {
my($self)=shift;
${$$self{NBERR}};
}
sub YYRecovering {
my($self)=shift;
${$$self{ERRST}} != 0;
}
sub YYAbort {
my($self)=shift;
${$$self{CHECK}}='ABORT';
undef;
}
sub YYAccept {
my($self)=shift;
${$$self{CHECK}}='ACCEPT';
undef;
}
sub YYError {
my($self)=shift;
${$$self{CHECK}}='ERROR';
undef;
}
sub YYSemval {
my($self)=shift;
my($index)= $_[0] - ${$$self{DOTPOS}} - 1;
$index < 0
and -$index <= @{$$self{STACK}}
and return $$self{STACK}[$index][1];
undef; #Invalid index
}
sub YYCurtok {
my($self)=shift;
@_
and ${$$self{TOKEN}}=$_[0];
${$$self{TOKEN}};
}
sub YYCurval {
my($self)=shift;
@_
and ${$$self{VALUE}}=$_[0];
${$$self{VALUE}};
}
sub YYExpect {
my($self)=shift;
keys %{$self->{STATES}[$self->{STACK}[-1][0]]{ACTIONS}}
}
sub YYLexer {
my($self)=shift;
$$self{LEX};
}
#################
# Private stuff #
#################
sub _CheckParams {
my($mandatory,$checklist,$inarray,$outhash)=@_;
my($prm,$value);
my($prmlst)={};
while(($prm,$value)=splice(@$inarray,0,2)) {
$prm=uc($prm);
exists($$checklist{$prm})
or croak("Unknown parameter '$prm'");
ref($value) eq $$checklist{$prm}
or croak("Invalid value for parameter '$prm'");
$prm=unpack('@2A*',$prm);
$$outhash{$prm}=$value;
}
for (@$mandatory) {
exists($$outhash{$_})
or croak("Missing mandatory parameter '".lc($_)."'");
}
}
sub _Error {
print "Parse error.\n";
}
sub _DBLoad {
{
no strict 'refs';
exists(${__PACKAGE__.'::'}{_DBParse})#Already loaded ?
and return;
}
my($fname)=__FILE__;
my(@drv);
open(DRV,"<$fname") or die "Report this as a BUG: Cannot open $fname";
while(<DRV>) {
/^\s*sub\s+_Parse\s*{\s*$/ .. /^\s*}\s*#\s*_Parse\s*$/
and do {
s/^#DBG>//;
push(@drv,$_);
}
}
close(DRV);
$drv[0]=~s/_P/_DBP/;
eval join('',@drv);
}
#Note that for loading debugging version of the driver,
#this file will be parsed from 'sub _Parse' up to '}#_Parse' inclusive.
#So, DO NOT remove comment at end of sub !!!
sub _Parse {
my($self)=shift;
my($rules,$states,$lex,$error)
= @$self{ 'RULES', 'STATES', 'LEX', 'ERROR' };
my($errstatus,$nberror,$token,$value,$stack,$check,$dotpos)
= @$self{ 'ERRST', 'NBERR', 'TOKEN', 'VALUE', 'STACK', 'CHECK', 'DOTPOS' };
#DBG> my($debug)=$$self{DEBUG};
#DBG> my($dbgerror)=0;
#DBG> my($ShowCurToken) = sub {
#DBG> my($tok)='>';
#DBG> for (split('',$$token)) {
#DBG> $tok.= (ord($_) < 32 or ord($_) > 126)
#DBG> ? sprintf('<%02X>',ord($_))
#DBG> : $_;
#DBG> }
#DBG> $tok.='<';
#DBG> };
$$errstatus=0;
$$nberror=0;
($$token,$$value)=(undef,undef);
@$stack=( [ 0, undef ] );
$$check='';
while(1) {
my($actions,$act,$stateno);
$stateno=$$stack[-1][0];
$actions=$$states[$stateno];
#DBG> print STDERR ('-' x 40),"\n";
#DBG> $debug & 0x2
#DBG> and print STDERR "In state $stateno:\n";
#DBG> $debug & 0x08
#DBG> and print STDERR "Stack:[".
#DBG> join(',',map { $$_[0] } @$stack).
#DBG> "]\n";
if (exists($$actions{ACTIONS})) {
defined($$token)
or do {
($$token,$$value)=&$lex($self);
#DBG> $debug & 0x01
#DBG> and print STDERR "Need token. Got ".&$ShowCurToken."\n";
};
$act= exists($$actions{ACTIONS}{$$token})
? $$actions{ACTIONS}{$$token}
: exists($$actions{DEFAULT})
? $$actions{DEFAULT}
: undef;
}
else {
$act=$$actions{DEFAULT};
#DBG> $debug & 0x01
#DBG> and print STDERR "Don't need token.\n";
}
defined($act)
and do {
$act > 0
and do { #shift
#DBG> $debug & 0x04
#DBG> and print STDERR "Shift and go to state $act.\n";
$$errstatus
and do {
--$$errstatus;
#DBG> $debug & 0x10
#DBG> and $dbgerror
#DBG> and $$errstatus == 0
#DBG> and do {
#DBG> print STDERR "**End of Error recovery.\n";
#DBG> $dbgerror=0;
#DBG> };
};
push(@$stack,[ $act, $$value ]);
$$token ne '' #Don't eat the eof
and $$token=$$value=undef;
next;
};
#reduce
my($lhs,$len,$code,@sempar,$semval);
($lhs,$len,$code)=@{$$rules[-$act]};
#DBG> $debug & 0x04
#DBG> and $act
#DBG> and print STDERR "Reduce using rule ".-$act." ($lhs,$len): ";
$act
or $self->YYAccept();
$$dotpos=$len;
unpack('A1',$lhs) eq '@' #In line rule
and do {
$lhs =~ /^\@[0-9]+\-([0-9]+)$/
or die "In line rule name '$lhs' ill formed: ".
"report it as a BUG.\n";
$$dotpos = $1;
};
@sempar = $$dotpos
? map { $$_[1] } @$stack[ -$$dotpos .. -1 ]
: ();
$semval = $code ? &$code( $self, @sempar )
: @sempar ? $sempar[0] : undef;
splice(@$stack,-$len,$len);
$$check eq 'ACCEPT'
and do {
#DBG> $debug & 0x04
#DBG> and print STDERR "Accept.\n";
return($semval);
};
$$check eq 'ABORT'
and do {
#DBG> $debug & 0x04
#DBG> and print STDERR "Abort.\n";
return(undef);
};
#DBG> $debug & 0x04
#DBG> and print STDERR "Back to state $$stack[-1][0], then ";
$$check eq 'ERROR'
or do {
#DBG> $debug & 0x04
#DBG> and print STDERR
#DBG> "go to state $$states[$$stack[-1][0]]{GOTOS}{$lhs}.\n";
#DBG> $debug & 0x10
#DBG> and $dbgerror
#DBG> and $$errstatus == 0
#DBG> and do {
#DBG> print STDERR "**End of Error recovery.\n";
#DBG> $dbgerror=0;
#DBG> };
push(@$stack,
[ $$states[$$stack[-1][0]]{GOTOS}{$lhs}, $semval ]);
$$check='';
next;
};
#DBG> $debug & 0x04
#DBG> and print STDERR "Forced Error recovery.\n";
$$check='';
};
#Error
$$errstatus
or do {
$$errstatus = 1;
&$error($self);
$$errstatus # if 0, then YYErrok has been called
or next; # so continue parsing
#DBG> $debug & 0x10
#DBG> and do {
#DBG> print STDERR "**Entering Error recovery.\n";
#DBG> ++$dbgerror;
#DBG> };
++$$nberror;
};
$$errstatus == 3 #The next token is not valid: discard it
and do {
$$token eq '' # End of input: no hope
and do {
#DBG> $debug & 0x10
#DBG> and print STDERR "**At eof: aborting.\n";
return(undef);
};
#DBG> $debug & 0x10
#DBG> and print STDERR "**Dicard invalid token ".&$ShowCurToken.".\n";
$$token=$$value=undef;
};
$$errstatus=3;
while( @$stack
and ( not exists($$states[$$stack[-1][0]]{ACTIONS})
or not exists($$states[$$stack[-1][0]]{ACTIONS}{error})
or $$states[$$stack[-1][0]]{ACTIONS}{error} <= 0)) {
#DBG> $debug & 0x10
#DBG> and print STDERR "**Pop state $$stack[-1][0].\n";
pop(@$stack);
}
@$stack
or do {
#DBG> $debug & 0x10
#DBG> and print STDERR "**No state left on stack: aborting.\n";
return(undef);
};
#shift the error token
#DBG> $debug & 0x10
#DBG> and print STDERR "**Shift \$error token and go to state ".
#DBG> $$states[$$stack[-1][0]]{ACTIONS}{error}.
#DBG> ".\n";
push(@$stack, [ $$states[$$stack[-1][0]]{ACTIONS}{error}, undef ]);
}
#never reached
croak("Error in driver logic. Please, report it as a BUG");
}#_Parse
#DO NOT remove comment
1; |
|
Perl | wireshark/tools/pidl/tests/cutil.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 7;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Util qw(MyDumper);
use Parse::Pidl::CUtil qw(get_pointer_to get_value_of);
is("&foo", get_pointer_to("foo"));
is("&(&foo)", get_pointer_to(get_pointer_to("foo")));
is("*foo", get_pointer_to("**foo"));
is("foo", get_pointer_to("*foo"));
is("foo", get_value_of("&foo"));
is("*foo", get_value_of("foo"));
is("**foo", get_value_of("*foo")); |
Perl | wireshark/tools/pidl/tests/dump.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 1;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Dump qw(DumpStruct);
is (DumpStruct({ NAME => "foo", ELEMENTS => []}),
"struct foo {\n}"); |
Perl | wireshark/tools/pidl/tests/header.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 27;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Util qw(MyDumper);
use Parse::Pidl::Samba4::Header qw(
GenerateFunctionInEnv GenerateFunctionOutEnv GenerateStructEnv
EnvSubstituteValue);
use Parse::Pidl::IDL qw(parse_string);
use Parse::Pidl::NDR;
sub parse_idl($)
{
my $text = shift;
my $idl = Parse::Pidl::IDL::parse_string($text, "nofile");
my $ndr = Parse::Pidl::NDR::Parse($idl);
return Parse::Pidl::Samba4::Header::Parse($ndr);
}
like(parse_idl(""), qr/\/\* header auto-generated by pidl \*\/\n/sm, "includes work");
like(parse_idl("interface x {}"), qr/\/\* header auto-generated by pidl \*\/\n/sm, "simple empty interface doesn't cause overhead");
like(parse_idl("interface p { typedef struct { int y; } x; };"),
qr/.*#ifndef _HEADER_p\n#define _HEADER_p\n.+\n#endif \/\* _HEADER_p \*\/.*/ms, "ifdefs are created");
like(parse_idl("interface p { typedef struct { int y; } x; };"),
qr/struct x.*{.*int32_t y;.*}.*;/sm, "interface member generated properly");
like(parse_idl("interface x { void foo (void); };"),
qr/struct foo.*{\s+int _dummy_element;\s+};/sm, "void fn contains dummy element");
like(parse_idl("interface x { void foo ([in] uint32 x); };"),
qr/struct foo.*{\s+struct\s+{\s+uint32_t x;\s+} in;\s+};/sm, "fn in arg works");
like(parse_idl("interface x { void foo ([out] uint32 x); };"),
qr/struct foo.*{.*struct\s+{\s+uint32_t x;\s+} out;.*};/sm, "fn out arg works");
like(parse_idl("interface x { void foo ([in,out] uint32 x); };"),
qr/struct foo.*{.*struct\s+{\s+uint32_t x;\s+} in;\s+struct\s+{\s+uint32_t x;\s+} out;.*};/sm, "fn in,out arg works");
like(parse_idl("interface x { void foo (uint32 x); };"), qr/struct foo.*{.*struct\s+{\s+uint32_t x;\s+} in;\s+struct\s+{\s+uint32_t x;\s+} out;.*};/sm, "fn with no props implies in,out");
like(parse_idl("interface p { struct x { int y; }; };"),
qr/struct x.*{.*int32_t y;.*}.*;/sm, "interface member generated properly");
like(parse_idl("interface p { struct x { struct y z; }; };"),
qr/struct x.*{.*struct y z;.*}.*;/sm, "tagged type struct member");
like(parse_idl("interface p { struct x { union y z; }; };"),
qr/struct x.*{.*union y z;.*}.*;/sm, "tagged type union member");
like(parse_idl("interface p { struct x { }; };"),
qr/struct x.*{.*char _empty_;.*}.*;/sm, "empty struct");
like(parse_idl("interface p { struct x; };"),
qr/struct x;/sm, "struct declaration");
like(parse_idl("interface p { typedef struct x { int p; } x; };"),
qr/struct x.*{.*int32_t p;.*};/sm, "double struct declaration");
like(parse_idl("cpp_quote(\"some-foo\")"),
qr/some-foo/sm, "cpp quote");
# Make sure GenerateFunctionInEnv and GenerateFunctionOutEnv work
my $fn = { ELEMENTS => [ { DIRECTION => ["in"], NAME => "foo" } ] };
is_deeply({ "foo" => "r->in.foo" }, GenerateFunctionInEnv($fn));
$fn = { ELEMENTS => [ { DIRECTION => ["out"], NAME => "foo" } ] };
is_deeply({ "foo" => "r->out.foo" }, GenerateFunctionOutEnv($fn));
$fn = { ELEMENTS => [ { DIRECTION => ["out", "in"], NAME => "foo" } ] };
is_deeply({ "foo" => "r->in.foo" }, GenerateFunctionInEnv($fn));
$fn = { ELEMENTS => [ { DIRECTION => ["out", "in"], NAME => "foo" } ] };
is_deeply({ "foo" => "r->out.foo" }, GenerateFunctionOutEnv($fn));
$fn = { ELEMENTS => [ { DIRECTION => ["in"], NAME => "foo" } ] };
is_deeply({ "foo" => "r->in.foo" }, GenerateFunctionOutEnv($fn));
$fn = { ELEMENTS => [ { DIRECTION => ["out"], NAME => "foo" } ] };
is_deeply({ }, GenerateFunctionInEnv($fn));
$fn = { ELEMENTS => [ { NAME => "foo" }, { NAME => "bar" } ] };
is_deeply({ foo => "r->foo", bar => "r->bar", this => "r" },
GenerateStructEnv($fn, "r"));
$fn = { ELEMENTS => [ { NAME => "foo" }, { NAME => "bar" } ] };
is_deeply({ foo => "some->complex.variable->foo",
bar => "some->complex.variable->bar",
this => "some->complex.variable" },
GenerateStructEnv($fn, "some->complex.variable"));
$fn = { ELEMENTS => [ { NAME => "foo", PROPERTIES => { value => 3 }} ] };
my $env = GenerateStructEnv($fn, "r");
EnvSubstituteValue($env, $fn);
is_deeply($env, { foo => 3, this => "r" });
$fn = { ELEMENTS => [ { NAME => "foo" }, { NAME => "bar" } ] };
$env = GenerateStructEnv($fn, "r");
EnvSubstituteValue($env, $fn);
is_deeply($env, { foo => 'r->foo', bar => 'r->bar', this => "r" });
$fn = { ELEMENTS => [ { NAME => "foo", PROPERTIES => { value => 0 }} ] };
$env = GenerateStructEnv($fn, "r");
EnvSubstituteValue($env, $fn);
is_deeply($env, { foo => 0, this => "r" }); |
Perl | wireshark/tools/pidl/tests/ndr.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 47;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Util qw(MyDumper);
use Parse::Pidl::NDR qw(GetElementLevelTable ParseElement align_type mapToScalar ParseType can_contain_deferred);
# Case 1
my $e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {},
'POINTERS' => 0,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'STRUCT' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "unique", 0), [
{
'IS_DEFERRED' => 0,
'LEVEL_INDEX' => 0,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
my $ne = ParseElement($e, "unique", 0);
is($ne->{ORIGINAL}, $e);
is($ne->{NAME}, "v");
is($ne->{ALIGN}, 1);
is($ne->{TYPE}, "uint8");
is_deeply($ne->{LEVELS}, [
{
'IS_DEFERRED' => 0,
'LEVEL_INDEX' => 0,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 2 : pointers
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"unique" => 1},
'POINTERS' => 1,
'PARENT' => { TYPE => 'STRUCT' },
'TYPE' => 'uint8',
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "unique", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 0,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 1,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 3 : double pointers
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"unique" => 1},
'POINTERS' => 2,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'STRUCT' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "unique", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 0,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 1,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 1,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 2,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 3 : ref pointers
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"ref" => 1},
'POINTERS' => 1,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'STRUCT' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "unique", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 0,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 1,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 3 : ref pointers
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"ref" => 1},
'POINTERS' => 3,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'STRUCT' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "unique", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 0,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 1,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 1,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 2,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 2,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 3,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 3 : ref pointers
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"ref" => 1},
'POINTERS' => 3,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'STRUCT' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "ref", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 0,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 1,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 1,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 2,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 2,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 3,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 4 : top-level ref pointers
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"ref" => 1},
'POINTERS' => 1,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'FUNCTION' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "unique", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 0,
LEVEL => 'TOP'
},
{
'IS_DEFERRED' => 0,
'LEVEL_INDEX' => 1,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 4 : top-level ref pointers, triple with pointer_default("unique")
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"ref" => 1},
'POINTERS' => 3,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'FUNCTION' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "unique", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 0,
LEVEL => 'TOP'
},
{
LEVEL_INDEX => 1,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 1,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 2,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 2,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 3,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 4 : top-level unique pointers, triple with pointer_default("unique")
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"unique" => 1, "in" => 1},
'POINTERS' => 3,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'FUNCTION' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "unique", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 0,
LEVEL => 'TOP'
},
{
LEVEL_INDEX => 1,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 1,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 2,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 2,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 3,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 4 : top-level unique pointers, triple with pointer_default("ref")
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"unique" => 1, "in" => 1},
'POINTERS' => 3,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'FUNCTION' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "ref", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "unique",
POINTER_INDEX => 0,
LEVEL => 'TOP'
},
{
LEVEL_INDEX => 1,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 1,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 2,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 2,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 3,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# Case 4 : top-level ref pointers, triple with pointer_default("ref")
#
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"ref" => 1},
'POINTERS' => 3,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'FUNCTION' },
'LINE' => 42 };
is_deeply(GetElementLevelTable($e, "ref", 0), [
{
LEVEL_INDEX => 0,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 0,
LEVEL => 'TOP'
},
{
LEVEL_INDEX => 1,
IS_DEFERRED => 0,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 1,
LEVEL => 'EMBEDDED'
},
{
LEVEL_INDEX => 2,
IS_DEFERRED => 1,
TYPE => 'POINTER',
POINTER_TYPE => "ref",
POINTER_INDEX => 2,
LEVEL => 'EMBEDDED'
},
{
'IS_DEFERRED' => 1,
'LEVEL_INDEX' => 3,
'DATA_TYPE' => 'uint8',
'CONTAINS_DEFERRED' => 0,
'TYPE' => 'DATA',
'IS_SURROUNDING' => 0,
}
]);
# representation_type
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => { represent_as => "bar" },
'POINTERS' => 0,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'STRUCT' },
'LINE' => 42 };
$ne = ParseElement($e, undef, 0);
is($ne->{REPRESENTATION_TYPE}, "bar");
# representation_type
$e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => { },
'POINTERS' => 0,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'STRUCT' },
'LINE' => 42 };
$ne = ParseElement($e, undef, 0);
is($ne->{REPRESENTATION_TYPE}, "uint8");
is(align_type("hyper"), 8);
is(align_type("double"), 8);
is(align_type("uint32"), 4);
is(align_type("uint16"), 2);
is(align_type("uint8"), 1);
is(align_type({ TYPE => "STRUCT", "NAME" => "bla",
ELEMENTS => [ { TYPE => "uint16" } ] }), 4);
is(align_type({ TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "hyper" } ] }), 8);
is(align_type({ TYPE => "TYPEDEF", DATA => {
TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "hyper" } ] }}), 8);
# typedef of struct without body
is(align_type({ TYPE => "TYPEDEF", DATA => {
TYPE => "STRUCT", ELEMENTS => undef }}), 4);
# struct without body
is(align_type({ TYPE => "STRUCT", ELEMENTS => undef }), 4);
# empty struct
is(align_type({ TYPE => "STRUCT", ELEMENTS => [] }), 1);
is(align_type({ TYPE => "STRUCT", "NAME" => "bla",
ELEMENTS => [ { TYPE => "uint8" } ] }), 4);
is(mapToScalar("someverymuchnotexistingtype"), undef);
is(mapToScalar("uint32"), "uint32");
is(mapToScalar({TYPE => "ENUM", PARENT => { PROPERTIES => { enum8bit => 1 } } }), "uint8");
is(mapToScalar({TYPE => "BITMAP", PROPERTIES => { bitmap64bit => 1 } }),
"hyper");
is(mapToScalar({TYPE => "TYPEDEF", DATA => {TYPE => "ENUM", PARENT => { PROPERTIES => { enum8bit => 1 } } }}), "uint8");
my $t;
$t = {
TYPE => "STRUCT",
NAME => "foo",
SURROUNDING_ELEMENT => undef,
ELEMENTS => undef,
PROPERTIES => undef,
ORIGINAL => {
TYPE => "STRUCT",
NAME => "foo"
},
ALIGN => undef
};
is_deeply(ParseType($t->{ORIGINAL}, "ref", 0), $t);
$t = {
TYPE => "UNION",
NAME => "foo",
SWITCH_TYPE => "uint32",
ELEMENTS => undef,
PROPERTIES => undef,
HAS_DEFAULT => 0,
IS_MS_UNION => 0,
ORIGINAL => {
TYPE => "UNION",
NAME => "foo"
},
ALIGN => undef
};
is_deeply(ParseType($t->{ORIGINAL}, "ref", 0), $t);
ok(not can_contain_deferred("uint32"));
ok(can_contain_deferred("some_unknown_type"));
ok(can_contain_deferred({ TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "uint32", POINTERS => 40 } ]}));
ok(can_contain_deferred({ TYPE => "TYPEDEF",
DATA => { TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "uint32", POINTERS => 40 } ]}}));
ok(not can_contain_deferred({ TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "uint32" } ]}));
ok(not can_contain_deferred({ TYPE => "TYPEDEF",
DATA => { TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "uint32" } ]}}));
ok(can_contain_deferred({ TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "someunknowntype" } ]}));
# Make sure the elements for a enum without body aren't filled in
ok(not defined(ParseType({TYPE => "ENUM", NAME => "foo" }, "ref", 0)->{ELEMENTS}));
# Make sure the elements for a bitmap without body aren't filled in
ok(not defined(ParseType({TYPE => "BITMAP", NAME => "foo" }, "ref", 0)->{ELEMENTS}));
# Make sure the elements for a union without body aren't filled in
ok(not defined(ParseType({TYPE => "UNION", NAME => "foo" }, "ref", 0)->{ELEMENTS})); |
Perl | wireshark/tools/pidl/tests/ndr_align.pl | #!/usr/bin/perl
# NDR alignment tests
# (C) 2005 Jelmer Vernooij. Published under the GNU GPL
use strict;
use Test::More tests => 5 * 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
test_samba4_ndr('align-uint8-uint16',
'
typedef [public] struct {
uint8 x;
uint16 y;
} bla;
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct bla r;
uint8_t expected[] = { 0x0D, 0x00, 0xef, 0xbe };
DATA_BLOB expected_blob = { expected, 4 };
DATA_BLOB result_blob;
r.x = 13;
r.y = 0xbeef;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_bla(ndr, NDR_SCALARS|NDR_BUFFERS, &r)))
return 1;
result_blob = ndr_push_blob(ndr);
if (data_blob_cmp(&result_blob, &expected_blob) != 0)
return 2;
');
test_samba4_ndr('align-uint8-uint32',
'
typedef [public] struct {
uint8 x;
uint32 y;
} bla;
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct bla r;
uint8_t expected[] = { 0x0D, 0x00, 0x00, 0x00, 0xef, 0xbe, 0xef, 0xbe };
DATA_BLOB expected_blob = { expected, 8 };
DATA_BLOB result_blob;
r.x = 13;
r.y = 0xbeefbeef;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_bla(ndr, NDR_SCALARS|NDR_BUFFERS, &r)))
return 1;
result_blob = ndr_push_blob(ndr);
if (data_blob_cmp(&result_blob, &expected_blob) != 0)
return 2;
');
test_samba4_ndr('align-uint8-hyper',
'
typedef [public] struct {
uint8 x;
hyper y;
} bla;
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct bla r;
uint8_t expected[] = { 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xef, 0xbe, 0xef, 0xbe, 0xef, 0xbe, 0xef, 0xbe };
DATA_BLOB expected_blob = { expected, 16 };
DATA_BLOB result_blob;
r.x = 13;
r.y = 0xbeefbeefbeefbeefLLU;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_bla(ndr, NDR_SCALARS|NDR_BUFFERS, &r)))
return 1;
result_blob = ndr_push_blob(ndr);
if (data_blob_cmp(&result_blob, &expected_blob) != 0)
return 2;
');
test_samba4_ndr('noalignflag-uint8-uint16',
'
typedef [public] struct {
uint8 x;
uint16 y;
} bla;
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct bla r;
uint8_t expected[] = { 0x0D, 0xef, 0xbe };
DATA_BLOB expected_blob = { expected, 3 };
DATA_BLOB result_blob;
ndr->flags |= LIBNDR_FLAG_NOALIGN;
r.x = 13;
r.y = 0xbeef;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_bla(ndr, NDR_SCALARS|NDR_BUFFERS, &r)))
return 1;
result_blob = ndr_push_blob(ndr);
if (data_blob_cmp(&result_blob, &expected_blob) != 0)
return 2;
');
test_samba4_ndr('align-blob-align2',
'
typedef [public] struct {
uint8 x;
[flag(LIBNDR_FLAG_ALIGN2)] DATA_BLOB data;
uint8 y;
} blie;
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct blie r;
uint8_t data[] = { 0x01, 0x02 };
uint8_t expected[] = { 0x0D, 0x00, 0x0E };
DATA_BLOB expected_blob = { expected, 3 };
DATA_BLOB result_blob;
r.x = 13;
r.y = 14;
r.data.data = data;
r.data.length = 2;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_blie(ndr, NDR_SCALARS|NDR_BUFFERS, &r)))
return 1;
result_blob = ndr_push_blob(ndr);
if (data_blob_cmp(&result_blob, &expected_blob) != 0)
return 2;
'); |
Perl | wireshark/tools/pidl/tests/ndr_alloc.pl | #!/usr/bin/perl
# NDR allocation tests
# (C) 2005 Jelmer Vernooij. Published under the GNU GPL
use strict;
use Test::More tests => 5 * 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
# Check that an outgoing scalar pointer is allocated correctly
test_samba4_ndr("alloc-scalar",
'
typedef struct {
uint8 *x;
} bla;
[public] void TestAlloc([in] bla foo);
','
uint8_t data[] = { 0xde, 0xad, 0xbe, 0xef, 0x03 };
DATA_BLOB b = { data, 5 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct TestAlloc r;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestAlloc(ndr, NDR_IN, &r)))
return 1;
if (r.in.foo.x == NULL)
return 2;
if (*r.in.foo.x != 0x03)
return 3;
'
);
# Check that an outgoing buffer pointer is allocated correctly
test_samba4_ndr("alloc-buffer",
'
typedef struct { uint8 data; } blie;
typedef struct { blie *x; } bla;
[public] void TestAlloc([in] bla foo);
','
uint8_t data[] = { 0xde, 0xad, 0xbe, 0xef, 0x03 };
DATA_BLOB b = { data, 5 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct TestAlloc r;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestAlloc(ndr, NDR_IN, &r)))
return 1;
if (r.in.foo.x == NULL)
return 2;
if (r.in.foo.x->data != 0x03)
return 3;
'
);
# Check that ref pointers aren't allocated by default
test_samba4_ndr("ref-noalloc-null",
'
[public] void TestAlloc([in,ref] uint8 *t);
','
uint8_t data[] = { 0x03 };
DATA_BLOB b = { data, 1 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct TestAlloc r;
r.in.t = NULL;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestAlloc(ndr, NDR_IN, &r)))
return 1;
'
);
# Check that ref pointers aren't allocated by default
test_samba4_ndr("ref-noalloc",
'
[public] void TestAlloc([in,ref] uint8 *t);
','
uint8_t data[] = { 0x03 };
DATA_BLOB b = { data, 1 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct TestAlloc r;
uint8_t x;
r.in.t = &x;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestAlloc(ndr, NDR_IN, &r)))
return 1;
if (*r.in.t != 0x03)
return 2;
'
);
# Check that an outgoing ref pointer is allocated correctly
test_samba4_ndr("ref-alloc",
'
[public] void TestAlloc([in,ref] uint8 *t);
','
uint8_t data[] = { 0x03 };
DATA_BLOB b = { data, 1 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct TestAlloc r;
ndr->flags |= LIBNDR_FLAG_REF_ALLOC;
r.in.t = NULL;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestAlloc(ndr, NDR_IN, &r)))
return 1;
if (r.in.t == NULL)
return 2;
if (*r.in.t != 0x03)
return 3;
'
); |
Perl | wireshark/tools/pidl/tests/ndr_array.pl | #!/usr/bin/perl
# Array testing
# (C) 2005 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use Test::More tests => 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
test_samba4_ndr(
'Fixed-Array',
'[public] void Test([in] uint8 x[10]);',
'
uint8_t data[] = {1,2,3,4,5,6,7,8,9,10};
int i;
DATA_BLOB b;
struct ndr_pull *ndr;
struct Test r;
b.data = data;
b.length = 10;
ndr = ndr_pull_init_blob(&b, mem_ctx, NULL);
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_Test(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 10)
return 2;
for (i = 0; i < 10; i++) {
if (r.in.x[i] != i+1) return 3;
}
'); |
Perl | wireshark/tools/pidl/tests/ndr_compat.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use Test::More tests => 2;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl;
use Parse::Pidl::IDL;
sub parse_idl($)
{
my $idl = shift;
my $pidl = Parse::Pidl::IDL::parse_string("interface echo { $idl }; ", "nofile");
Parse::Pidl::NDR::Parse($pidl);
}
test_warnings("", sub {parse_idl("void x();"); });
test_warnings("nofile:0: top-level [out] pointer `x' is not a [ref] pointer\n", sub {parse_idl("void x([out,unique] int *x);"); }); |
Perl | wireshark/tools/pidl/tests/ndr_deprecations.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 1;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Util qw(MyDumper);
use Parse::Pidl::NDR qw(ValidElement);
# Case 1
my $e = {
'FILE' => 'foo.idl',
'NAME' => 'v',
'PROPERTIES' => {"subcontext" => 1},
'POINTERS' => 0,
'TYPE' => 'uint8',
'PARENT' => { TYPE => 'STRUCT' },
'LINE' => 42 };
test_warnings("foo.idl:42: subcontext() is deprecated. Use represent_as() or transmit_as() instead\n",
sub { ValidElement($e); }); |
Perl | wireshark/tools/pidl/tests/ndr_fullptr.pl | #!/usr/bin/perl
# Simple tests for unique pointers
# (C) 2006 Jelmer Vernooij <[email protected]>.
# Published under the GNU General Public License.
use strict;
use Test::More tests => 1 * 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
SKIP: {
skip "full pointers not supported yet", 8;
test_samba4_ndr("fullptr-push-dup",
'
[public] uint16 echo_TestFull([in,ptr] uint32 *x, [in,ptr] uint32 *y);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
uint32_t v = 13;
struct echo_TestFull r;
r.in.x = &v;
r.in.y = &v;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestFull(ndr, NDR_IN, &r))) {
fprintf(stderr, "push failed\n");
return 1;
}
if (ndr->offset != 12) {
fprintf(stderr, "Offset(%d) != 12\n", ndr->offset);
return 2;
}
if (ndr->data[0] != ndr->data[8] ||
ndr->data[1] != ndr->data[9] ||
ndr->data[2] != ndr->data[10] ||
ndr->data[3] != ndr->data[11]) {
fprintf(stderr, "Data incorrect\n");
return 3;
}
');
} |
Perl | wireshark/tools/pidl/tests/ndr_refptr.pl | #!/usr/bin/perl
# Simple tests for pidl's handling of ref pointers, based
# on tridge's ref_notes.txt
# (C) 2005 Jelmer Vernooij <[email protected]>.
# Published under the GNU General Public License.
use strict;
use Test::More tests => 22 * 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
test_samba4_ndr("noptr-push",
' typedef struct {
uint16 x;
} xstruct;
[public] uint16 echo_TestRef([in] xstruct foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
uint16_t v = 13;
struct echo_TestRef r;
r.in.foo.x = v;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r))) {
fprintf(stderr, "push failed\n");
return 1;
}
if (ndr->offset != 2) {
fprintf(stderr, "Offset(%d) != 2\n", ndr->offset);
return 2;
}
if (ndr->data[0] != 13 || ndr->data[1] != 0) {
fprintf(stderr, "Data incorrect\n");
return 3;
}
');
test_samba4_ndr("ptr-embedded-push",
' typedef struct {
uint16 *x;
} xstruct;
[public] uint16 echo_TestRef([in] xstruct foo);
',
'
uint16_t v = 13;
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo.x = &v;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 6)
return 2;
if (ndr->data[0] == 0 && ndr->data[1] == 0 &&
ndr->data[2] == 0 && ndr->data[3] == 0)
return 3;
if (ndr->data[4] != 13 || ndr->data[5] != 0)
return 4;
');
test_samba4_ndr("ptr-embedded-push-null",
' typedef struct {
uint16 *x;
} xstruct;
[public] uint16 echo_TestRef([in] xstruct foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo.x = NULL;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 4)
return 2;
if (ndr->data[0] != 0 || ndr->data[1] != 0 ||
ndr->data[2] != 0 || ndr->data[3] != 0)
return 3;
');
test_samba4_ndr("refptr-embedded-push",
'
typedef struct {
[ref] uint16 *x;
} xstruct;
[public] uint16 echo_TestRef([in] xstruct foo);
',
'
uint16_t v = 13;
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo.x = &v;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 6)
return 2;
if (ndr->data[0] == 0 && ndr->data[1] == 0 &&
ndr->data[2] == 0 && ndr->data[3] == 0)
return 3;
if (ndr->data[4] != 13 || ndr->data[5] != 0)
return 4;
');
test_samba4_ndr("refptr-embedded-push-null",
'
typedef struct {
[ref] uint16 *x;
} xstruct;
[public] uint16 echo_TestRef([in] xstruct foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo.x = NULL;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
/* Windows gives [client runtime error 0x6f4] */
');
test_samba4_ndr("ptr-top-push",
'
typedef struct {
uint16 x;
} xstruct;
[public] uint16 echo_TestRef([in] xstruct *foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
struct xstruct s;
s.x = 13;
r.in.foo = &s;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 2)
return 2;
if (ndr->data[0] != 13 || ndr->data[1] != 0)
return 3;
');
test_samba4_ndr("ptr-top-push-null",
'
typedef struct {
uint16 x;
} xstruct;
[public] uint16 echo_TestRef([in] xstruct *foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo = NULL;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
/* Windows gives [client runtime error 0x6f4] */
');
test_samba4_ndr("refptr-top-push",
'
typedef struct {
uint16 x;
} xstruct;
[public] uint16 echo_TestRef([in,ref] xstruct *foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
struct xstruct s;
s.x = 13;
r.in.foo = &s;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 2)
return 2;
if (ndr->data[0] != 13 || ndr->data[1] != 0)
return 3;
');
test_samba4_ndr("refptr-top-push-null",
'
typedef struct {
uint16 x;
} xstruct;
[public] uint16 echo_TestRef([in,ref] xstruct *foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo = NULL;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
/* Windows gives [client runtime error 0x6f4] */
');
test_samba4_ndr("uniqueptr-top-push",
' typedef struct {
uint16 x;
} xstruct;
[public] uint16 echo_TestRef([in,unique] xstruct *foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
struct xstruct s;
s.x = 13;
r.in.foo = &s;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 6)
return 2;
if (ndr->data[0] == 0 && ndr->data[1] == 0 &&
ndr->data[2] == 0 && ndr->data[3] == 0)
return 3;
if (ndr->data[4] != 13 || ndr->data[5] != 0)
return 4;
');
test_samba4_ndr("uniqueptr-top-push-null",
' typedef struct {
uint16 x;
} xstruct;
[public] uint16 echo_TestRef([in,unique] xstruct *foo);
',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo = NULL;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 4)
return 2;
if (ndr->data[0] != 0 || ndr->data[1] != 0 ||
ndr->data[2] != 0 || ndr->data[3] != 0)
return 3;
');
test_samba4_ndr("ptr-top-out-pull",
'
typedef struct {
uint16 x;
} xstruct;
[public] void echo_TestRef([out] xstruct *foo);
',
'
uint8_t data[] = { 0x0D, 0x00 };
DATA_BLOB b = { data, 2 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct xstruct s;
struct echo_TestRef r;
r.out.foo = &s;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_echo_TestRef(ndr, NDR_OUT, &r)))
return 1;
if (!r.out.foo)
return 2;
if (r.out.foo->x != 13)
return 3;
');
test_samba4_ndr("ptr-top-out-pull-null",
'
typedef struct {
uint16 x;
} xstruct;
[public] void echo_TestRef([out] xstruct *foo);
',
'
uint8_t data[] = { 0x0D, 0x00 };
DATA_BLOB b = { data, 2 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct echo_TestRef r;
r.out.foo = NULL;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_pull_echo_TestRef(ndr, NDR_OUT, &r)))
return 1;
/* Windows gives [client runtime error 0x6f4] */
');
test_samba4_ndr("refptr-top-out-pull",
'
typedef struct {
uint16 x;
} xstruct;
[public] void echo_TestRef([out,ref] xstruct *foo);
',
'
uint8_t data[] = { 0x0D, 0x00 };
DATA_BLOB b = { data, 2 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct xstruct s;
struct echo_TestRef r;
r.out.foo = &s;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_echo_TestRef(ndr, NDR_OUT, &r)))
return 1;
if (!r.out.foo)
return 2;
if (r.out.foo->x != 13)
return 3;
');
test_samba4_ndr("refptr-top-out-pull-null",
'
typedef struct {
uint16 x;
} xstruct;
[public] void echo_TestRef([out,ref] xstruct *foo);
',
'
uint8_t data[] = { 0x0D, 0x00 };
DATA_BLOB b = { data, 2 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL, NULL);
struct echo_TestRef r;
r.out.foo = NULL;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_pull_echo_TestRef(ndr, NDR_OUT, &r)))
return 1;
/* Windows gives [client runtime error 0x6f4] */
');
test_samba4_ndr("ptr-top-push-double",
'
[public] void echo_TestRef([in] uint16 **foo);
',
' struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
uint16_t v = 13;
uint16_t *pv = &v;
r.in.foo = &pv;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 6)
return 2;
if (ndr->data[0] == 0 && ndr->data[1] == 0 &&
ndr->data[2] == 0 && ndr->data[3] == 0)
return 3;
if (ndr->data[4] != 0x0D || ndr->data[5] != 0x00)
return 4;
');
SKIP: {
skip "ptr-top-push-double-sndnull is known to fail", 8;
test_samba4_ndr("ptr-top-push-double-sndnull",
'
[public] void echo_TestRef([in] uint16 **foo);
',
' struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
uint16_t *pv = NULL;
r.in.foo = &pv;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 4)
return 2;
if (ndr->data[0] != 0 || ndr->data[1] != 0 ||
ndr->data[2] != 0 || ndr->data[3] != 0)
return 3;
');
}
test_samba4_ndr("ptr-top-push-double-fstnull",
'
[public] void echo_TestRef([in] uint16 **foo);
',
' struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo = NULL;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
/* Windows gives [client runtime error 0x6f4] */
');
test_samba4_ndr("refptr-top-push-double",
'
[public] void echo_TestRef([in,ref] uint16 **foo);
',
' struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
uint16_t v = 13;
uint16_t *pv = &v;
r.in.foo = &pv;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 6)
return 2;
if (ndr->data[0] == 0 && ndr->data[1] == 0 &&
ndr->data[2] == 0 && ndr->data[3] == 0)
return 3;
if (ndr->data[4] != 0x0D || ndr->data[5] != 0x00)
return 4;
');
SKIP: {
skip "refptr-top-push-double-sndnull is known to fail", 8;
test_samba4_ndr("refptr-top-push-double-sndnull",
'
[public] void echo_TestRef([in,ref] uint16 **foo);
',
' struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
uint16_t *pv = NULL;
r.in.foo = &pv;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 4)
return 2;
if (ndr->data[0] != 0 || ndr->data[1] != 0 ||
ndr->data[2] != 0 || ndr->data[3] != 0)
return 3;
');
}
test_samba4_ndr("refptr-top-push-double-fstnull",
'
[public] void echo_TestRef([in,ref] uint16 **foo);
',
' struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
r.in.foo = NULL;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
/* Windows gives [client runtime error 0x6f4] */
');
SKIP: {
skip "ignore-ptrs are not supported yet", 8;
test_samba4_ndr("ignore-ptr",
'
[public] void echo_TestRef([in,ignore] uint16 *foo, [in] uint16 *bar);
',
' struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct echo_TestRef r;
uint16_t v = 10;
r.in.foo = &v;
r.in.bar = &v;
if (NDR_ERR_CODE_IS_SUCCESS(ndr_push_echo_TestRef(ndr, NDR_IN, &r)))
return 1;
if (ndr->offset != 4)
return 2;
');
} |
Perl | wireshark/tools/pidl/tests/ndr_represent.pl | #!/usr/bin/perl
# NDR represent_as() / transmit_as() tests
# (C) 2006 Jelmer Vernooij. Published under the GNU GPL
use strict;
use Test::More tests => 2 * 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
test_samba4_ndr('represent_as-simple',
'
void bla([in,represent_as(uint32)] uint8 x);
',
'
uint8_t expected[] = { 0x0D };
DATA_BLOB in_blob = { expected, 1 };
struct ndr_pull *ndr = ndr_pull_init_blob(&in_blob, NULL, NULL);
struct bla r;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_bla(ndr, NDR_SCALARS|NDR_BUFFERS, &r)))
return 1;
if (r.in.x != 13)
return 2;
',
'
enum ndr_err_code ndr_uint8_to_uint32(uint8_t from, uint32_t *to)
{
*to = from;
return NDR_ERR_SUCCESS;
}
enum ndr_err_code ndr_uint32_to_uint8(uint32_t from, uint8_t *to)
{
*to = from;
return NDR_ERR_SUCCESS;
}
'
);
test_samba4_ndr('transmit_as-simple',
'
void bla([in,transmit_as(uint32)] uint8 x);
',
'
uint8_t expected[] = { 0x0D };
DATA_BLOB in_blob = { expected, 1 };
struct ndr_pull *ndr = ndr_pull_init_blob(&in_blob, NULL, NULL);
struct bla r;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_bla(ndr, NDR_SCALARS|NDR_BUFFERS, &r)))
return 1;
if (r.in.x != 13)
return 2;
',
'
enum ndr_err_code ndr_uint8_to_uint32(uint8_t from, uint32_t *to)
{
*to = from;
return NDR_ERR_SUCCESS;
}
enum ndr_err_code ndr_uint32_to_uint8(uint32_t from, uint8_t *to)
{
*to = from;
return NDR_ERR_SUCCESS;
}
'
); |
Perl | wireshark/tools/pidl/tests/ndr_simple.pl | #!/usr/bin/perl
# Some simple tests for pidl
# (C) 2005 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use Test::More tests => 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
test_samba4_ndr("simple", "void Test(); ",
"
uint8_t data[] = { 0x02 };
uint8_t result;
DATA_BLOB b;
struct ndr_pull *ndr;
b.data = data;
b.length = 1;
ndr = ndr_pull_init_blob(&b, mem_ctx, NULL);
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_uint8(ndr, NDR_SCALARS, &result)))
return 1;
if (result != 0x02)
return 2;
"); |
Perl | wireshark/tools/pidl/tests/ndr_string.pl | #!/usr/bin/perl
# String tests for pidl
# (C) 2005 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use Test::More tests => 6 * 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
test_samba4_ndr("string-pull-empty",
' [public] void TestString([in,flag(STR_ASCII|LIBNDR_FLAG_STR_SIZE4)] string data);',
'
uint8_t data[] = { 0x00, 0x00, 0x00, 0x00 };
DATA_BLOB b = { data, 4 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL);
struct TestString r;
r.in.data = NULL;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestString(ndr, NDR_IN, &r)))
return 1;
if (r.in.data == NULL)
return 2;
if (r.in.data[0] != 0)
return 3;
');
test_samba4_ndr("string-ascii-pull",
'
[public] void TestString([in,flag(STR_ASCII|LIBNDR_FLAG_STR_SIZE4)] string data);
',
'
uint8_t data[] = { 0x03, 0x00, 0x00, 0x00,
\'f\', \'o\', \'o\', 0 };
DATA_BLOB b = { data, 8 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL);
struct TestString r;
r.in.data = NULL;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestString(ndr, NDR_IN, &r)))
return 1;
if (r.in.data == NULL)
return 2;
if (strncmp(r.in.data, "foo", 3) != 0)
return 3;
if (r.in.data[4] != 0)
return 4;
');
test_samba4_ndr("string-wchar-fixed-array-01",
'
typedef struct {
uint32 l1;
[string,charset(UTF16)] uint16 str[6];
uint32 l2;
} TestStringStruct;
[public] void TestString([in,ref] TestStringStruct *str);
',
'
uint8_t data[] = { 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00,
\'f\', 0x00, \'o\', 0x00,
\'o\', 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00
};
DATA_BLOB b = { data, sizeof(data) };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL);
struct TestString r;
struct TestStringStruct str;
r.in.str = &str;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestString(ndr, NDR_IN, &r)))
return 1;
if (r.in.str == NULL)
return 2;
if (r.in.str->l1 != 0x00000001)
return 3;
if (strncmp(str.str, "foo", 3) != 0)
return 4;
if (r.in.str->str[4] != 0)
return 5;
if (r.in.str->l2 != 0x00000002)
return 6;
');
test_samba4_ndr("string-wchar-fixed-array-02",
'
typedef struct {
uint32 l1;
[string,charset(UTF16)] uint16 str[6];
uint32 l2;
} TestStringStruct;
[public] void TestString([in,ref] TestStringStruct *str);
',
'
uint8_t data[] = { 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00,
\'f\', 0x00, \'o\', 0x00,
\'o\', 0x00, \'b\', 0x00,
\'a\', 0x00, \'r\', 0x00,
0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00
};
DATA_BLOB b = { data, sizeof(data) };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL);
struct TestString r;
struct TestStringStruct str;
r.in.str = &str;
/* the string terminator is wrong */
if (NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestString(ndr, NDR_IN, &r)))
return 1;
');
test_samba4_ndr("string-wchar-fixed-array-03",
'
typedef struct {
uint32 l1;
[string,charset(UTF16)] uint16 str[6];
uint32 l2;
} TestStringStruct;
[public] void TestString([in,ref] TestStringStruct *str);
',
'
uint8_t data[] = { 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00,
\'f\', 0x00, \'o\', 0x00,
\'o\', 0x00, \'b\', 0x00,
\'a\', 0x00, \'r\', 0x00,
0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00
};
DATA_BLOB b = { data, sizeof(data) };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL);
struct TestString r;
struct TestStringStruct str;
r.in.str = &str;
/* the length 0x07 is to large */
if (NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestString(ndr, NDR_IN, &r)))
return 1;
');
SKIP: {
skip "doesn't seem to work yet", 8;
test_samba4_ndr("string-out",
'
[public] void TestString([out,string,charset(UNIX)] uint8 **data);
',
'
uint8_t data[] = { 0x03, 0x00, 0x00, 0x00,
\'f\', \'o\', \'o\', 0 };
DATA_BLOB b = { data, 8 };
struct ndr_pull *ndr = ndr_pull_init_blob(&b, NULL);
struct TestString r;
char *str = NULL;
r.out.data = &str;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_pull_TestString(ndr, NDR_IN, &r)))
return 1;
if (r.out.data == NULL)
return 2;
if (*r.out.data == NULL)
return 3;
if (strncmp(r.out.data, "foo", 3) != 0)
return 4;
if (r.out.data[4] != 0)
return 5;
');
} |
Perl | wireshark/tools/pidl/tests/ndr_tagtype.pl | #!/usr/bin/perl
# Support for tagged types
# (C) 2005 Jelmer Vernooij. Published under the GNU GPL
use strict;
use Test::More tests => 3 * 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_samba4_ndr);
test_samba4_ndr('struct-notypedef', '[public] struct bla { uint8 x; }; ',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct bla r;
uint8_t expected[] = { 0x0D };
DATA_BLOB expected_blob = { expected, 1 };
DATA_BLOB result_blob;
r.x = 13;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_STRUCT_bla(ndr, NDR_SCALARS|NDR_BUFFERS, &r)))
return 1;
result_blob = ndr_push_blob(ndr);
if (data_blob_cmp(&result_blob, &expected_blob) != 0)
return 2;
');
test_samba4_ndr('struct-notypedef-used', '[public] struct bla { uint8 x; };
[public] void myfn([in] struct bla r); ',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct myfn fn;
uint8_t expected[] = { 0x0D };
DATA_BLOB expected_blob = { expected, 1 };
DATA_BLOB result_blob;
fn.in.r.x = 13;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_myfn(ndr, NDR_IN, &fn)))
return 1;
result_blob = ndr_push_blob(ndr);
if (data_blob_cmp(&result_blob, &expected_blob) != 0)
return 2;
');
test_samba4_ndr('struct-notypedef-embedded', 'struct bla { uint8 x; };
[public] struct myst { struct bla r; }; ',
'
struct ndr_push *ndr = ndr_push_init_ctx(NULL, NULL);
struct myst st;
uint8_t expected[] = { 0x0D };
DATA_BLOB expected_blob = { expected, 1 };
DATA_BLOB result_blob;
st.r.x = 13;
if (!NDR_ERR_CODE_IS_SUCCESS(ndr_push_STRUCT_myst(ndr, NDR_IN, &st)))
return 1;
result_blob = ndr_push_blob(ndr);
if (data_blob_cmp(&result_blob, &expected_blob) != 0)
return 2;
'); |
Perl | wireshark/tools/pidl/tests/parse_idl.pl | #!/usr/bin/perl
# Some simple tests for pidls parsing routines
# (C) 2005 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use Test::More tests => 65 * 2 + 7;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_errors);
use Parse::Pidl::IDL;
use Parse::Pidl::NDR;
sub testok($$)
{
my ($name, $data) = @_;
test_errors("", sub {
my $pidl = Parse::Pidl::IDL::parse_string($data, "<$name>");
ok (defined($pidl), $name);
});
}
sub testfail($$$)
{
my ($name, $data, $error) = @_;
test_errors($error, sub {
my $pidl = Parse::Pidl::IDL::parse_string($data, "<$name>");
ok ((not defined $pidl), $name);
});
}
testfail "unknowntag", "bla test {};",
"<unknowntag>:0: Syntax error near 'bla'\n";
testok "test1", "interface test { void Test(); }; ";
testok "voidtest", "interface test { int Testx(void); }; ";
testfail "voidtest", "interface test { Test(); }; ",
"<voidtest>:0: Syntax error near '('\n";
testok "argtest", "interface test { int Test(int a, long b, uint32 c); }; ";
testok "array1", "interface test { int Test(int a[]); };";
testok "array2", "interface test { int Test(int a[2]); };";
testok "array3", "interface test { int Test(int a[b]); };";
testfail "array4", "interface test { int Test(int[] a); };",
"<array4>:0: Syntax error near '['\n";
testok "ptr1", "interface test { int Test(int *a); };";
testok "ptr2", "interface test { int Test(int **a); };";
testok "ptr3", "interface test { int Test(int ***a); };";
testfail "empty1", "interface test { };", "<empty1>:0: Syntax error near '}'\n";
testfail "empty2", "", "";
testok "attr1", "[uuid(\"myuuid\"),attr] interface test { int Test(int ***a); };";
testok "attr2", "interface test { [public] int Test(); };";
testok "attr3", "[attr1] [attr2] interface test { [public] int Test(); };";
testok "multfn", "interface test { int test1(); int test2(); };";
testok "multif", "interface test { int test1(); }; interface test2 { int test2(); };";
testok "tdstruct1", "interface test { typedef struct { } foo; };";
testok "tdstruct2", "interface test { typedef struct { int a; } foo; };";
testok "tdstruct3", "interface test { typedef struct { int a; int b; } foo; };";
testfail "tdstruct4", "interface test { typedef struct { int a, int b; } foo; };",
"<tdstruct4>:0: Syntax error near ','\n";
testok "struct1", "interface test { struct x { }; };";
testok "struct2", "interface test { struct x { int a; }; };";
testok "struct3", "interface test { struct x { int a; int b; }; };";
testfail "struct4", "interface test { struct x { int a, int b; }; };",
"<struct4>:0: Syntax error near ','\n";
testfail "struct5", "interface test { struct { int a; } x; };",
"<struct5>:0: Syntax error near 'x'\n";
testok "tdunion1", "interface test { typedef union { } a; };";
testok "tdunion2", "interface test { typedef union { int a; } a; };";
testok "union1", "interface test { union a { }; };";
testok "union2", "interface test { union x { int a; }; };";
testfail "union3", "interface test { union { int a; } x; };",
"<union3>:0: Syntax error near 'x'\n";
testok "typedef1", "interface test { typedef int a; };";
testfail "typedef2", "interface test { typedef x; };",
"<typedef2>:0: Syntax error near ';'\n";
testok "tdenum1", "interface test { typedef enum { A=1, B=2, C} a; };";
testok "enum1", "interface test { enum a { A=1, B=2, C}; };";
testfail "enum2", "interface test { enum { A=1, B=2, C} a; };",
"<enum2>:0: Syntax error near 'a'\n";
testok "nested1", "interface test { struct x { struct { int a; } z; }; };";
testok "nested2", "interface test { struct x { struct y { int a; } z; }; };";
testok "bitmap1", "interface test { bitmap x { a=1 }; };";
testok "unsigned", "interface test { struct x { unsigned short y; }; };";
testok "struct-property", "interface test { [public] struct x { short y; }; };";
testok "signed", "interface test { struct x { signed short y; }; };";
testok "declarg", "interface test { void test(struct { int x; } a); };";
testok "structarg", "interface test { void test(struct a b); };";
testfail "structargmissing", "interface test { void test(struct a); };",
"<structargmissing>:0: Syntax error near ')'\n";
testok "structqual", "interface test { struct x { struct y z; }; };";
testok "unionqual", "interface test { struct x { union y z; }; };";
testok "enumqual", "interface test { struct x { enum y z; }; };";
testok "bitmapqual", "interface test { struct x { bitmap y z; }; };";
testok "emptystructdecl", "interface test { struct x; };";
testok "emptyenumdecl", "interface test { enum x; };";
testok "emptytdstructdecl", "interface test { typedef struct x y; };";
testok "import", "import \"foo.idl\";";
testok "include", "include \"foo.h\";";
testfail "import-noquotes", "import foo.idl;",
"<import-noquotes>:0: Syntax error near 'foo'\n";
testfail "include-noquotes", "include foo.idl;",
"<include-noquotes>:0: Syntax error near 'foo'\n";
testok "importlib", "importlib \"foo.idl\";";
testfail "import-nosemicolon", "import \"foo.idl\"",
"<import-nosemicolon>:0: Syntax error near 'foo.idl'\n";
testok "import-multiple", "import \"foo.idl\", \"bar.idl\";";
testok "include-multiple", "include \"foo.idl\", \"bar.idl\";";
testok "empty-struct", "interface test { struct foo { }; }";
testok "typedef-double", "interface test { typedef struct foo { } foo; }";
testok "cpp-quote", "cpp_quote(\"bla\")";
my $x = Parse::Pidl::IDL::parse_string("interface foo { struct x {}; }", "<foo>");
is_deeply($x, [ {
'TYPE' => 'INTERFACE',
'NAME' => 'foo',
'DATA' => [ {
'TYPE' => 'STRUCT',
'NAME' => 'x',
'ELEMENTS' => [],
'FILE' => '<foo>',
'LINE' => 0
} ],
'FILE' => '<foo>',
'LINE' => 0
}]);
$x = Parse::Pidl::IDL::parse_string("interface foo { struct x; }", "<foo>");
is_deeply($x, [ {
'TYPE' => 'INTERFACE',
'NAME' => 'foo',
'DATA' => [ {
'TYPE' => 'STRUCT',
'NAME' => 'x',
'FILE' => '<foo>',
'LINE' => 0
} ],
'FILE' => '<foo>',
'LINE' => 0
}]);
$x = Parse::Pidl::IDL::parse_string("cpp_quote(\"foobar\")", "<quote>");
is_deeply($x, [ {
'TYPE' => 'CPP_QUOTE',
'DATA' => '"foobar"',
'FILE' => '<quote>',
'LINE' => 0
}]);
# A typedef of a struct without body
$x = Parse::Pidl::IDL::parse_string("interface foo { typedef struct x y; }", "<foo>");
is_deeply($x, [ {
'TYPE' => 'INTERFACE',
'NAME' => 'foo',
'DATA' => [ {
'TYPE' => 'TYPEDEF',
'NAME' => 'y',
'POINTERS' => 0,
'DATA' => {
'TYPE' => 'STRUCT',
'NAME' => 'x',
'FILE' => '<foo>',
'LINE' => 0,
},
'FILE' => '<foo>',
'LINE' => 0,
} ],
'FILE' => '<foo>',
'LINE' => 0
}]);
# A typedef of a struct with empty body
$x = Parse::Pidl::IDL::parse_string("interface foo { typedef struct {} y; }", "<foo>");
is_deeply($x, [ {
'TYPE' => 'INTERFACE',
'NAME' => 'foo',
'DATA' => [ {
'TYPE' => 'TYPEDEF',
'NAME' => 'y',
'POINTERS' => 0,
'DATA' => {
'TYPE' => 'STRUCT',
'ELEMENTS' => [],
'FILE' => '<foo>',
'LINE' => 0
},
'FILE' => '<foo>',
'LINE' => 0
} ],
'FILE' => '<foo>',
'LINE' => 0
}]);
# A typedef of a bitmap with no body
$x = Parse::Pidl::IDL::parse_string("interface foo { typedef bitmap x y; }", "<foo>");
is_deeply($x, [ {
'TYPE' => 'INTERFACE',
'NAME' => 'foo',
'DATA' => [ {
'TYPE' => 'TYPEDEF',
'NAME' => 'y',
'POINTERS' => 0,
'DATA' => {
'TYPE' => 'BITMAP',
'NAME' => 'x',
'FILE' => '<foo>',
'LINE' => 0
},
'FILE' => '<foo>',
'LINE' => 0
} ],
'FILE' => '<foo>',
'LINE' => 0
}]);
# A typedef of a union with no body
$x = Parse::Pidl::IDL::parse_string("interface foo { typedef union x y; }", "<foo>");
is_deeply($x, [ {
'TYPE' => 'INTERFACE',
'NAME' => 'foo',
'DATA' => [ {
'TYPE' => 'TYPEDEF',
'NAME' => 'y',
'POINTERS' => 0,
'DATA' => {
'TYPE' => 'UNION',
'NAME' => 'x',
'FILE' => '<foo>',
'LINE' => 0
},
'FILE' => '<foo>',
'LINE' => 0
} ],
'FILE' => '<foo>',
'LINE' => 0
}]); |
Perl | wireshark/tools/pidl/tests/samba-ndr.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 31;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use strict;
use Parse::Pidl::Util qw(MyDumper);
use Parse::Pidl::Samba4::NDR::Parser qw(check_null_pointer
NeededFunction NeededElement NeededType
NeededInterface TypeFunctionName ParseElementPrint);
my $output;
sub print_fn($) { my $x = shift; $output.=$x; }
# Test case 1: Simple unique pointer dereference
$output = "";
my $fn = check_null_pointer({
PARENT => {
ELEMENTS => [
{
NAME => "bla",
LEVELS => [
{ TYPE => "POINTER",
POINTER_INDEX => 0,
POINTER_TYPE => "unique" },
{ TYPE => "DATA" }
],
},
]
}
}, { bla => "r->in.bla" }, \&print_fn, "return;");
test_warnings("", sub { $fn->("r->in.bla"); });
is($output, "if (r->in.bla == NULL) return;");
# Test case 2: Simple ref pointer dereference
$output = "";
$fn = check_null_pointer({
PARENT => {
ELEMENTS => [
{
NAME => "bla",
LEVELS => [
{ TYPE => "POINTER",
POINTER_INDEX => 0,
POINTER_TYPE => "ref" },
{ TYPE => "DATA" }
],
},
]
}
}, { bla => "r->in.bla" }, \&print_fn, undef);
test_warnings("", sub { $fn->("r->in.bla"); });
is($output, "");
# Test case 3: Illegal dereference
$output = "";
$fn = check_null_pointer({
FILE => "nofile",
LINE => 1,
PARENT => {
ELEMENTS => [
{
NAME => "bla",
LEVELS => [
{ TYPE => "DATA" }
],
},
]
}
}, { bla => "r->in.bla" }, \&print_fn, undef);
test_warnings("nofile:1: too much dereferences for `bla'\n",
sub { $fn->("r->in.bla"); });
is($output, "");
# Test case 4: Double pointer dereference
$output = "";
$fn = check_null_pointer({
PARENT => {
ELEMENTS => [
{
NAME => "bla",
LEVELS => [
{ TYPE => "POINTER",
POINTER_INDEX => 0,
POINTER_TYPE => "unique" },
{ TYPE => "POINTER",
POINTER_INDEX => 1,
POINTER_TYPE => "unique" },
{ TYPE => "DATA" }
],
},
]
}
}, { bla => "r->in.bla" }, \&print_fn, "return;");
test_warnings("",
sub { $fn->("*r->in.bla"); });
is($output, "if (*r->in.bla == NULL) return;");
# Test case 5: Unknown variable
$output = "";
$fn = check_null_pointer({
FILE => "nofile",
LINE => 2,
PARENT => {
ELEMENTS => [
{
NAME => "bla",
LEVELS => [
{ TYPE => "DATA" }
],
},
]
}
}, { }, \&print_fn, "return;");
test_warnings("nofile:2: unknown dereferenced expression `r->in.bla'\n",
sub { $fn->("r->in.bla"); });
is($output, "if (r->in.bla == NULL) return;");
my $needed = {};
NeededElement({ TYPE => "foo", REPRESENTATION_TYPE => "foo" }, "pull", $needed);
is_deeply($needed, { ndr_pull_foo => 1 });
# old settings should be kept
$needed = { ndr_pull_foo => 0 };
NeededElement({ TYPE => "foo", REPRESENTATION_TYPE => "foo" }, "pull", $needed);
is_deeply($needed, { ndr_pull_foo => 0 });
# print/pull/push are independent of each other
$needed = { ndr_pull_foo => 0 };
NeededElement({ TYPE => "foo", REPRESENTATION_TYPE => "foo" }, "print", $needed);
is_deeply($needed, { ndr_pull_foo => 0, ndr_print_foo => 1 });
$needed = { };
NeededFunction({ NAME => "foo", ELEMENTS => [ { TYPE => "bar", REPRESENTATION_TYPE => "bar" } ] }, $needed);
is_deeply($needed, { ndr_pull_foo => 1, ndr_print_foo => 1, ndr_push_foo => 1,
ndr_pull_bar => 1, ndr_print_bar => 1, ndr_push_bar => 1});
# push/pull/print are always set for functions
$needed = { ndr_pull_foo => 0 };
NeededFunction({ NAME => "foo", ELEMENTS => [ { TYPE => "bar", REPRESENTATION_TYPE => "bar" } ] }, $needed);
is_deeply($needed, { ndr_pull_foo => 1, ndr_print_foo => 1, ndr_push_foo => 1,
ndr_pull_bar => 1, ndr_push_bar => 1, ndr_print_bar => 1});
# public structs are always needed
$needed = {};
NeededType({ NAME => "bla", TYPE => "TYPEDEF",
DATA => { TYPE => "STRUCT", ELEMENTS => [] } },
$needed, "pull");
is_deeply($needed, { });
$needed = {};
NeededInterface({ TYPES => [ { PROPERTIES => { public => 1 }, NAME => "bla",
TYPE => "TYPEDEF",
DATA => { TYPE => "STRUCT", ELEMENTS => [] } } ] },
$needed);
is_deeply($needed, { ndr_pull_bla => 1, ndr_push_bla => 1, ndr_print_bla => 1 });
# make sure types for elements are set too
$needed = {};
NeededInterface({ TYPES => [ { PROPERTIES => { public => 1 }, NAME => "bla",
TYPE => "TYPEDEF",
DATA => { TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "bar", REPRESENTATION_TYPE => "bar" } ] } } ] },
$needed);
is_deeply($needed, { ndr_pull_bla => 1, ndr_pull_bar => 1, ndr_push_bla => 1, ndr_push_bar => 1,
ndr_print_bla => 1, ndr_print_bar => 1});
$needed = {};
NeededInterface({ TYPES => [ { PROPERTIES => { gensize => 1}, NAME => "bla",
TYPE => "TYPEDEF",
DATA => { TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "bar", REPRESENTATION_TYPE => "bar" } ] } } ] },
$needed);
is_deeply($needed, { ndr_size_bla => 1 });
# make sure types for elements are set too
$needed = { ndr_pull_bla => 1 };
NeededType({ NAME => "bla",
TYPE => "TYPEDEF",
DATA => { TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "bar", REPRESENTATION_TYPE => "bar" } ] } },
$needed, "pull");
is_deeply($needed, { ndr_pull_bla => 1, ndr_pull_bar => 1 });
$needed = {};
NeededInterface({ TYPES => [ { PROPERTIES => { public => 1},
NAME => "bla",
TYPE => "TYPEDEF",
DATA => { TYPE => "STRUCT",
ELEMENTS => [ { TYPE => "bar", REPRESENTATION_TYPE => "rep" } ] } } ] }, $needed);
is_deeply($needed, { ndr_pull_bla => 1, ndr_push_bla => 1, ndr_print_bla => 1,
ndr_print_rep => 1,
ndr_pull_bar => 1, ndr_push_bar => 1,
ndr_bar_to_rep => 1, ndr_rep_to_bar => 1});
my $generator = new Parse::Pidl::Samba4::NDR::Parser();
$generator->ParseStructPush({
NAME => "mystruct",
TYPE => "STRUCT",
PROPERTIES => {},
ALIGN => 4,
ELEMENTS => [ ]}, "ndr", "x");
is($generator->{res}, "NDR_PUSH_CHECK_FLAGS(ndr, ndr_flags);
if (ndr_flags & NDR_SCALARS) {
NDR_CHECK(ndr_push_align(ndr, 4));
NDR_CHECK(ndr_push_trailer_align(ndr, 4));
}
if (ndr_flags & NDR_BUFFERS) {
}
");
$generator = new Parse::Pidl::Samba4::NDR::Parser();
my $e = {
NAME => "el1",
TYPE => "mytype",
REPRESENTATION_TYPE => "mytype",
PROPERTIES => {},
LEVELS => [
{ LEVEL_INDEX => 0, TYPE => "DATA", DATA_TYPE => "mytype" }
] };
$generator->ParseStructPush({
NAME => "mystruct",
TYPE => "STRUCT",
PROPERTIES => {},
ALIGN => 4,
SURROUNDING_ELEMENT => $e,
ELEMENTS => [ $e ]}, "ndr", "x");
is($generator->{res}, "NDR_PUSH_CHECK_FLAGS(ndr, ndr_flags);
if (ndr_flags & NDR_SCALARS) {
NDR_CHECK(ndr_push_uint3264(ndr, NDR_SCALARS, ndr_string_array_size(ndr, x->el1)));
NDR_CHECK(ndr_push_align(ndr, 4));
NDR_CHECK(ndr_push_mytype(ndr, NDR_SCALARS, &x->el1));
NDR_CHECK(ndr_push_trailer_align(ndr, 4));
}
if (ndr_flags & NDR_BUFFERS) {
}
");
is(TypeFunctionName("ndr_pull", "uint32"), "ndr_pull_uint32");
is(TypeFunctionName("ndr_pull", {TYPE => "ENUM", NAME => "bar"}), "ndr_pull_ENUM_bar");
is(TypeFunctionName("ndr_pull", {TYPE => "TYPEDEF", NAME => "bar", DATA => undef}), "ndr_pull_bar");
is(TypeFunctionName("ndr_push", {TYPE => "STRUCT", NAME => "bar"}), "ndr_push_STRUCT_bar");
# check noprint works
$generator = new Parse::Pidl::Samba4::NDR::Parser();
$generator->ParseElementPrint({ NAME => "x", TYPE => "rt", REPRESENTATION_TYPE => "rt",
PROPERTIES => { noprint => 1},
LEVELS => [ { TYPE => "DATA", DATA_TYPE => "rt"} ]},
"ndr", "var", { "x" => "r->foobar" } );
is($generator->{res}, "");
$generator = new Parse::Pidl::Samba4::NDR::Parser();
$generator->ParseElementPrint({ NAME => "x", TYPE => "rt", REPRESENTATION_TYPE => "rt",
PROPERTIES => {},
LEVELS => [ { TYPE => "DATA", DATA_TYPE => "rt" }]},
"ndr", "var", { "x" => "r->foobar" } );
is($generator->{res}, "ndr_print_rt(ndr, \"x\", &var);\n");
# make sure that a print function for an element with value() set works
$generator = new Parse::Pidl::Samba4::NDR::Parser();
$generator->ParseElementPrint({ NAME => "x", TYPE => "uint32", REPRESENTATION_TYPE => "uint32",
PROPERTIES => { value => "23" },
LEVELS => [ { TYPE => "DATA", DATA_TYPE => "uint32"} ]},
"ndr", "var", { "x" => "r->foobar" } );
is($generator->{res}, "ndr_print_uint32(ndr, \"x\", (ndr->flags & LIBNDR_PRINT_SET_VALUES)?23:var);\n");
$generator = new Parse::Pidl::Samba4::NDR::Parser();
$generator->AuthServiceStruct("bridge", "\"rot13\",\"onetimepad\"");
is($generator->{res}, "static const char * const bridge_authservice_strings[] = {
\"rot13\",
\"onetimepad\",
};
static const struct ndr_interface_string_array bridge_authservices = {
.count = 2,
.names = bridge_authservice_strings
};
"); |
Perl | wireshark/tools/pidl/tests/samba3-cli.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 8;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Util qw(MyDumper);
use Parse::Pidl::Samba3::ClientNDR qw(ParseFunction);
use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv);
# Make sure GenerateFunctionInEnv and GenerateFunctionOutEnv work
my $fn = { ELEMENTS => [ { DIRECTION => ["in"], NAME => "foo" } ] };
is_deeply({ "foo" => "r.in.foo" }, GenerateFunctionInEnv($fn, "r."));
is_deeply({ "foo" => "r.in.foo" }, GenerateFunctionOutEnv($fn, "r."));
$fn = { ELEMENTS => [ { DIRECTION => ["out", "in"], NAME => "foo" } ] };
is_deeply({ "foo" => "r.in.foo" }, GenerateFunctionInEnv($fn, "r."));
is_deeply({ "foo" => "r.out.foo" }, GenerateFunctionOutEnv($fn, "r."));
$fn = { ELEMENTS => [ { DIRECTION => ["out"], NAME => "foo" } ] };
is_deeply({ }, GenerateFunctionInEnv($fn, "r."));
is_deeply({ "foo" => "r.out.foo" }, GenerateFunctionOutEnv($fn, "r."));
my $x = new Parse::Pidl::Samba3::ClientNDR();
$fn = { NAME => "bar", ELEMENTS => [ ] };
$x->ParseFunction("foo", $fn);
is($x->{res},
"struct rpccli_bar_state {
TALLOC_CTX *out_mem_ctx;
};
static void rpccli_bar_done(struct tevent_req *subreq);
struct tevent_req *rpccli_bar_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct rpc_pipe_client *cli)
{
struct tevent_req *req;
struct rpccli_bar_state *state;
struct tevent_req *subreq;
req = tevent_req_create(mem_ctx, &state,
struct rpccli_bar_state);
if (req == NULL) {
return NULL;
}
state->out_mem_ctx = NULL;
subreq = dcerpc_bar_send(state,
ev,
cli->binding_handle);
if (tevent_req_nomem(subreq, req)) {
return tevent_req_post(req, ev);
}
tevent_req_set_callback(subreq, rpccli_bar_done, req);
return req;
}
static void rpccli_bar_done(struct tevent_req *subreq)
{
struct tevent_req *req = tevent_req_callback_data(
subreq, struct tevent_req);
struct rpccli_bar_state *state = tevent_req_data(
req, struct rpccli_bar_state);
NTSTATUS status;
TALLOC_CTX *mem_ctx;
if (state->out_mem_ctx) {
mem_ctx = state->out_mem_ctx;
} else {
mem_ctx = state;
}
status = dcerpc_bar_recv(subreq,
mem_ctx);
TALLOC_FREE(subreq);
if (!NT_STATUS_IS_OK(status)) {
tevent_req_nterror(req, status);
return;
}
tevent_req_done(req);
}
NTSTATUS rpccli_bar_recv(struct tevent_req *req,
TALLOC_CTX *mem_ctx)
{
struct rpccli_bar_state *state = tevent_req_data(
req, struct rpccli_bar_state);
NTSTATUS status;
if (tevent_req_is_nterror(req, &status)) {
tevent_req_received(req);
return status;
}
/* Steal possible out parameters to the callers context */
talloc_steal(mem_ctx, state->out_mem_ctx);
tevent_req_received(req);
return NT_STATUS_OK;
}
NTSTATUS rpccli_bar(struct rpc_pipe_client *cli,
TALLOC_CTX *mem_ctx)
{
NTSTATUS status;
status = dcerpc_bar(cli->binding_handle,
mem_ctx);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
/* Return result */
return NT_STATUS_OK;
}
");
$x = new Parse::Pidl::Samba3::ClientNDR();
$fn = { NAME => "bar", ELEMENTS => [ ], RETURN_TYPE => "WERROR" };
$x->ParseFunction("foo", $fn);
is($x->{res},
"struct rpccli_bar_state {
TALLOC_CTX *out_mem_ctx;
WERROR result;
};
static void rpccli_bar_done(struct tevent_req *subreq);
struct tevent_req *rpccli_bar_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct rpc_pipe_client *cli)
{
struct tevent_req *req;
struct rpccli_bar_state *state;
struct tevent_req *subreq;
req = tevent_req_create(mem_ctx, &state,
struct rpccli_bar_state);
if (req == NULL) {
return NULL;
}
state->out_mem_ctx = NULL;
subreq = dcerpc_bar_send(state,
ev,
cli->binding_handle);
if (tevent_req_nomem(subreq, req)) {
return tevent_req_post(req, ev);
}
tevent_req_set_callback(subreq, rpccli_bar_done, req);
return req;
}
static void rpccli_bar_done(struct tevent_req *subreq)
{
struct tevent_req *req = tevent_req_callback_data(
subreq, struct tevent_req);
struct rpccli_bar_state *state = tevent_req_data(
req, struct rpccli_bar_state);
NTSTATUS status;
TALLOC_CTX *mem_ctx;
if (state->out_mem_ctx) {
mem_ctx = state->out_mem_ctx;
} else {
mem_ctx = state;
}
status = dcerpc_bar_recv(subreq,
mem_ctx,
&state->result);
TALLOC_FREE(subreq);
if (!NT_STATUS_IS_OK(status)) {
tevent_req_nterror(req, status);
return;
}
tevent_req_done(req);
}
NTSTATUS rpccli_bar_recv(struct tevent_req *req,
TALLOC_CTX *mem_ctx,
WERROR *result)
{
struct rpccli_bar_state *state = tevent_req_data(
req, struct rpccli_bar_state);
NTSTATUS status;
if (tevent_req_is_nterror(req, &status)) {
tevent_req_received(req);
return status;
}
/* Steal possible out parameters to the callers context */
talloc_steal(mem_ctx, state->out_mem_ctx);
/* Return result */
*result = state->result;
tevent_req_received(req);
return NT_STATUS_OK;
}
NTSTATUS rpccli_bar(struct rpc_pipe_client *cli,
TALLOC_CTX *mem_ctx,
WERROR *werror)
{
WERROR result;
NTSTATUS status;
status = dcerpc_bar(cli->binding_handle,
mem_ctx,
&result);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
/* Return result */
if (werror) {
*werror = result;
}
return werror_to_ntstatus(result);
}
"); |
Perl | wireshark/tools/pidl/tests/samba3-srv.pl | #!/usr/bin/perl
# (C) 2008 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 1;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Util qw(MyDumper has_property);
use Parse::Pidl::Samba3::ServerNDR qw(DeclLevel);
my $l = { TYPE => "DATA", DATA_TYPE => "uint32" };
my $e = { FILE => "foo", LINE => 0, PROPERTIES => { }, TYPE => "uint32",
LEVELS => [ $l ] };
is("uint32_t", DeclLevel($e, 0)); |
Perl | wireshark/tools/pidl/tests/tdr.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 6;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Samba4::TDR qw(ParserType);
my $tdr = new Parse::Pidl::Samba4::TDR();
$tdr->ParserType({TYPE => "STRUCT", NAME => "foo", PROPERTIES => {public => 1}}, "pull");
is($tdr->{ret}, "NTSTATUS tdr_pull_foo (struct tdr_pull *tdr, TALLOC_CTX *mem_ctx, struct foo *v)
{
return NT_STATUS_OK;
}
");
is($tdr->{ret_hdr}, "NTSTATUS tdr_pull_foo (struct tdr_pull *tdr, TALLOC_CTX *mem_ctx, struct foo *v);\n");
$tdr = new Parse::Pidl::Samba4::TDR();
$tdr->ParserType({TYPE => "UNION", NAME => "bar", PROPERTIES => {public => 1}}, "pull");
is($tdr->{ret}, "NTSTATUS tdr_pull_bar(struct tdr_pull *tdr, TALLOC_CTX *mem_ctx, int level, union bar *v)
{
switch (level) {
}
return NT_STATUS_OK;
}
");
is($tdr->{ret_hdr}, "NTSTATUS tdr_pull_bar(struct tdr_pull *tdr, TALLOC_CTX *mem_ctx, int level, union bar *v);\n");
$tdr = new Parse::Pidl::Samba4::TDR();
$tdr->ParserType({TYPE => "UNION", NAME => "bar", PROPERTIES => {}}, "pull");
is($tdr->{ret}, "static NTSTATUS tdr_pull_bar(struct tdr_pull *tdr, TALLOC_CTX *mem_ctx, int level, union bar *v)
{
switch (level) {
}
return NT_STATUS_OK;
}
");
is($tdr->{ret_hdr}, ""); |
Perl | wireshark/tools/pidl/tests/test_util.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use Test::More tests => 6;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util qw(test_warnings test_errors);
use Parse::Pidl qw(warning error);
test_warnings("", sub {});
test_warnings("x:1: msg\n", sub { warning({FILE => "x", LINE => 1}, "msg"); });
test_warnings("", sub {});
test_errors("", sub {});
test_errors("x:1: msg\n", sub { error({FILE => "x", LINE => 1}, "msg"); });
test_errors("", sub {}); |
Perl | wireshark/tools/pidl/tests/typelist.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 56;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Typelist qw(hasType typeHasBody getType mapTypeName expandAlias
mapScalarType addType typeIs is_scalar scalar_is_reference
enum_type_fn bitmap_type_fn mapType);
is("foo", expandAlias("foo"));
is("uint32", expandAlias("DWORD"));
is("int32", expandAlias("int"));
is("", expandAlias(""));
is("int32", expandAlias("int32"));
is("uint32_t", mapScalarType("uint32"));
is("void", mapScalarType("void"));
is("uint64_t", mapScalarType("hyper"));
is("double", mapScalarType("double"));
my $x = { TYPE => "ENUM", NAME => "foo", EXTRADATA => 1 };
addType($x);
is_deeply($x, getType("foo"));
is(undef, getType("bloebla"));
is_deeply(getType({ TYPE => "STRUCT" }), { TYPE => "STRUCT" });
is_deeply(getType({ TYPE => "ENUM", NAME => "foo" }), $x);
is_deeply(getType("uint16"), {
NAME => "uint16",
BASEFILE => "<builtin>",
TYPE => "TYPEDEF",
DATA => { NAME => "uint16", TYPE => "SCALAR" }});
is_deeply(getType("double"), {
NAME => "double",
BASEFILE => "<builtin>",
TYPE => "TYPEDEF",
DATA => { NAME => "double", TYPE => "SCALAR" }});
is(0, typeIs("someUnknownType", "ENUM"));
is(0, typeIs("foo", "ENUM"));
addType({NAME => "mytypedef", TYPE => "TYPEDEF", DATA => { TYPE => "ENUM" }});
is(1, typeIs("mytypedef", "ENUM"));
is(0, typeIs("mytypedef", "BITMAP"));
is(1, typeIs({ TYPE => "ENUM"}, "ENUM"));
is(0, typeIs({ TYPE => "BITMAP"}, "ENUM"));
is(1, typeIs("uint32", "SCALAR"));
is(0, typeIs("uint32", "ENUM"));
is(1, hasType("foo"));
is(0, hasType("nonexistent"));
is(0, hasType({TYPE => "ENUM", NAME => "someUnknownType"}));
is(1, hasType({TYPE => "ENUM", NAME => "foo"}));
is(1, hasType({TYPE => "ENUM"}));
is(1, hasType({TYPE => "STRUCT"}));
is(1, is_scalar("uint32"));
is(0, is_scalar("nonexistent"));
is(1, is_scalar({TYPE => "ENUM"}));
is(0, is_scalar({TYPE => "STRUCT"}));
is(1, is_scalar({TYPE => "TYPEDEF", DATA => {TYPE => "ENUM" }}));
is(1, is_scalar("mytypedef"));
is(1, scalar_is_reference("string"));
is(0, scalar_is_reference("uint32"));
is(0, scalar_is_reference({TYPE => "STRUCT", NAME => "echo_foobar"}));
is("uint8", enum_type_fn({TYPE => "ENUM", PARENT=>{PROPERTIES => {enum8bit => 1}}}));
is("uint32", enum_type_fn({TYPE => "ENUM", PARENT=>{PROPERTIES => {v1_enum => 1}}}));
is("uint1632", enum_type_fn({TYPE => "ENUM", PARENT=>{PROPERTIES => {}}}));
is("uint8", bitmap_type_fn({TYPE => "BITMAP", PROPERTIES => {bitmap8bit => 1}}));
is("uint16", bitmap_type_fn({TYPE => "BITMAP", PROPERTIES => {bitmap16bit => 1}}));
is("hyper", bitmap_type_fn({TYPE => "BITMAP", PROPERTIES => {bitmap64bit => 1}}));
is("uint32", bitmap_type_fn({TYPE => "BITMAP", PROPERTIES => {}}));
is("enum foo", mapType({TYPE => "ENUM"}, "foo"));
is("union foo", mapType({TYPE => "UNION"}, "foo"));
is("struct foo", mapType({TYPE => "STRUCT"}, "foo"));
is("uint8_t", mapType({TYPE => "BITMAP", PROPERTIES => {bitmap8bit => 1}}, "foo"));
is("uint8_t", mapType({TYPE => "SCALAR"}, "uint8"));
is("uint32_t", mapType({TYPE => "TYPEDEF", DATA => {TYPE => "SCALAR"}}, "uint32"));
is("void", mapTypeName(undef));
is("uint32_t", mapTypeName("uint32"));
is("int32_t", mapTypeName("int"));
ok(not typeHasBody({TYPE => "TYPEDEF", DATA => { TYPE => "STRUCT" }}));
ok(typeHasBody({TYPE => "TYPEDEF", DATA => { TYPE => "STRUCT", ELEMENTS => [] }})); |
Perl | wireshark/tools/pidl/tests/util.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
use strict;
use warnings;
use Test::More tests => 72;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl qw(error);
use Parse::Pidl::Util;
# has_property()
is(undef, has_property({}, "foo"));
is(undef, has_property({PROPERTIES => {}}, "foo"));
is("data", has_property({PROPERTIES => {foo => "data"}}, "foo"));
is(undef, has_property({PROPERTIES => {foo => undef}}, "foo"));
# is_constant()
ok(is_constant("2"));
ok(is_constant("256"));
ok(is_constant("0x400"));
ok(is_constant("0x4BC"));
ok(not is_constant("0x4BGC"));
ok(not is_constant("str"));
ok(not is_constant("2 * expr"));
# make_str()
is("\"bla\"", make_str("bla"));
is("\"bla\"", make_str("\"bla\""));
is("\"\"bla\"\"", make_str("\"\"bla\"\""));
is("\"bla\"\"", make_str("bla\""));
is("\"foo\"bar\"", make_str("foo\"bar"));
is("bla", unmake_str("\"bla\""));
is("\"bla\"", unmake_str("\"\"bla\"\""));
# print_uuid()
is(undef, print_uuid("invalid"));
is("{0x12345778,0x1234,0xabcd,{0xef,0x00},{0x01,0x23,0x45,0x67,0x89,0xac}}",
print_uuid("12345778-1234-abcd-ef00-0123456789ac"));
is("{0x12345778,0x1234,0xabcd,{0xef,0x00},{0x01,0x23,0x45,0x67,0x89,0xac}}",
print_uuid("\"12345778-1234-abcd-ef00-0123456789ac\""));
# property_matches()
# missing property
ok(not property_matches({PROPERTIES => {}}, "x", "data"));
# data not matching
ok(not property_matches({PROPERTIES => {x => "bar"}}, "x", "data"));
# data matching exactly
ok(property_matches({PROPERTIES => {x => "data"}}, "x", "data"));
# regex matching
ok(property_matches({PROPERTIES => {x => "data"}}, "x", "^([dat]+)\$"));
# ParseExpr()
is(undef, ParseExpr("", {}, undef));
is("a", ParseExpr("a", {"b" => "2"}, undef));
is("2", ParseExpr("a", {"a" => "2"}, undef));
is("2 * 2", ParseExpr("a*a", {"a" => "2"}, undef));
is("r->length + r->length",
ParseExpr("length+length", {"length" => "r->length"}, undef));
is("2 / 2 * (r->length)",
ParseExpr("constant/constant*(len)", {"constant" => "2",
"len" => "r->length"}, undef));
is("2 + 2 - r->length",
ParseExpr("constant+constant-len", {"constant" => "2",
"len" => "r->length"}, undef));
is("*r->length", ParseExpr("*len", { "len" => "r->length"}, undef));
is("**r->length", ParseExpr("**len", { "len" => "r->length"}, undef));
is("r->length & 2", ParseExpr("len&2", { "len" => "r->length"}, undef));
is("&r->length", ParseExpr("&len", { "len" => "r->length"}, undef));
is("calc()", ParseExpr("calc()", { "foo" => "2"}, undef));
is("calc(2 * 2)", ParseExpr("calc(foo * 2)", { "foo" => "2"}, undef));
is("strlen(\"data\")", ParseExpr("strlen(foo)", { "foo" => "\"data\""}, undef));
is("strlen(\"data\", 4)", ParseExpr("strlen(foo, 4)", { "foo" => "\"data\""}, undef));
is("foo / bar", ParseExpr("foo / bar", { "bla" => "\"data\""}, undef));
is("r->length % 2", ParseExpr("len%2", { "len" => "r->length"}, undef));
is("r->length == 2", ParseExpr("len==2", { "len" => "r->length"}, undef));
is("r->length != 2", ParseExpr("len!=2", { "len" => "r->length"}, undef));
is("pr->length", ParseExpr("pr->length", { "p" => "r"}, undef));
is("r->length", ParseExpr("p->length", { "p" => "r"}, undef));
is("_foo / bla32", ParseExpr("_foo / bla32", { "bla" => "\"data\""}, undef));
is("foo.bar.blah", ParseExpr("foo.blah", { "foo" => "foo.bar"}, undef));
is("\"bla\"", ParseExpr("\"bla\"", {}, undef));
is("1 << 2", ParseExpr("1 << 2", {}, undef));
is("1 >> 2", ParseExpr("1 >> 2", {}, undef));
is("0x200", ParseExpr("0x200", {}, undef));
is("2?3:0", ParseExpr("2?3:0", {}, undef));
is("~0", ParseExpr("~0", {}, undef));
is("b->a->a", ParseExpr("a->a->a", {"a" => "b"}, undef));
is("b.a.a", ParseExpr("a.a.a", {"a" => "b"}, undef));
test_errors("nofile:0: Parse error in `~' near `~'\n", sub {
is(undef, ParseExpr("~", {}, {FILE => "nofile", LINE => 0})); });
test_errors("nofile:0: Got pointer, expected integer\n", sub {
is(undef, ParseExprExt("foo", {}, {FILE => "nofile", LINE => 0},
undef, sub { my $x = shift;
error({FILE => "nofile", LINE => 0},
"Got pointer, expected integer");
return undef; }))});
is("b.a.a", ParseExpr("b.a.a", {"a" => "b"}, undef));
is("((rr_type) == NBT_QTYPE_NETBIOS)", ParseExpr("((rr_type)==NBT_QTYPE_NETBIOS)", {}, undef));
is("talloc_check_name", ParseExpr("talloc_check_name", {}, undef));
is("talloc_check_name()", ParseExpr("talloc_check_name()", {}, undef));
is("talloc_check_name(ndr)", ParseExpr("talloc_check_name(ndr)", {}, undef));
is("talloc_check_name(ndr, 1)", ParseExpr("talloc_check_name(ndr,1)", {}, undef));
is("talloc_check_name(ndr, \"struct ndr_push\")", ParseExpr("talloc_check_name(ndr,\"struct ndr_push\")", {}, undef));
is("((rr_type) == NBT_QTYPE_NETBIOS) && talloc_check_name(ndr, \"struct ndr_push\")", ParseExpr("((rr_type)==NBT_QTYPE_NETBIOS)&&talloc_check_name(ndr,\"struct ndr_push\")", {}, undef));
is("(rdata).data.length", ParseExpr("(rdata).data.length", {}, undef));
is("((rdata).data.length == 2)", ParseExpr("((rdata).data.length==2)", {}, undef));
is("((rdata).data.length == 2)?0:rr_type", ParseExpr("((rdata).data.length==2)?0:rr_type", {}, undef));
is("((((rr_type) == NBT_QTYPE_NETBIOS) && talloc_check_name(ndr, \"struct ndr_push\") && ((rdata).data.length == 2))?0:rr_type)", ParseExpr("((((rr_type)==NBT_QTYPE_NETBIOS)&&talloc_check_name(ndr,\"struct ndr_push\")&&((rdata).data.length==2))?0:rr_type)", {}, undef)); |
wireshark/tools/pidl/tests/Util.pm | # Some simple utility functions for pidl tests
# Copyright (C) 2005-2006 Jelmer Vernooij
# Published under the GNU General Public License
package Util;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(test_samba4_ndr test_warnings test_errors);
use strict;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
use Parse::Pidl::Samba4 qw(is_intree);
use Parse::Pidl;
my $warnings = "";
undef &Parse::Pidl::warning;
*Parse::Pidl::warning = sub {
my ($e, $l) = @_;
if (defined($e)) {
$warnings .= "$e->{FILE}:$e->{LINE}: $l\n";
} else {
$warnings .= "$l\n";
}
};
my $errors = "";
undef &Parse::Pidl::error;
*Parse::Pidl::error = sub {
my ($e, $l) = @_;
if (defined($e)) {
$errors .= "$e->{FILE}:$e->{LINE}: $l\n";
} else {
$errors .= "$l\n";
}
};
use Test::More;
use Parse::Pidl::IDL;
use Parse::Pidl::NDR;
use Parse::Pidl::Samba4::NDR::Parser;
use Parse::Pidl::Samba4::Header;
# Generate a Samba4 parser for an IDL fragment and run it with a specified
# piece of code to check whether the parser works as expected
sub test_samba4_ndr
{
my ($name,$idl,$c,$extra) = @_;
$extra = "" unless defined($extra);
my $pidl = Parse::Pidl::IDL::parse_string("interface echo { $idl }; ", "<$name>");
ok(defined($pidl), "($name) parse idl");
my $pndr = Parse::Pidl::NDR::Parse($pidl);
ok(defined($pndr), "($name) generate NDR tree");
my $header = Parse::Pidl::Samba4::Header::Parse($pndr);
ok(defined($header), "($name) generate generic header");
my $generator = new Parse::Pidl::Samba4::NDR::Parser();
my ($ndrheader,$ndrparser) = $generator->Parse($pndr, undef, undef);
ok(defined($ndrparser), "($name) generate NDR parser");
ok(defined($ndrheader), "($name) generate NDR header");
SKIP: {
my $flags;
if (system("pkg-config --exists ndr") == 0 and !is_intree()) {
$flags = `pkg-config --libs --cflags ndr`;
} else {
skip "no samba environment available, skipping compilation", 3;
}
my $main = "
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
#include <util/data_blob.h>
/* header start */
$header
/* header end */
/* ndrheader start */
$ndrheader
/* ndrheader end */
/* extra start */
$extra
/* extra end */
/* ndrparser start */
$ndrparser
/* ndrparser end */
/* main start */
int main(int argc, const char **argv)
{
TALLOC_CTX *mem_ctx = talloc_init(NULL);
$c
talloc_free(mem_ctx);
return 0;
}
/* main end */
\n";
my $main_debug = "# ".join("\n# ", split("\n", $main));
my $test_data_prefix = $ENV{TEST_DATA_PREFIX};
my $outfile;
if (defined($test_data_prefix)) {
$outfile = "$test_data_prefix/test-$name";
} else {
$outfile = "./test-$name";
}
my $cflags = $ENV{CFLAGS};
unless (defined($cflags)) {
$cflags = "";
}
my $ldflags = $ENV{LDFLAGS};
unless (defined($ldflags)) {
$ldflags = "";
}
my $cc = $ENV{CC};
unless (defined($cc)) {
$cc = "cc";
}
my $cmd = "$cc $cflags -x c - -o $outfile $flags $ldflags";
$cmd =~ s/\n//g;
open CC, "|$cmd";
print CC $main;
close CC;
ok(-f $outfile, "($name) compile");
my $ret = system($outfile, ()) >> 8;
print "# code:\n#\n$main_debug\n" if ($ret != 0);
print "# cmd: $cmd\n" if ($ret != 0);
print "# return code: $ret\n" if ($ret != 0);
ok($ret == 0, "($name) run");
ok(unlink($outfile), "($name) remove");
}
}
sub test_warnings($$)
{
my ($exp, $code) = @_;
$warnings = "";
$code->();
is($warnings, $exp);
}
sub test_errors($$)
{
my ($exp, $code) = @_;
$errors = "";
$code->();
is($errors, $exp);
}
1; |
|
Perl | wireshark/tools/pidl/tests/wireshark-conf.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
# test parsing wireshark conformance files
use strict;
use warnings;
use Test::More tests => 49;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Util qw(MyDumper);
use Parse::Pidl::Wireshark::Conformance qw(ReadConformanceFH valid_ft_type valid_base_type);
sub parse_conf($)
{
my $str = shift;
open(TMP, "+>", undef) or die("unable to open temp file");
print TMP $str;
seek(TMP, 0, 0);
my $data = {};
ReadConformanceFH(*TMP, $data, "nofile") or return undef;
close(TMP);
return $data;
}
ok(parse_conf("\n"), undef);
ok(parse_conf(" \n"), undef);
ok(parse_conf("CODE START\nCODE END\n"));
test_warnings("nofile:1: Expecting CODE END\n", sub { is(parse_conf("CODE START\n"), undef); });
ok(parse_conf("#foobar\n"), undef);
test_warnings("nofile:1: Unknown command `foobar'\n",
sub { ok(parse_conf("foobar\n"), undef); });
test_warnings("nofile:1: incomplete HF_RENAME command\n",
sub { parse_conf("HF_RENAME\n"); });
is_deeply(parse_conf("HF_RENAME foo bar\n")->{hf_renames}->{foo},
{ OLDNAME => "foo", NEWNAME => "bar", POS => {FILE => "nofile", LINE => 1}, USED => 0});
is_deeply(parse_conf("NOEMIT\n"), { "noemit_dissector" => 1 });
is_deeply(parse_conf("NOEMIT foo\n"), { "noemit" => { "foo" => 1 } });
test_warnings("nofile:1: incomplete MANUAL command\n",
sub { parse_conf("MANUAL\n"); } );
is_deeply(parse_conf("MANUAL foo\n"), { manual => {foo => 1}});
test_errors("nofile:1: incomplete INCLUDE command\n",
sub { parse_conf("INCLUDE\n"); } );
test_warnings("nofile:1: incomplete FIELD_DESCRIPTION command\n",
sub { parse_conf("FIELD_DESCRIPTION foo\n"); });
is_deeply(parse_conf("FIELD_DESCRIPTION foo \"my description\"\n"),
{ fielddescription => { foo => { DESCRIPTION => "\"my description\"", POS => { FILE => "nofile", LINE => 1}, USED => 0 }}});
is_deeply(parse_conf("FIELD_DESCRIPTION foo my description\n"),
{ fielddescription => { foo => { DESCRIPTION => "my", POS => { FILE => "nofile", LINE => 1}, USED => 0 }}});
is_deeply(parse_conf("CODE START\ndata\nCODE END\n"), { override => "data\n" });
is_deeply(parse_conf("CODE START\ndata\nmore data\nCODE END\n"), { override => "data\nmore data\n" });
test_warnings("nofile:1: CODE END outside CODE section\n",
sub { parse_conf("CODE END\n"); } );
is_deeply(parse_conf("TYPE winreg_String dissect_myminregstring(); FT_STRING BASE_DEC 0 0 2\n"), { types => { winreg_String => {
NAME => "winreg_String",
POS => { FILE => "nofile", LINE => 1 },
USED => 0,
DISSECTOR_NAME => "dissect_myminregstring();",
FT_TYPE => "FT_STRING",
BASE_TYPE => "BASE_DEC",
MASK => 0,
VALSSTRING => 0,
ALIGNMENT => 2}}});
ok(valid_ft_type("FT_UINT32"));
ok(not valid_ft_type("BLA"));
ok(not valid_ft_type("ft_uint32"));
ok(valid_ft_type("FT_BLA"));
ok(valid_base_type("BASE_DEC"));
ok(valid_base_type("BASE_HEX"));
ok(not valid_base_type("base_dec"));
ok(not valid_base_type("BLA"));
ok(not valid_base_type("BASEDEC"));
test_errors("nofile:1: incomplete TYPE command\n",
sub { parse_conf("TYPE mytype dissector\n"); });
test_warnings("nofile:1: dissector name does not contain `dissect'\n",
sub { parse_conf("TYPE winreg_String myminregstring; FT_STRING BASE_DEC 0 0 2\n"); });
test_warnings("nofile:1: invalid FT_TYPE `BLA'\n",
sub { parse_conf("TYPE winreg_String dissect_myminregstring; BLA BASE_DEC 0 0 2\n"); });
test_warnings("nofile:1: invalid BASE_TYPE `BLOE'\n",
sub { parse_conf("TYPE winreg_String dissect_myminregstring; FT_UINT32 BLOE 0 0 2\n"); });
is_deeply(parse_conf("TFS hf_bla \"True string\" \"False String\"\n"),
{ tfs => { hf_bla => {
TRUE_STRING => "\"True string\"",
FALSE_STRING => "\"False String\"" } } });
test_errors("nofile:1: incomplete TFS command\n",
sub { parse_conf("TFS hf_bla \"Trues\""); } );
test_errors("nofile:1: incomplete PARAM_VALUE command\n",
sub { parse_conf("PARAM_VALUE\n"); });
is_deeply(parse_conf("PARAM_VALUE Life 42\n"),
{ dissectorparams => {
Life => {
DISSECTOR => "Life",
POS => { FILE => "nofile", LINE => 1 },
PARAM => 42,
USED => 0
}
}
});
is_deeply(parse_conf("STRIP_PREFIX bla_\n"),
{ strip_prefixes => [ "bla_" ] });
is_deeply(parse_conf("STRIP_PREFIX bla_\nSTRIP_PREFIX bloe\n"),
{ strip_prefixes => [ "bla_", "bloe" ] });
is_deeply(parse_conf("PROTOCOL atsvc \"Scheduling jobs on remote machines\" \"at\" \"atsvc\"\n"),
{ protocols => {
atsvc => {
LONGNAME => "\"Scheduling jobs on remote machines\"",
SHORTNAME => "\"at\"",
FILTERNAME => "\"atsvc\""
}
}
}
);
is_deeply(parse_conf("IMPORT bla\n"), {
imports => {
bla => {
NAME => "bla",
DATA => "",
USED => 0,
POS => { FILE => "nofile", LINE => 1 }
}
}
}
);
is_deeply(parse_conf("IMPORT bla fn1 fn2 fn3\n"), {
imports => {
bla => {
NAME => "bla",
DATA => "fn1 fn2 fn3",
USED => 0,
POS => { FILE => "nofile", LINE => 1 }
}
}
}
);
test_errors("nofile:1: no dissectorname specified\n",
sub { parse_conf("IMPORT\n"); } );
test_errors("nofile:1: incomplete HF_FIELD command\n",
sub { parse_conf("HF_FIELD hf_idx\n"); });
test_errors("nofile:1: incomplete ETT_FIELD command\n",
sub { parse_conf("ETT_FIELD\n"); });
is_deeply(parse_conf("TYPE winreg_String dissect_myminregstring(); FT_STRING BASE_DEC 0 0 0 2\n"), {
types => {
winreg_String => {
NAME => "winreg_String",
POS => { FILE => "nofile", LINE => 1 },
USED => 0,
DISSECTOR_NAME => "dissect_myminregstring();",
FT_TYPE => "FT_STRING",
BASE_TYPE => "BASE_DEC",
MASK => 0,
VALSSTRING => 0,
ALIGNMENT => 0
}
}
}
);
is_deeply(parse_conf("TYPE winreg_String \"offset = dissect_myminregstring(\@HF\@);\" FT_STRING BASE_DEC 0 0 0 2\n"), {
types => {
winreg_String => {
NAME => "winreg_String",
POS => { FILE => "nofile", LINE => 1 },
USED => 0,
DISSECTOR_NAME => "offset = dissect_myminregstring(\@HF\@);",
FT_TYPE => "FT_STRING",
BASE_TYPE => "BASE_DEC",
MASK => 0,
VALSSTRING => 0,
ALIGNMENT => 0
}
}
}
); |
Perl | wireshark/tools/pidl/tests/wireshark-ndr.pl | #!/usr/bin/perl
# (C) 2007 Jelmer Vernooij <[email protected]>
# Published under the GNU General Public License
# test parsing wireshark conformance files
use strict;
use warnings;
use Test::More tests => 40;
use FindBin qw($RealBin);
use lib "$RealBin";
use Util;
use Parse::Pidl::Util qw(MyDumper);
use strict;
use Parse::Pidl::Wireshark::NDR qw(field2name %res PrintIdl StripPrefixes RegisterInterfaceHandoff register_hf_field ProcessImport ProcessInclude find_type DumpEttList DumpEttDeclaration DumpHfList DumpHfDeclaration DumpFunctionTable register_type register_ett);
is("Access Mask", field2name("access_mask"));
is("AccessMask", field2name("AccessMask"));
my $x = new Parse::Pidl::Wireshark::NDR();
$x->PrintIdl("foo\nbar\n");
is("/* IDL: foo */
/* IDL: bar */
", $x->{res}->{code});
is("bla_foo", StripPrefixes("bla_foo", []));
is("foo", StripPrefixes("bla_foo", ["bla"]));
is("foo_bla", StripPrefixes("foo_bla", ["bla"]));
$x = new Parse::Pidl::Wireshark::NDR();
$x->RegisterInterfaceHandoff({});
is($x->{res}->{code}, "");
ok(not defined($x->{hf_used}->{hf_bla_opnum}));
$x = new Parse::Pidl::Wireshark::NDR();
$x->{res}->{code} = "";
$x->RegisterInterfaceHandoff({UUID => "uuid", NAME => "bla"});
is($x->{res}->{code}, 'void proto_reg_handoff_dcerpc_bla(void)
{
dcerpc_init_uuid(proto_dcerpc_bla, ett_dcerpc_bla,
&uuid_dcerpc_bla, ver_dcerpc_bla,
bla_dissectors, hf_bla_opnum);
}
');
is($x->{hf_used}->{hf_bla_opnum}, 1);
$x->{conformance} = {};
is("hf_bla_idx",
$x->register_hf_field("hf_bla_idx", "bla", "my.filter", "FT_UINT32", "BASE_HEX", "NULL", 0xF, undef));
is_deeply($x->{conformance}, {
header_fields => {
"hf_bla_idx" => {
INDEX => "hf_bla_idx",
NAME => "bla",
FILTER => "my.filter",
BASE_TYPE => "BASE_HEX",
FT_TYPE => "FT_UINT32",
VALSSTRING => "NULL",
BLURB => undef,
MASK => 0xF
}
},
hf_renames => {},
fielddescription => {}
});
$x->{conformance} = { fielddescription => { hf_bla_idx => { DESCRIPTION => "Some Description" }}};
is("hf_bla_idx",
$x->register_hf_field("hf_bla_idx", "bla", "my.filter", "FT_UINT32", "BASE_HEX", "NULL", 0xF, undef));
is_deeply($x->{conformance}, {
fielddescription => {
hf_bla_idx => {
DESCRIPTION => "Some Description",
USED => 1
}
},
header_fields => {
"hf_bla_idx" => {
INDEX => "hf_bla_idx",
NAME => "bla",
FILTER => "my.filter",
BASE_TYPE => "BASE_HEX",
FT_TYPE => "FT_UINT32",
VALSSTRING => "NULL",
BLURB => "Some Description",
MASK => 0xF
}
},
hf_renames => {},
});
$x->{conformance} = { fielddescription => { hf_bla_idx => { DESCRIPTION => "Some Description" }}};
is("hf_bla_idx",
$x->register_hf_field("hf_bla_idx", "bla", "my.filter", "FT_UINT32", "BASE_HEX", "NULL", 0xF,
"Actual Description"));
is_deeply($x->{conformance}, {
fielddescription => {
hf_bla_idx => { DESCRIPTION => "Some Description" }
},
header_fields => {
"hf_bla_idx" => {
INDEX => "hf_bla_idx",
NAME => "bla",
FILTER => "my.filter",
BASE_TYPE => "BASE_HEX",
FT_TYPE => "FT_UINT32",
VALSSTRING => "NULL",
BLURB => "Actual Description",
MASK => 0xF
}
},
hf_renames => {},
});
$x->{conformance} = { hf_renames => { "hf_bla_idx" => { NEWNAME => "hf_bloe_idx" } } };
$x->register_hf_field("hf_bla_idx", "bla", "my.filter", "FT_UINT32", "BASE_HEX", "NULL", 0xF, undef);
is_deeply($x->{conformance}, {
hf_renames => { hf_bla_idx => { USED => 1, NEWNAME => "hf_bloe_idx" } } });
$x->{hf_used} = { hf_bla => 1 };
test_warnings("", sub {
$x->CheckUsed({ header_fields => { foo => { INDEX => "hf_bla" }}})});
$x->{hf_used} = { };
test_warnings("hf field `hf_bla' not used\n", sub {
$x->CheckUsed({ header_fields => { foo => { INDEX => "hf_bla" }}})});
test_warnings("hf field `hf_id' not used\n",
sub { $x->CheckUsed({
hf_renames => {
hf_id => {
OLDNAME => "hf_id",
NEWNAME => "hf_newid",
USED => 0
}
}
}); } );
test_warnings("dissector param never used\n",
sub { $x->CheckUsed({
dissectorparams => {
dissect_foo => {
PARAM => 42,
USED => 0
}
}
}); } );
test_warnings("description never used\n",
sub { $x->CheckUsed({
fielddescription => {
hf_bla => {
USED => 0
}
}
}); } );
test_warnings("import never used\n",
sub { $x->CheckUsed({
imports => {
bla => {
USED => 0
}
}
}); } );
test_warnings("nofile:1: type never used\n",
sub { $x->CheckUsed({
types => {
bla => {
USED => 0,
POS => { FILE => "nofile", LINE => 1 }
}
}
}); } );
test_warnings("True/False description never used\n",
sub { $x->CheckUsed({
tfs => {
hf_bloe => {
USED => 0
}
}
}); } );
$x = new Parse::Pidl::Wireshark::NDR();
$x->ProcessImport("security", "bla");
is($x->{res}->{hdr}, "#include \"packet-dcerpc-bla.h\"\n\n");
$x = new Parse::Pidl::Wireshark::NDR();
$x->ProcessImport("\"bla.idl\"", "\"foo.idl\"");
is($x->{res}->{hdr}, "#include \"packet-dcerpc-bla.h\"\n" .
"#include \"packet-dcerpc-foo.h\"\n\n");
$x = new Parse::Pidl::Wireshark::NDR();
$x->ProcessInclude("foo.h", "bla.h", "bar.h");
is($x->{res}->{hdr}, "#include \"foo.h\"\n" .
"#include \"bla.h\"\n" .
"#include \"bar.h\"\n\n");
$x->{conformance} = {types => { bla => "brainslug" } };
is("brainslug", $x->find_type("bla"));
is(DumpEttList(["ett_t1", "ett_bla"]),
"\tstatic gint *ett[] = {\n" .
"\t\t&ett_t1,\n" .
"\t\t&ett_bla,\n" .
"\t};\n");
is(DumpEttList(), "\tstatic gint *ett[] = {\n\t};\n");
is(DumpEttList(["bla"]), "\tstatic gint *ett[] = {\n\t\t&bla,\n\t};\n");
is(DumpEttDeclaration(["void", "zoid"]),
"\n/* Ett declarations */\n" .
"static gint void = -1;\n" .
"static gint zoid = -1;\n" .
"\n");
is(DumpEttDeclaration(), "\n/* Ett declarations */\n\n");
$x->{conformance} = {
header_fields => {
hf_bla => { INDEX => "hf_bla", NAME => "Bla", FILTER => "bla.field", FT_TYPE => "FT_UINT32", BASE_TYPE => "BASE_DEC", VALSSTRING => "NULL", MASK => 0xFF, BLURB => "NULL" }
}
};
is($x->DumpHfList(), "\tstatic hf_register_info hf[] = {
{ &hf_bla,
{ \"Bla\", \"bla.field\", FT_UINT32, BASE_DEC, NULL, 255, \"NULL\", HFILL }},
};
");
is($x->DumpHfDeclaration(), "
/* Header field declarations */
static gint hf_bla = -1;
");
is(DumpFunctionTable({
NAME => "someif",
FUNCTIONS => [ { NAME => "fn1", OPNUM => 3 }, { NAME => "someif_fn2", OPNUM => 2 } ] }),
'static dcerpc_sub_dissector someif_dissectors[] = {
{ 3, "fn1",
someif_dissect_fn1_request, someif_dissect_fn1_response},
{ 2, "fn2",
someif_dissect_fn2_request, someif_dissect_fn2_response},
{ 0, NULL, NULL, NULL }
};
');
$x->{conformance} = {};
$x->register_type("bla_type", "dissect_bla", "FT_UINT32", "BASE_HEX", 0xFF, "NULL", 4);
is_deeply($x->{conformance}, {
types => {
bla_type => {
NAME => "bla_type",
DISSECTOR_NAME => "dissect_bla",
FT_TYPE => "FT_UINT32",
BASE_TYPE => "BASE_HEX",
MASK => 255,
VALSSTRING => "NULL",
ALIGNMENT => 4
}
}
}
);
$x->{ett} = [];
$x->register_ett("name");
is_deeply($x->{ett}, ["name"]);
$x->register_ett("leela");
is_deeply($x->{ett}, ["name", "leela"]); |
Text | wireshark/tools/radiotap-gen/CMakeLists.txt | if(UNIX)
add_executable( radiotap-gen radiotap-gen.c )
target_link_libraries( radiotap-gen pcap ${GLIB2_LIBRARIES} )
endif() |
C | wireshark/tools/radiotap-gen/radiotap-gen.c | /*
* A generic packet generator application for U-SIG radiotap packets.
*
* Copyright Richard Sharpe, 2022.
*
* You will need libpcap installed.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* A sample program showing how to create packets with radiotap headers. This
* is mainly useful for those situations where you are adding a new radiotap
* TLV but the drivers for the hardware is not ready yet and you need to
* test your radiotap dissector.
*/
#include <errno.h>
#include <glib.h>
#include <pcap.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
struct u_sig_hdr {
uint16_t type;
uint16_t len;
uint32_t common;
uint32_t value;
uint32_t mask;
} __attribute__((packed));
struct radiotap_hdr {
uint8_t vers;
uint8_t pad;
uint16_t len;
uint32_t presence_flags;
uint32_t MAC_timestamp[2];
uint8_t flags;
uint8_t data_rate;
uint16_t channel_freq;
uint16_t pad2;
uint16_t pad3;
struct u_sig_hdr u_sig_hdr;
} __attribute__((packed));
struct complete_pkt {
struct radiotap_hdr radiotap;
uint8_t pkt_data[26];
} __attribute__((packed));
/* Some random 802.11 packet, an S1G beacon, I think */
uint8_t pkt_data[26] = { 0x1c, 0x0b, 0x00, 0x00, 0x02, 0x00, 0xeb, 0x4b,
0x02, 0x8b, 0x12, 0x52, 0xa7, 0x6b, 0x00, 0x62,
0x9c, 0x6b, 0x64, 0x4e, 0x35, 0xae, 0x05, 0x02,
0x00, 0x02 };
#define PHY_VERSION_ID_KNOWN 0x00000001
#define BW_KNOWN 0x00000002
#define UL_DL_KNOWN 0x00000004
#define BSS_COLOR_KNOWN 0x00000008
#define UL_DL 0x00040000
/*
* Generate some u_sig packets.
*/
static void gen_u_sig_pkts(pcap_dumper_t *dumper)
{
struct pcap_pkthdr hdr;
struct complete_pkt pkt;
struct timeval ts;
/*
* Create the complete packet.
*
* 1. Set up the radiotap headers we need, including the TLVs.
*/
pkt.radiotap.vers = 0;
pkt.radiotap.pad = 0;
pkt.radiotap.len = sizeof(struct radiotap_hdr);
pkt.radiotap.presence_flags = 0x1000000F;
pkt.radiotap.MAC_timestamp[0] = 0x17860500;
pkt.radiotap.MAC_timestamp[1] = 0x22ac9b1a;
pkt.radiotap.flags = 0;
pkt.radiotap.data_rate = 0x02;
pkt.radiotap.channel_freq = 5600;
pkt.radiotap.pad2 = 0x0100;
pkt.radiotap.pad3 = 0x0000;
pkt.radiotap.u_sig_hdr.type = 33; /* The TLV we want U-SIG */
pkt.radiotap.u_sig_hdr.len = 12;
/* Set the BW to 80MHz for the moment */
pkt.radiotap.u_sig_hdr.common = PHY_VERSION_ID_KNOWN | BW_KNOWN | \
UL_DL_KNOWN | 0x00012000;
/*
* The bits are: U-SIG-1 B20-25: all 1s.
* PPDU Type and Comp mode: 0
* Validate: 1
* Punctured Channel Information: 0 (no puncturing)
* Validate: 1
* EHT SIG MCS: 0 (EHT-MCS 0)
*/
pkt.radiotap.u_sig_hdr.value = 0x0000413F;
pkt.radiotap.u_sig_hdr.mask = 0x003fbec0; /* The Intel value */
/* Copy the packet data in */
memcpy(pkt.pkt_data, pkt_data, sizeof(pkt.pkt_data));
gettimeofday(&ts, NULL);
hdr.ts.tv_sec = ts.tv_sec;
hdr.ts.tv_usec = ts.tv_usec;
hdr.caplen = sizeof(struct complete_pkt);
hdr.len = sizeof(struct complete_pkt);
pcap_dump((u_char *)dumper, &hdr, (u_char *)&pkt);
/* Dump another with different 160MHz */
/*
* The bits are: U-SIG-1 B20-25: all 1s.
* PPDU Type and Comp mode: 0
* Validate: 1
* Punctured Channel Information: 1 ([x 1 1 1]puncturing)
* Validate: 1
* EHT SIG MCS: 1 (EHT-MCS 1)
*/
pkt.radiotap.u_sig_hdr.common = PHY_VERSION_ID_KNOWN | BW_KNOWN | \
UL_DL_KNOWN | 0x00018000;;
pkt.radiotap.u_sig_hdr.mask = 0x003fbec0;
pkt.radiotap.u_sig_hdr.value = 0x0001183F;
/* We should probably update the timestamp */
pcap_dump((u_char *)dumper, &hdr, (u_char *)&pkt);
/* Dump another with different 160MHz */
/*
* The bits are: U-SIG-1 B20-25: all 1s.
* PPDU Type and Comp mode: 0
* Validate: 1
* Punctured Channel Information: 1 ([x 1 1 1]puncturing)
* Validate: 1
* EHT SIG MCS: 1 (EHT-MCS 1)
*/
pkt.radiotap.u_sig_hdr.common = PHY_VERSION_ID_KNOWN | BW_KNOWN | \
UL_DL_KNOWN | UL_DL | 0x00018000;
pkt.radiotap.u_sig_hdr.mask = 0x003fbec0;
pkt.radiotap.u_sig_hdr.value = 0x0001183F;
pcap_dump((u_char *)dumper, &hdr, (u_char *)&pkt);
}
int main(int argc, char *argv[])
{
int err = -1;
pcap_t *pd = NULL;
pcap_dumper_t *dumper = NULL;
if (argc < 2) {
printf("Usage: %s <pcap-file-name>\n", argv[0]);
return 1;
}
pd = pcap_open_dead(DLT_IEEE802_11_RADIO, 65535);
if (pd == NULL) {
fprintf(stderr, "Unable to open pcap device: %s\n",
g_strerror(errno));
return -1;
}
dumper = pcap_dump_open(pd, argv[1]);
if (dumper == NULL) {
fprintf(stderr, "Unable to create dump file %s: %s\n",
argv[1], pcap_geterr(pd));
goto close_pd;
}
/*
* Add calls to any functions that generate packets.
*/
gen_u_sig_pkts(dumper);
pcap_dump_close(dumper);
close_pd:
pcap_close(pd);
return err;
} |
C | wireshark/ui/alert_box.c | /* alert_box.c
* Routines to put up various "standard" alert boxes used in multiple
* places
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <string.h>
#include <wiretap/wtap.h>
#include <wsutil/filesystem.h>
#include "ui/alert_box.h"
#include "ui/simple_dialog.h"
/*
* Alert box for general errors.
*/
void
failure_alert_box(const char *msg_format, ...)
{
va_list ap;
va_start(ap, msg_format);
vsimple_error_message_box(msg_format, ap);
va_end(ap);
}
void
vfailure_alert_box(const char *msg_format, va_list ap)
{
vsimple_error_message_box(msg_format, ap);
}
void
vwarning_alert_box(const char *msg_format, va_list ap)
{
vsimple_warning_message_box(msg_format, ap);
}
/*
* Alert box for a failed attempt to open a capture file for reading.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values.
*
* XXX - add explanatory secondary text for at least some of the errors;
* various HIGs suggest that you should, for example, suggest that the
* user remove files if the file system is full. Perhaps that's because
* they're providing guidelines for people less sophisticated than the
* typical Wireshark user is, but....
*/
void
cfile_open_failure_alert_box(const char *filename, int err, gchar *err_info)
{
gchar *display_basename;
if (err < 0) {
/* Wiretap error. */
display_basename = g_filename_display_basename(filename);
switch (err) {
case WTAP_ERR_NOT_REGULAR_FILE:
simple_error_message_box(
"The file \"%s\" is a \"special file\" or socket or other non-regular file.",
display_basename);
break;
case WTAP_ERR_RANDOM_OPEN_PIPE:
simple_error_message_box(
"The file \"%s\" is a pipe or FIFO; Wireshark can't read pipe or FIFO files.\n"
"To capture from a pipe or FIFO use wireshark -i -",
display_basename);
break;
case WTAP_ERR_FILE_UNKNOWN_FORMAT:
simple_error_message_box(
"The file \"%s\" isn't a capture file in a format Wireshark understands.",
display_basename);
break;
case WTAP_ERR_UNSUPPORTED:
simple_error_message_box(
"The file \"%s\" contains record data that Wireshark doesn't support.\n"
"(%s)",
display_basename,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
simple_error_message_box(
"The file \"%s\" is a capture for a network type that Wireshark doesn't support.",
display_basename);
break;
case WTAP_ERR_BAD_FILE:
simple_error_message_box(
"The file \"%s\" appears to be damaged or corrupt.\n"
"(%s)",
display_basename,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_CANT_OPEN:
simple_error_message_box(
"The file \"%s\" could not be opened for some unknown reason.",
display_basename);
break;
case WTAP_ERR_SHORT_READ:
simple_error_message_box(
"The file \"%s\" appears to have been cut short"
" in the middle of a packet or other data.",
display_basename);
break;
case WTAP_ERR_DECOMPRESS:
simple_error_message_box(
"The file \"%s\" cannot be decompressed; it may be damaged or corrupt.\n"
"(%s)", display_basename,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_INTERNAL:
simple_error_message_box(
"An internal error occurred opening the file \"%s\".\n"
"(%s)", display_basename,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED:
simple_error_message_box(
"The file \"%s\" cannot be decompressed; it is compressed in a way that we don't support.\n"
"(%s)", display_basename,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
default:
simple_error_message_box(
"The file \"%s\" could not be opened: %s.",
display_basename,
wtap_strerror(err));
break;
}
g_free(display_basename);
} else {
/* OS error. */
open_failure_alert_box(filename, err, FALSE);
}
}
/*
* Alert box for a failed attempt to open a capture file for writing.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values;
* "file_type_subtype" is a WTAP_FILE_TYPE_SUBTYPE_ value for the type
* and subtype of file being opened.
*
* XXX - add explanatory secondary text for at least some of the errors;
* various HIGs suggest that you should, for example, suggest that the
* user remove files if the file system is full. Perhaps that's because
* they're providing guidelines for people less sophisticated than the
* typical Wireshark user is, but....
*/
void
cfile_dump_open_failure_alert_box(const char *filename, int err,
gchar *err_info, int file_type_subtype)
{
gchar *display_basename;
if (err < 0) {
/* Wiretap error. */
display_basename = g_filename_display_basename(filename);
switch (err) {
case WTAP_ERR_NOT_REGULAR_FILE:
simple_error_message_box(
"The file \"%s\" is a \"special file\" or socket or other non-regular file.",
display_basename);
break;
case WTAP_ERR_CANT_WRITE_TO_PIPE:
simple_error_message_box(
"The file \"%s\" is a pipe, and %s capture files can't be "
"written to a pipe.",
display_basename, wtap_file_type_subtype_description(file_type_subtype));
break;
case WTAP_ERR_UNWRITABLE_FILE_TYPE:
simple_error_message_box(
"Wireshark doesn't support writing capture files in that format.");
break;
case WTAP_ERR_UNWRITABLE_ENCAP:
simple_error_message_box("Wireshark can't save this capture in that format.");
break;
case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
simple_error_message_box(
"Wireshark can't save this capture in that format.");
break;
case WTAP_ERR_CANT_OPEN:
simple_error_message_box(
"The file \"%s\" could not be created for some unknown reason.",
display_basename);
break;
case WTAP_ERR_SHORT_WRITE:
simple_error_message_box(
"A full header couldn't be written to the file \"%s\".",
display_basename);
break;
case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
simple_error_message_box(
"This file type cannot be written as a compressed file.");
break;
case WTAP_ERR_INTERNAL:
simple_error_message_box(
"An internal error occurred creating the file \"%s\".\n"
"(%s)",
display_basename,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
default:
simple_error_message_box(
"The file \"%s\" could not be created: %s.",
display_basename,
wtap_strerror(err));
break;
}
g_free(display_basename);
} else {
/* OS error. */
open_failure_alert_box(filename, err, TRUE);
}
}
/*
* Alert box for a failed attempt to read from a capture file.
* "err" is assumed to be a UNIX-style errno or a WTAP_ERR_ value;
* "err_info" is assumed to be a string giving further information for
* some WTAP_ERR_ values.
*/
void
cfile_read_failure_alert_box(const char *filename, int err, gchar *err_info)
{
gchar *display_name;
if (filename == NULL)
display_name = g_strdup("capture file");
else {
gchar *display_basename;
display_basename = g_filename_display_basename(filename);
display_name = ws_strdup_printf("capture file \"%s\"", display_basename);
g_free(display_basename);
}
switch (err) {
case WTAP_ERR_UNSUPPORTED:
simple_error_message_box(
"The %s contains record data that Wireshark doesn't support.\n"
"(%s)",
display_name,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_SHORT_READ:
simple_error_message_box(
"The %s appears to have been cut short in the middle of a packet.",
display_name);
break;
case WTAP_ERR_BAD_FILE:
simple_error_message_box(
"The %s appears to be damaged or corrupt.\n"
"(%s)",
display_name,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_DECOMPRESS:
simple_error_message_box(
"The %s cannot be decompressed; it may be damaged or corrupt.\n"
"(%s)",
display_name,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_INTERNAL:
simple_error_message_box(
"An internal error occurred while reading the %s.\n(%s)",
display_name,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED:
simple_error_message_box(
"The %s cannot be decompressed; it is compressed in a way that we don't support.\n"
"(%s)",
display_name,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
default:
simple_error_message_box(
"An error occurred while reading the %s: %s.",
display_name,
wtap_strerror(err));
break;
}
g_free(display_name);
}
/*
* Alert box for a failed attempt to write to a capture file.
* "in_filename" is the name of the file from which the record being
* written came; "out_filename" is the name of the file to which we're
* writing; "err" is assumed "err" is assumed to be a UNIX-style errno
* or a WTAP_ERR_ value; "err_info" is assumed to be a string giving
* further information for some WTAP_ERR_ values; "framenum" is the frame
* number of the record on which the error occurred; "file_type_subtype"
* is a WTAP_FILE_TYPE_SUBTYPE_ value for the type and subtype of file
* being written.
*/
void
cfile_write_failure_alert_box(const char *in_filename, const char *out_filename,
int err, gchar *err_info, guint32 framenum,
int file_type_subtype)
{
char *in_file_string;
char *out_display_basename;
if (err < 0) {
/* Wiretap error. */
if (in_filename == NULL)
in_file_string = g_strdup("");
else
in_file_string = ws_strdup_printf(" of file \"%s\"", in_filename);
switch (err) {
case WTAP_ERR_UNWRITABLE_ENCAP:
/*
* This is a problem with the particular frame we're writing and
* the file type and subtype we're writing; note that, and report
* the frame number and file type/subtype.
*/
simple_error_message_box(
"Frame %u%s has a network type that can't be saved in a \"%s\" file.",
framenum, in_file_string,
wtap_file_type_subtype_description(file_type_subtype));
break;
case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
/*
* This is a problem with the particular frame we're writing and
* the file type and subtype we're writing; note that, and report
* the frame number and file type/subtype.
*/
simple_error_message_box(
"Frame %u%s has a network type that differs from the network type of earlier packets, which isn't supported in a \"%s\" file.",
framenum, in_file_string,
wtap_file_type_subtype_description(file_type_subtype));
break;
case WTAP_ERR_INTERNAL:
out_display_basename = g_filename_display_basename(out_filename);
simple_error_message_box(
"An internal error occurred while writing to the file \"%s\".\n(%s)",
out_display_basename,
err_info != NULL ? err_info : "no information supplied");
g_free(out_display_basename);
g_free(err_info);
break;
case WTAP_ERR_PACKET_TOO_LARGE:
/*
* This is a problem with the particular frame we're writing and
* the file type and subtype we're writing; note that, and report
* the frame number and file type/subtype.
*/
simple_error_message_box(
"Frame %u%s is larger than Wireshark supports in a \"%s\" file.",
framenum, in_file_string,
wtap_file_type_subtype_description(file_type_subtype));
break;
case WTAP_ERR_UNWRITABLE_REC_TYPE:
/*
* This is a problem with the particular record we're writing and
* the file type and subtype we're writing; note that, and report
* the record number and file type/subtype.
*/
simple_error_message_box(
"Record %u%s has a record type that can't be saved in a \"%s\" file.",
framenum, in_file_string,
wtap_file_type_subtype_description(file_type_subtype));
break;
case WTAP_ERR_UNWRITABLE_REC_DATA:
/*
* This is a problem with the particular record we're writing and
* the file type and subtype we're writing; note that, and report
* the record number and file type/subtype.
*/
simple_error_message_box(
"Record %u%s has data that can't be saved in a \"%s\" file.\n"
"(%s)",
framenum, in_file_string,
wtap_file_type_subtype_description(file_type_subtype),
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_SHORT_WRITE:
out_display_basename = g_filename_display_basename(out_filename);
simple_error_message_box(
"A full write couldn't be done to the file \"%s\".",
out_display_basename);
g_free(out_display_basename);
break;
default:
out_display_basename = g_filename_display_basename(out_filename);
simple_error_message_box(
"An error occurred while writing to the file \"%s\": %s.",
out_display_basename, wtap_strerror(err));
g_free(out_display_basename);
break;
}
g_free(in_file_string);
} else {
/* OS error. */
write_failure_alert_box(out_filename, err);
}
}
/*
* Alert box for a failed attempt to close a capture file.
* "err" is assumed to be a UNIX-style errno or a WTAP_ERR_ value;
* "err_info" is assumed to be a string giving further information for
* some WTAP_ERR_ values.
*
* When closing a capture file:
*
* some information in the file that can't be determined until
* all packets have been written might be written to the file
* (such as a table of the file offsets of all packets);
*
* data buffered in the low-level file writing code might be
* flushed to the file;
*
* for remote file systems, data written to the file but not
* yet sent to the server might be sent to the server or, if
* that data was sent asynchronously, "out of space", "disk
* quota exceeded", or "I/O error" indications might have
* been received but not yet delivered, and the close operation
* could deliver them;
*
* so we have to check for write errors here.
*
* XXX - add explanatory secondary text for at least some of the errors;
* various HIGs suggest that you should, for example, suggest that the
* user remove files if the file system is full. Perhaps that's because
* they're providing guidelines for people less sophisticated than the
* typical Wireshark user is, but....
*/
void
cfile_close_failure_alert_box(const char *filename, int err, gchar *err_info)
{
gchar *display_basename;
if (err < 0) {
/* Wiretap error. */
display_basename = g_filename_display_basename(filename);
switch (err) {
case WTAP_ERR_CANT_CLOSE:
simple_error_message_box(
"The file \"%s\" couldn't be closed for some unknown reason.",
display_basename);
break;
case WTAP_ERR_SHORT_WRITE:
simple_error_message_box(
"A full write couldn't be done to the file \"%s\".",
display_basename);
break;
case WTAP_ERR_INTERNAL:
simple_error_message_box(
"An internal error occurred closing the file \"%s\".\n"
"(%s)",
display_basename,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
default:
simple_error_message_box(
"An error occurred while closing the file \"%s\": %s.",
display_basename, wtap_strerror(err));
break;
}
g_free(display_basename);
} else {
/* OS error.
We assume that a close error from the OS is really a write error. */
write_failure_alert_box(filename, err);
}
}
/*
* Alert box for a failed attempt to open or create a file.
* "err" is assumed to be a UNIX-style errno; "for_writing" is TRUE if
* the file is being opened for writing and FALSE if it's being opened
* for reading.
*
* XXX - add explanatory secondary text for at least some of the errors;
* various HIGs suggest that you should, for example, suggest that the
* user remove files if the file system is full. Perhaps that's because
* they're providing guidelines for people less sophisticated than the
* typical Wireshark user is, but....
*/
void
open_failure_alert_box(const char *filename, int err, gboolean for_writing)
{
gchar *display_basename;
display_basename = g_filename_display_basename(filename);
simple_message_box(ESD_TYPE_ERROR, NULL, NULL,
file_open_error_message(err, for_writing),
display_basename);
g_free(display_basename);
}
/*
* Alert box for a failed attempt to read a file.
* "err" is assumed to be a UNIX-style errno.
*/
void
read_failure_alert_box(const char *filename, int err)
{
gchar *display_basename;
display_basename = g_filename_display_basename(filename);
simple_message_box(ESD_TYPE_ERROR, NULL, NULL,
"An error occurred while reading from the file \"%s\": %s.",
display_basename, g_strerror(err));
g_free(display_basename);
}
/*
* Alert box for a failed attempt to write to a file.
* "err" is assumed to be a UNIX-style errno.
*
* XXX - add explanatory secondary text for at least some of the errors;
* various HIGs suggest that you should, for example, suggest that the
* user remove files if the file system is full. Perhaps that's because
* they're providing guidelines for people less sophisticated than the
* typical Wireshark user is, but....
*/
void
write_failure_alert_box(const char *filename, int err)
{
gchar *display_basename;
display_basename = g_filename_display_basename(filename);
simple_message_box(ESD_TYPE_ERROR, NULL, NULL,
file_write_error_message(err), display_basename);
g_free(display_basename);
} |
C/C++ | wireshark/ui/alert_box.h | /** @file
*
* Routines to put up various "standard" alert boxes used in multiple
* places
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __ALERT_BOX_H__
#define __ALERT_BOX_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* Alert box for general errors.
*/
extern void failure_alert_box(const char *msg_format, ...) G_GNUC_PRINTF(1, 2);
extern void vfailure_alert_box(const char *msg_format, va_list ap);
/*
* Alert box for general warnings.
*/
extern void vwarning_alert_box(const char *msg_format, va_list ap);
/*
* Alert box for a failed attempt to open a capture file for reading.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values..
*/
extern void cfile_open_failure_alert_box(const char *filename, int err,
gchar *err_info);
/*
* Alert box for a failed attempt to open a capture file for writing.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values;
* "file_type_subtype" is a WTAP_FILE_TYPE_SUBTYPE_ value for the type
* and subtype of file being opened.
*/
extern void cfile_dump_open_failure_alert_box(const char *filename, int err,
gchar *err_info,
int file_type_subtype);
/*
* Alert box for a failed attempt to read from a capture file.
* "err" is assumed to be a UNIX-style errno or a WTAP_ERR_ value;
* "err_info" is assumed to be a string giving further information for
* some WTAP_ERR_ values.
*/
extern void cfile_read_failure_alert_box(const char *filename, int err,
gchar *err_info);
/*
* Alert box for a failed attempt to write to a capture file.
* "in_filename" is the name of the file from which the record being
* written came; "out_filename" is the name of the file to which we're
* writing; "err" is assumed "err" is assumed to be a UNIX-style errno
* or a WTAP_ERR_ value; "err_info" is assumed to be a string giving
* further information for some WTAP_ERR_ values; "framenum" is the frame
* number of the record on which the error occurred; "file_type_subtype"
* is a WTAP_FILE_TYPE_SUBTYPE_ value for the type and subtype of file
* being written.
*/
extern void cfile_write_failure_alert_box(const char *in_filename,
const char *out_filename,
int err, gchar *err_info,
guint32 framenum,
int file_type_subtype);
/*
* Alert box for a failed attempt to close a capture file.
* "err" is assumed to be a UNIX-style errno or a WTAP_ERR_ value;
* "err_info" is assumed to be a string giving further information for
* some WTAP_ERR_ values.
*
* When closing a capture file:
*
* some information in the file that can't be determined until
* all packets have been written might be written to the file
* (such as a table of the file offsets of all packets);
*
* data buffered in the low-level file writing code might be
* flushed to the file;
*
* for remote file systems, data written to the file but not
* yet sent to the server might be sent to the server or, if
* that data was sent asynchronously, "out of space", "disk
* quota exceeded", or "I/O error" indications might have
* been received but not yet delivered, and the close operation
* could deliver them;
*
* so we have to check for write errors here.
*/
extern void cfile_close_failure_alert_box(const char *filename, int err,
gchar *err_info);
/*
* Alert box for a failed attempt to open or create a file.
* "err" is assumed to be a UNIX-style errno; "for_writing" is TRUE if
* the file is being opened for writing and FALSE if it's being opened
* for reading.
*/
extern void open_failure_alert_box(const char *filename, int err,
gboolean for_writing);
/*
* Alert box for a failed attempt to read a file.
* "err" is assumed to be a UNIX-style errno.
*/
extern void read_failure_alert_box(const char *filename, int err);
/*
* Alert box for a failed attempt to write to a file.
* "err" is assumed to be a UNIX-style errno.
*/
extern void write_failure_alert_box(const char *filename, int err);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __ALERT_BOX_H__ */ |
C/C++ | wireshark/ui/all_files_wildcard.h | /** @file
*
* Definition of a macro for the file wildcard pattern that matches
* all files
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __ALL_FILES_WILDCARD_H__
#define __ALL_FILES_WILDCARD_H__
#ifdef _WIN32
/*
* On Windows, the wildcard for matching all files is "*.*", which
* even matches files with no extension.
*/
#define ALL_FILES_WILDCARD "*.*"
#else
/*
* On UN*X, the wildcard for matching all files is "*"; "*.*" only
* matches files with at least one extension.
*/
#define ALL_FILES_WILDCARD "*"
#endif
#endif /* __ALL_FILES_WILDCARD_H__ */ |
C | wireshark/ui/capture.c | /* capture.c
* Routines for packet capture
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#define WS_LOG_DOMAIN LOG_DOMAIN_CAPTURE
#ifdef HAVE_LIBPCAP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <epan/packet.h>
#include <epan/dfilter/dfilter.h>
#include "extcap.h"
#include "file.h"
#include "ui/capture.h"
#include "capture/capture_ifinfo.h"
#include <capture/capture_sync.h>
#include "ui/capture_info.h"
#include "ui/capture_ui_utils.h"
#include "ui/util.h"
#include "ui/urls.h"
#include "capture/capture-pcap-util.h"
#ifdef _WIN32
#include "capture/capture-wpcap.h"
#endif
#include "ui/simple_dialog.h"
#include "ui/ws_ui_util.h"
#include "wsutil/file_util.h"
#include "wsutil/str_util.h"
#include <wsutil/filesystem.h>
#include <wsutil/wslog.h>
#include <wsutil/ws_assert.h>
typedef struct if_stat_cache_item_s {
char *name;
struct pcap_stat ps;
} if_stat_cache_item_t;
struct if_stat_cache_s {
int stat_fd;
ws_process_id fork_child;
GList *cache_list; /* List of if_stat_chache_entry_t */
};
/* this callback mechanism should possibly be replaced by the g_signal_...() stuff (if I only would know how :-) */
typedef struct {
capture_callback_t cb_fct;
gpointer user_data;
} capture_callback_data_t;
static GList *capture_callbacks = NULL;
static void
capture_callback_invoke(int event, capture_session *cap_session)
{
capture_callback_data_t *cb;
GList *cb_item = capture_callbacks;
/* there should be at least one interested */
ws_assert(cb_item != NULL);
while(cb_item != NULL) {
cb = (capture_callback_data_t *)cb_item->data;
cb->cb_fct(event, cap_session, cb->user_data);
cb_item = g_list_next(cb_item);
}
}
void
capture_callback_add(capture_callback_t func, gpointer user_data)
{
capture_callback_data_t *cb;
cb = g_new(capture_callback_data_t, 1);
cb->cb_fct = func;
cb->user_data = user_data;
capture_callbacks = g_list_prepend(capture_callbacks, cb);
}
void
capture_callback_remove(capture_callback_t func, gpointer user_data)
{
capture_callback_data_t *cb;
GList *cb_item = capture_callbacks;
while(cb_item != NULL) {
cb = (capture_callback_data_t *)cb_item->data;
if(cb->cb_fct == func && cb->user_data == user_data) {
capture_callbacks = g_list_remove(capture_callbacks, cb);
g_free(cb);
return;
}
cb_item = g_list_next(cb_item);
}
ws_assert_not_reached();
}
/**
* Start a capture.
*
* @return TRUE if the capture starts successfully, FALSE otherwise.
*/
gboolean
capture_start(capture_options *capture_opts, GPtrArray *capture_comments,
capture_session *cap_session, info_data_t* cap_data,
void(*update_cb)(void))
{
GString *source;
cap_session->state = CAPTURE_PREPARING;
cap_session->count = 0;
ws_message("Capture Start ...");
source = get_iface_list_string(capture_opts, IFLIST_SHOW_FILTER);
cf_set_tempfile_source((capture_file *)cap_session->cf, source->str);
g_string_free(source, TRUE);
/* try to start the capture child process */
if (!sync_pipe_start(capture_opts, capture_comments, cap_session,
cap_data, update_cb)) {
/* We failed to start the capture child. */
if(capture_opts->save_file != NULL) {
g_free(capture_opts->save_file);
capture_opts->save_file = NULL;
}
ws_message("Capture Start failed.");
cap_session->state = CAPTURE_STOPPED;
return FALSE;
}
// Do we need data structures for ignoring duplicate frames?
if (prefs.ignore_dup_frames && capture_opts->real_time_mode) {
fifo_string_cache_init(&cap_session->frame_dup_cache,
prefs.ignore_dup_frames_cache_entries, g_free);
cap_session->frame_cksum = g_checksum_new(G_CHECKSUM_SHA256);
}
/* the capture child might not respond shortly after bringing it up */
/* (for example: it will block if no input arrives from an input capture pipe (e.g. mkfifo)) */
/* to prevent problems, bring the main GUI into "capture mode" right after a successful */
/* spawn/exec of the capture child, without waiting for any response from it */
capture_callback_invoke(capture_cb_capture_prepared, cap_session);
wtap_rec_init(&cap_session->rec);
ws_buffer_init(&cap_session->buf, 1514);
cap_session->wtap = NULL;
if (capture_opts->show_info) {
if (cap_data->counts.counts_hash != NULL)
{
/* Clean up any previous lists of packet counts */
g_hash_table_destroy(cap_data->counts.counts_hash);
}
cap_data->counts.counts_hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, g_free);
cap_data->counts.other = 0;
cap_data->counts.total = 0;
cap_data->ui.counts = &cap_data->counts;
capture_info_ui_create(&cap_data->ui, cap_session);
}
return TRUE;
}
void
capture_stop(capture_session *cap_session)
{
ws_message("Capture Stop ...");
capture_callback_invoke(capture_cb_capture_stopping, cap_session);
if (!extcap_session_stop(cap_session)) {
extcap_request_stop(cap_session);
cap_session->capture_opts->stop_after_extcaps = TRUE;
} else {
/* stop the capture child gracefully */
sync_pipe_stop(cap_session);
}
}
void
capture_kill_child(capture_session *cap_session)
{
ws_info("Capture Kill");
/* kill the capture child */
sync_pipe_kill(cap_session->fork_child);
}
/* We've succeeded in doing a (non real-time) capture; try to read it into a new capture file */
static gboolean
capture_input_read_all(capture_session *cap_session, gboolean is_tempfile,
gboolean drops_known, guint32 drops)
{
capture_options *capture_opts = cap_session->capture_opts;
int err;
/* Capture succeeded; attempt to open the capture file. */
if (cf_open((capture_file *)cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err) != CF_OK) {
/* We're not doing a capture any more, so we don't have a save file. */
return FALSE;
}
/* Set the read filter to NULL. */
/* XXX - this is odd here; try to put it somewhere where it fits better */
cf_set_rfcode((capture_file *)cap_session->cf, NULL);
/* Get the packet-drop statistics.
XXX - there are currently no packet-drop statistics stored
in libpcap captures, and that's what we're reading.
At some point, we will add support in Wiretap to return
packet-drop statistics for capture file formats that store it,
and will make "cf_read()" get those statistics from Wiretap.
We clear the statistics (marking them as "not known") in
"cf_open()", and "cf_read()" will only fetch them and mark
them as known if Wiretap supplies them, so if we get the
statistics now, after calling "cf_open()" but before calling
"cf_read()", the values we store will be used by "cf_read()".
If a future libpcap capture file format stores the statistics,
we'll put them into the capture file that we write, and will
thus not have to set them here - "cf_read()" will get them from
the file and use them. */
if (drops_known) {
cf_set_drops_known((capture_file *)cap_session->cf, TRUE);
/* XXX - on some systems, libpcap doesn't bother filling in
"ps_ifdrop" - it doesn't even set it to zero - so we don't
bother looking at it.
Ideally, libpcap would have an interface that gave us
several statistics - perhaps including various interface
error statistics - and would tell us which of them it
supplies, allowing us to display only the ones it does. */
cf_set_drops((capture_file *)cap_session->cf, drops);
}
/* read in the packet data */
switch (cf_read((capture_file *)cap_session->cf, /*reloading=*/FALSE)) {
case CF_READ_OK:
case CF_READ_ERROR:
/* Just because we got an error, that doesn't mean we were unable
to read any of the file; we handle what we could get from the
file. */
break;
case CF_READ_ABORTED:
/* User wants to quit program. Exit by leaving the main loop,
so that any quit functions we registered get called. */
exit_application(0);
return FALSE;
}
/* if we didn't capture even a single packet, close the file again */
if(cap_session->count == 0 && !capture_opts->restart) {
simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
"%sNo packets captured.%s\n"
"\n"
"As no data was captured, closing the %scapture file.\n"
"\n"
"\n"
"Help about capturing can be found at\n"
"\n"
" " WS_WIKI_URL("CaptureSetup")
#ifdef _WIN32
"\n\n"
"Wireless (Wi-Fi/WLAN):\n"
"Try to switch off promiscuous mode in the Capture Options"
#endif
"",
simple_dialog_primary_start(), simple_dialog_primary_end(),
(cf_is_tempfile((capture_file *)cap_session->cf)) ? "temporary " : "");
cf_close((capture_file *)cap_session->cf);
}
return TRUE;
}
static const char *
cf_open_error_message(int err, gchar *err_info)
{
const char *errmsg;
static char errmsg_errno[1024 + 1];
if (err < 0) {
/* Wiretap error. */
switch (err) {
case WTAP_ERR_NOT_REGULAR_FILE:
errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
break;
case WTAP_ERR_FILE_UNKNOWN_FORMAT:
/* Seen only when opening a capture file for reading. */
errmsg = "The file \"%s\" isn't a capture file in a format Wireshark understands.";
break;
case WTAP_ERR_UNSUPPORTED:
snprintf(errmsg_errno, sizeof(errmsg_errno),
"The file \"%%s\" contains record data that Wireshark doesn't support.\n"
"(%s)", err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
errmsg = errmsg_errno;
break;
case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
errmsg = "The file \"%s\" is a capture for a network type that Wireshark doesn't support.";
break;
case WTAP_ERR_BAD_FILE:
snprintf(errmsg_errno, sizeof(errmsg_errno),
"The file \"%%s\" appears to be damaged or corrupt.\n"
"(%s)", err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
errmsg = errmsg_errno;
break;
case WTAP_ERR_CANT_OPEN:
errmsg = "The file \"%s\" could not be opened for some unknown reason.";
break;
case WTAP_ERR_SHORT_READ:
errmsg = "The file \"%s\" appears to have been cut short"
" in the middle of a packet or other data.";
break;
case WTAP_ERR_DECOMPRESS:
snprintf(errmsg_errno, sizeof(errmsg_errno),
"The file \"%%s\" cannot be decompressed; it may be damaged or corrupt.\n"
"(%s)", err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
errmsg = errmsg_errno;
break;
case WTAP_ERR_INTERNAL:
snprintf(errmsg_errno, sizeof(errmsg_errno),
"An internal error occurred opening the file \"%%s\".\n"
"(%s)", err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
errmsg = errmsg_errno;
break;
case WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED:
snprintf(errmsg_errno, sizeof(errmsg_errno),
"The file \"%%s\" cannot be decompressed; it is compressed in a way that We don't support.\n"
"(%s)", err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
errmsg = errmsg_errno;
break;
default:
snprintf(errmsg_errno, sizeof(errmsg_errno),
"The file \"%%s\" could not be opened: %s.",
wtap_strerror(err));
errmsg = errmsg_errno;
break;
}
}
else
errmsg = file_open_error_message(err, FALSE);
return errmsg;
}
/* capture child tells us we have a new (or the first) capture file */
static bool
capture_input_new_file(capture_session *cap_session, gchar *new_file)
{
capture_options *capture_opts = cap_session->capture_opts;
gboolean is_tempfile;
int err;
gchar *err_info;
gchar *err_msg;
if(cap_session->state == CAPTURE_PREPARING) {
ws_message("Capture started");
}
ws_message("File: \"%s\"", new_file);
ws_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
/* free the old filename */
if(capture_opts->save_file != NULL) {
/* we start a new capture file, close the old one (if we had one before). */
/* (we can only have an open capture file in real_time_mode!) */
if (((capture_file*)cap_session->cf)->state == FILE_READ_PENDING) {
capture_callback_invoke(capture_cb_capture_fixed_finished, cap_session);
} else if (((capture_file*)cap_session->cf)->state != FILE_CLOSED) {
cap_session->session_will_restart = TRUE;
capture_callback_invoke(capture_cb_capture_update_finished, cap_session);
cf_finish_tail((capture_file *)cap_session->cf,
&cap_session->rec, &cap_session->buf, &err,
&cap_session->frame_dup_cache, cap_session->frame_cksum);
cf_close((capture_file *)cap_session->cf);
}
g_free(capture_opts->save_file);
is_tempfile = FALSE;
cf_set_tempfile((capture_file *)cap_session->cf, FALSE);
} else {
/* we didn't have a save_file before; must be a tempfile */
is_tempfile = TRUE;
cf_set_tempfile((capture_file *)cap_session->cf, TRUE);
}
/* save the new filename */
capture_opts->save_file = g_strdup(new_file);
/* if we are in real-time mode, open the new file now */
if(capture_opts->real_time_mode) {
/* Attempt to open the capture file and set up to read from it. */
switch(cf_open((capture_file *)cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
case CF_OK:
break;
case CF_ERROR:
/* Don't unlink (delete) the save file - leave it around,
for debugging purposes. */
g_free(capture_opts->save_file);
capture_opts->save_file = NULL;
return FALSE;
}
} else {
capture_callback_invoke(capture_cb_capture_prepared, cap_session);
}
if(capture_opts->show_info) {
if (cap_session->wtap != NULL) {
wtap_close(cap_session->wtap);
}
cap_session->wtap = wtap_open_offline(new_file, WTAP_TYPE_AUTO, &err, &err_info, FALSE);
if (!cap_session->wtap) {
err_msg = ws_strdup_printf(cf_open_error_message(err, err_info),
new_file);
ws_warning("capture_input_new_file: %d (%s)", err, err_msg);
g_free(err_msg);
return FALSE;
}
}
if(capture_opts->real_time_mode) {
capture_callback_invoke(capture_cb_capture_update_started, cap_session);
} else {
capture_callback_invoke(capture_cb_capture_fixed_started, cap_session);
}
cap_session->state = CAPTURE_RUNNING;
return TRUE;
}
static void
capture_info_packet(info_data_t* cap_info, gint wtap_linktype, const guchar *pd, guint32 caplen, union wtap_pseudo_header *pseudo_header)
{
capture_packet_info_t cpinfo;
/* Setup the capture packet structure */
cpinfo.counts = cap_info->counts.counts_hash;
cap_info->counts.total++;
if (!try_capture_dissector("wtap_encap", wtap_linktype, pd, 0, caplen, &cpinfo, pseudo_header))
cap_info->counts.other++;
}
/* new packets arrived */
static void
capture_info_new_packets(int to_read, wtap *wth, info_data_t* cap_info)
{
int err;
gchar *err_info;
gint64 data_offset;
wtap_rec rec;
Buffer buf;
union wtap_pseudo_header *pseudo_header;
int wtap_linktype;
cap_info->ui.new_packets = to_read;
/*ws_warning("new packets: %u", to_read);*/
wtap_rec_init(&rec);
ws_buffer_init(&buf, 1514);
while (to_read > 0) {
wtap_cleareof(wth);
if (wtap_read(wth, &rec, &buf, &err, &err_info, &data_offset)) {
if (rec.rec_type == REC_TYPE_PACKET) {
pseudo_header = &rec.rec_header.packet_header.pseudo_header;
wtap_linktype = rec.rec_header.packet_header.pkt_encap;
capture_info_packet(cap_info, wtap_linktype,
ws_buffer_start_ptr(&buf),
rec.rec_header.packet_header.caplen,
pseudo_header);
/*ws_warning("new packet");*/
to_read--;
}
wtap_rec_reset(&rec);
}
}
wtap_rec_cleanup(&rec);
ws_buffer_free(&buf);
capture_info_ui_update(&cap_info->ui);
}
/* capture child tells us we have new packets to read */
static void
capture_input_new_packets(capture_session *cap_session, int to_read)
{
capture_options *capture_opts = cap_session->capture_opts;
int err;
ws_assert(capture_opts->save_file);
if(capture_opts->real_time_mode) {
if (((capture_file*)cap_session->cf)->state == FILE_READ_PENDING) {
/* Attempt to open the capture file and set up to read from it. */
switch (cf_open((capture_file*)cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, cf_is_tempfile((capture_file*)cap_session->cf), &err)) {
case CF_OK:
break;
case CF_ERROR:
/* Don't unlink (delete) the save file - leave it around,
for debugging purposes. */
g_free(capture_opts->save_file);
capture_opts->save_file = NULL;
capture_kill_child(cap_session);
}
capture_callback_invoke(capture_cb_capture_update_started, cap_session);
}
/* Read from the capture file the number of records the child told us it added. */
to_read += cap_session->count_pending;
cap_session->count_pending = 0;
switch (cf_continue_tail((capture_file *)cap_session->cf, to_read,
&cap_session->rec, &cap_session->buf, &err,
&cap_session->frame_dup_cache, cap_session->frame_cksum)) {
case CF_READ_OK:
case CF_READ_ERROR:
/* Just because we got an error, that doesn't mean we were unable
to read any of the file; we handle what we could get from the
file.
XXX - abort on a read error? */
capture_callback_invoke(capture_cb_capture_update_continue, cap_session);
break;
case CF_READ_ABORTED:
/* Kill the child capture process; the user wants to exit, and we
shouldn't just leave it running. */
capture_kill_child(cap_session);
break;
}
} else {
cf_fake_continue_tail((capture_file *)cap_session->cf);
cap_session->count_pending += to_read;
capture_callback_invoke(capture_cb_capture_fixed_continue, cap_session);
}
if(cap_session->wtap)
capture_info_new_packets(to_read, cap_session->wtap, cap_session->cap_data_info);
}
/* Capture child told us how many dropped packets it counted.
*/
static void
capture_input_drops(capture_session *cap_session, guint32 dropped, const char* interface_name)
{
if (interface_name != NULL) {
ws_info("%u packet%s dropped from %s", dropped, plurality(dropped, "", "s"), interface_name);
} else {
ws_info("%u packet%s dropped", dropped, plurality(dropped, "", "s"));
}
ws_assert(cap_session->state == CAPTURE_RUNNING);
cf_set_drops_known((capture_file *)cap_session->cf, TRUE);
cf_set_drops((capture_file *)cap_session->cf, dropped);
}
/* Capture child told us that an error has occurred while starting/running
the capture.
The buffer we're handed has *two* null-terminated strings in it - a
primary message and a secondary message, one right after the other.
The secondary message might be a null string.
*/
static void
capture_input_error(capture_session *cap_session _U_, char *error_msg,
char *secondary_error_msg)
{
gchar *safe_error_msg;
gchar *safe_secondary_error_msg;
ws_message("Error message from child: \"%s\", \"%s\"", error_msg, secondary_error_msg);
ws_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
safe_error_msg = simple_dialog_format_message(error_msg);
if (*secondary_error_msg != '\0') {
/* We have both primary and secondary messages. */
safe_secondary_error_msg = simple_dialog_format_message(secondary_error_msg);
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s%s%s\n\n%s",
simple_dialog_primary_start(), safe_error_msg,
simple_dialog_primary_end(), safe_secondary_error_msg);
g_free(safe_secondary_error_msg);
} else {
/* We have only a primary message. */
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s%s%s",
simple_dialog_primary_start(), safe_error_msg,
simple_dialog_primary_end());
}
g_free(safe_error_msg);
/* the capture child will close the sync_pipe if required, nothing to do for now */
}
/* Capture child told us that an error has occurred while parsing a
capture filter when starting/running the capture.
*/
static void
capture_input_cfilter_error(capture_session *cap_session, guint i,
const char *error_message)
{
capture_options *capture_opts = cap_session->capture_opts;
dfilter_t *rfcode = NULL;
gchar *safe_cfilter;
gchar *safe_descr;
gchar *safe_cfilter_error_msg;
interface_options *interface_opts;
ws_message("Capture filter error message from child: \"%s\"", error_message);
ws_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
ws_assert(i < capture_opts->ifaces->len);
interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
safe_cfilter = simple_dialog_format_message(interface_opts->cfilter);
safe_descr = simple_dialog_format_message(interface_opts->descr);
safe_cfilter_error_msg = simple_dialog_format_message(error_message);
/* Did the user try a display filter? */
if (dfilter_compile(interface_opts->cfilter, &rfcode, NULL) && rfcode != NULL) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"%sInvalid capture filter \"%s\" for interface %s.%s\n"
"\n"
"That string looks like a valid display filter; however, it isn't a valid\n"
"capture filter (%s).\n"
"\n"
"Note that display filters and capture filters don't have the same syntax,\n"
"so you can't use most display filter expressions as capture filters.\n"
"\n"
"See the User's Guide for a description of the capture filter syntax.",
simple_dialog_primary_start(), safe_cfilter, safe_descr,
simple_dialog_primary_end(), safe_cfilter_error_msg);
dfilter_free(rfcode);
} else {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"%sInvalid capture filter \"%s\" for interface %s.%s\n"
"\n"
"That string isn't a valid capture filter (%s).\n"
"See the User's Guide for a description of the capture filter syntax.",
simple_dialog_primary_start(), safe_cfilter, safe_descr,
simple_dialog_primary_end(), safe_cfilter_error_msg);
}
g_free(safe_cfilter_error_msg);
g_free(safe_descr);
g_free(safe_cfilter);
/* the capture child will close the sync_pipe if required, nothing to do for now */
}
/* capture child closed its side of the pipe, do the required cleanup */
static void
capture_input_closed(capture_session *cap_session, gchar *msg)
{
capture_options *capture_opts = cap_session->capture_opts;
int err;
ws_message("Capture stopped.");
ws_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
if (msg != NULL) {
ESD_TYPE_E dlg_type = ESD_TYPE_ERROR;
if (strstr(msg, " WARNING] ")) {
dlg_type = ESD_TYPE_WARN;
}
/*
* ws_log prefixes log messages with a timestamp delimited by " -- " and possibly
* a function name delimted by "(): ". Log it to sterr, but omit it in the UI.
*/
char *plain_msg = strstr(msg, "(): ");
if (plain_msg != NULL) {
plain_msg += strlen("(): ");
} else if ((plain_msg = strstr(msg, " -- ")) != NULL) {
plain_msg += strlen(" -- ");
} else {
plain_msg = msg;
}
ws_warning("%s", msg);
simple_dialog(dlg_type, ESD_BTN_OK, "%s", plain_msg);
}
wtap_rec_cleanup(&cap_session->rec);
ws_buffer_free(&cap_session->buf);
if(cap_session->state == CAPTURE_PREPARING) {
/* We started the capture child, but we didn't manage to start
the capture process; note that the attempt to start it
failed. */
capture_callback_invoke(capture_cb_capture_failed, cap_session);
} else {
/* We started a capture; process what's left of the capture file if
we were in "update list of packets in real time" mode, or process
all of it if we weren't. */
if(((capture_file*)cap_session->cf)->state == FILE_READ_IN_PROGRESS) {
cf_read_status_t status;
/* Read what remains of the capture file. */
status = cf_finish_tail((capture_file *)cap_session->cf,
&cap_session->rec, &cap_session->buf, &err,
&cap_session->frame_dup_cache, cap_session->frame_cksum);
// The real-time reading of the pcap is done. Now we can clear the
// dup-frame cache, if present. But check that we actually have
// data structures to clear (by checking frame-checksum); the user
// could have changed the preference *during* the live capture.
if (cap_session->frame_cksum != NULL) {
fifo_string_cache_free(&cap_session->frame_dup_cache);
g_checksum_free(cap_session->frame_cksum);
cap_session->frame_cksum = NULL;
}
/* Tell the GUI we are not doing a capture any more.
Must be done after the cf_finish_tail(), so file lengths are
correctly displayed */
cap_session->session_will_restart = FALSE;
capture_callback_invoke(capture_cb_capture_update_finished, cap_session);
/* Finish the capture. */
switch (status) {
case CF_READ_OK:
if (cap_session->count == 0 && !capture_opts->restart) {
simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
"%sNo packets captured.%s\n"
"\n"
"As no data was captured, closing the %scapture file.\n"
"\n"
"\n"
"Help about capturing can be found at\n"
"\n"
" " WS_WIKI_URL("CaptureSetup")
#ifdef _WIN32
"\n\n"
"Wireless (Wi-Fi/WLAN):\n"
"Try to switch off promiscuous mode in the Capture Options."
#endif
"",
simple_dialog_primary_start(), simple_dialog_primary_end(),
cf_is_tempfile((capture_file *)cap_session->cf) ? "temporary " : "");
cf_close((capture_file *)cap_session->cf);
}
break;
case CF_READ_ERROR:
/* Just because we got an error, that doesn't mean we were unable
to read any of the file; we handle what we could get from the
file. */
break;
case CF_READ_ABORTED:
/* Exit by leaving the main loop, so that any quit functions
we registered get called. */
exit_application(0);
break;
}
} else if (((capture_file*)cap_session->cf)->state == FILE_READ_PENDING) {
/* first of all, we are not doing a capture any more */
capture_callback_invoke(capture_cb_capture_fixed_finished, cap_session);
/* this is a normal mode capture and if no error happened, read in the capture file data */
if(capture_opts->save_file != NULL) {
capture_input_read_all(cap_session, cf_is_tempfile((capture_file *)cap_session->cf),
cf_get_drops_known((capture_file *)cap_session->cf), cf_get_drops((capture_file *)cap_session->cf));
}
}
}
capture_info_ui_destroy(&cap_session->cap_data_info->ui);
if(cap_session->wtap) {
wtap_close(cap_session->wtap);
cap_session->wtap = NULL;
}
cap_session->state = CAPTURE_STOPPED;
/* if we couldn't open a capture file, there's nothing more for us to do */
if(capture_opts->save_file == NULL) {
cf_close((capture_file *)cap_session->cf);
return;
}
/* does the user wants to restart the current capture? */
if(capture_opts->restart) {
capture_opts->restart = FALSE;
/* If we have a ring buffer, the original save file has been overwritten
with the "ring filename". Restore it before starting again */
if ((capture_opts->multi_files_on) && (capture_opts->orig_save_file != NULL)) {
g_free(capture_opts->save_file);
capture_opts->save_file = g_strdup(capture_opts->orig_save_file);
}
/* If it was a tempfile, throw away the old filename (so it will become a tempfile again) */
if (cf_is_tempfile((capture_file *)cap_session->cf)) {
g_free(capture_opts->save_file);
capture_opts->save_file = NULL;
}
} else {
/* We're not doing a capture any more, so we don't have a save file. */
g_free(capture_opts->save_file);
capture_opts->save_file = NULL;
}
}
if_stat_cache_t *
capture_stat_start(capture_options *capture_opts)
{
int stat_fd;
ws_process_id fork_child;
gchar *msg;
if_stat_cache_t *sc = g_new0(if_stat_cache_t, 1);
if_stat_cache_item_t *sc_item;
guint i;
interface_t *device;
sc->stat_fd = -1;
sc->fork_child = WS_INVALID_PID;
/* Fire up dumpcap. */
/*
* XXX - on systems with BPF, the number of BPF devices limits the
* number of devices on which you can capture simultaneously.
*
* This means that
*
* 1) this might fail if you run out of BPF devices
*
* and
*
* 2) opening every interface could leave too few BPF devices
* for *other* programs.
*
* It also means the system could end up getting a lot of traffic
* that it has to pass through the networking stack and capture
* mechanism, so opening all the devices and presenting packet
* counts might not always be a good idea.
*/
if (sync_interface_stats_open(&stat_fd, &fork_child, &msg, NULL) == 0) {
sc->stat_fd = stat_fd;
sc->fork_child = fork_child;
/* Initialize the cache */
for (i = 0; i < capture_opts->all_ifaces->len; i++) {
device = &g_array_index(capture_opts->all_ifaces, interface_t, i);
if (device->type != IF_PIPE && device->type != IF_EXTCAP) {
sc_item = g_new0(if_stat_cache_item_t, 1);
ws_assert(device->if_info.name);
sc_item->name = g_strdup(device->if_info.name);
sc->cache_list = g_list_prepend(sc->cache_list, sc_item);
}
}
} else {
g_free(msg); /* XXX: should we display this to the user ? */
}
return sc;
}
#define MAX_STAT_LINE_LEN 500
static void
capture_stat_cache_update(if_stat_cache_t *sc)
{
gchar stat_line[MAX_STAT_LINE_LEN] = "";
gchar **stat_parts;
GList *sc_entry;
if_stat_cache_item_t *sc_item;
if (!sc || sc->fork_child == WS_INVALID_PID) {
return;
}
while (sync_pipe_gets_nonblock(sc->stat_fd, stat_line, MAX_STAT_LINE_LEN) > 0) {
g_strstrip(stat_line);
stat_parts = g_strsplit(stat_line, "\t", 3);
if (stat_parts[0] == NULL || stat_parts[1] == NULL ||
stat_parts[2] == NULL) {
g_strfreev(stat_parts);
continue;
}
for (sc_entry = sc->cache_list; sc_entry != NULL; sc_entry = g_list_next(sc_entry)) {
sc_item = (if_stat_cache_item_t *)sc_entry->data;
if (strcmp(sc_item->name, stat_parts[0]) == 0) {
sc_item->ps.ps_recv = (u_int) strtoul(stat_parts[1], NULL, 10);
sc_item->ps.ps_drop = (u_int) strtoul(stat_parts[2], NULL, 10);
}
}
g_strfreev(stat_parts);
}
}
gboolean
capture_stats(if_stat_cache_t *sc, char *ifname, struct pcap_stat *ps)
{
GList *sc_entry;
if_stat_cache_item_t *sc_item;
if (!sc || sc->fork_child == WS_INVALID_PID || !ifname || !ps) {
return FALSE;
}
capture_stat_cache_update(sc);
for (sc_entry = sc->cache_list; sc_entry != NULL; sc_entry = g_list_next(sc_entry)) {
sc_item = (if_stat_cache_item_t *)sc_entry->data;
if (strcmp(sc_item->name, ifname) == 0) {
memcpy(ps, &sc_item->ps, sizeof(struct pcap_stat));
return TRUE;
}
}
return FALSE;
}
void
capture_stat_stop(if_stat_cache_t *sc)
{
GList *sc_entry;
if_stat_cache_item_t *sc_item;
int ret;
gchar *msg;
if (!sc) {
return;
}
if (sc->fork_child != WS_INVALID_PID) {
ret = sync_interface_stats_close(&sc->stat_fd, &sc->fork_child, &msg);
if (ret == -1) {
/* XXX - report failure? */
g_free(msg);
}
}
for (sc_entry = sc->cache_list; sc_entry != NULL; sc_entry = g_list_next(sc_entry)) {
sc_item = (if_stat_cache_item_t *)sc_entry->data;
g_free(sc_item->name);
g_free(sc_item);
}
g_list_free(sc->cache_list);
g_free(sc);
}
/* Initialize a capture session for our callbacks. */
void
capture_input_init(capture_session *cap_session, capture_file *cf)
{
capture_session_init(cap_session, cf,
capture_input_new_file, capture_input_new_packets,
capture_input_drops, capture_input_error,
capture_input_cfilter_error, capture_input_closed);
}
#endif /* HAVE_LIBPCAP */ |
C/C++ | wireshark/ui/capture.h | /** @file
*
* Definitions for packet capture windows
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/* This file should only be included if libpcap is present */
#ifndef __CAPTURE_H__
#define __CAPTURE_H__
/** @file
* Capture related things.
*/
#include "capture_opts.h"
#include "capture_info.h"
#include "cfile.h"
#include "capture/capture_session.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef enum {
capture_cb_capture_prepared,
capture_cb_capture_update_started,
capture_cb_capture_update_continue,
capture_cb_capture_update_finished,
capture_cb_capture_fixed_started,
capture_cb_capture_fixed_continue,
capture_cb_capture_fixed_finished,
capture_cb_capture_stopping,
capture_cb_capture_failed
} capture_cbs;
typedef void (*capture_callback_t) (gint event, capture_session *cap_session,
gpointer user_data);
extern void
capture_callback_add(capture_callback_t func, gpointer user_data);
extern void
capture_callback_remove(capture_callback_t func, gpointer user_data);
/**
* Initialize a capture session.
*
* @param cap_session the handle for the capture session
* @param cf the capture_file for the file
*/
extern void
capture_input_init(capture_session *cap_session, capture_file *cf);
/**
* Start a capture session.
*
* @param capture_opts the numerous capture options
* @param capture_comments if not NULL, a GPtrArray * to a set of comments
* to put in the capture file's Section Header Block if it's a pcapng file
* @param cap_session the handle for the capture session
* @param cap_data a struct with capture info data
* @param update_cb update screen
* @return TRUE if the capture starts successfully, FALSE otherwise.
*/
extern gboolean
capture_start(capture_options *capture_opts, GPtrArray *capture_comments,
capture_session *cap_session, info_data_t* cap_data,
void(*update_cb)(void));
/** Stop a capture session (usually from a menu item). */
extern void
capture_stop(capture_session *cap_session);
/** Terminate the capture child cleanly when exiting. */
extern void
capture_kill_child(capture_session *cap_session);
struct if_stat_cache_s;
typedef struct if_stat_cache_s if_stat_cache_t;
/**
* Start gathering capture statistics for the interfaces specified.
* @param capture_opts A structure containing options for the capture.
* @return A pointer to the statistics state data.
*/
extern WS_RETNONNULL if_stat_cache_t * capture_stat_start(capture_options *capture_opts);
/**
* Fetch capture statistics, similar to pcap_stats().
*/
struct pcap_stat; /* Stub in case we don't or haven't yet included pcap.h */
extern gboolean capture_stats(if_stat_cache_t *sc, char *ifname, struct pcap_stat *ps);
/**
* Stop gathering capture statistics.
*/
void capture_stat_stop(if_stat_cache_t *sc);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* capture.h */ |
C/C++ | wireshark/ui/capture_globals.h | /** @file
*
* Capture-related globals.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __CAPTURE_GLOBALS_H__
#define __CAPTURE_GLOBALS_H__
#include "capture_opts.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
extern capture_options global_capture_opts;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __CAPTURE_GLOBALS_H__ */ |
C/C++ | wireshark/ui/capture_info.h | /** @file
*
* Declarations of platform-dependent capture info functions.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/** @file
*
* Capture info functions.
*
*/
#ifndef __CAPTURE_INFO_H__
#define __CAPTURE_INFO_H__
#include "capture_opts.h"
#include <capture/capture_session.h>
#include <epan/capture_dissectors.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** Current Capture info. */
typedef struct _capture_info {
/* handle */
gpointer ui; /**< user interface handle */
/* capture info */
packet_counts *counts; /**< protocol specific counters */
gint new_packets; /**< packets since last update */
} capture_info;
typedef struct _info_data {
packet_counts counts; /* Packet counting */
capture_info ui; /* user interface data */
} info_data_t;
/** Create the capture info dialog */
extern void
capture_info_ui_create(capture_info *cinfo, capture_session *cap_session);
/** Update the capture info counters in the dialog */
extern void capture_info_ui_update(
capture_info *cinfo);
/** Destroy the capture info dialog again */
extern void capture_info_ui_destroy(
capture_info *cinfo);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* ui/capture_info.h */ |
C | wireshark/ui/capture_ui_utils.c | /* capture_ui_utils.c
* Utilities for capture user interfaces
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#ifdef HAVE_LIBPCAP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include "epan/prefs.h"
#include "epan/ex-opt.h"
#include "capture/capture_ifinfo.h"
#include "ui/capture_ui_utils.h"
#include "ui/capture_globals.h"
#include "wiretap/wtap.h"
#include "epan/to_str.h"
#include "wsutil/strtoi.h"
/*
* In a list of interface information, in the form of a comma-separated
* list of {name}({property}) items, find the entry for a particular
* interface, and return a pointer a g_malloced string containing
* the property.
*/
static char *
capture_dev_get_if_property(const gchar *pref, const gchar *if_name)
{
gchar **if_tokens;
gchar *property = NULL;
int i;
if (if_name == NULL || strlen(if_name) < 1) {
return NULL;
}
if (pref == NULL || strlen(pref) < 1) {
/* There is no interface information list. */
return NULL;
}
/*
* Split the list into a sequence of items.
*
* XXX - this relies on the items not themselves containing commas.
*/
if_tokens = g_strsplit(pref, ",", -1);
for (i = 0; if_tokens[i] != NULL; i++) {
gchar *opening_parenp, *closing_parenp;
/*
* Separate this item into name and property.
* The first opening parenthesis and the last closing parenthesis
* surround the property. Any other parentheses are part of
* the property.
*/
opening_parenp = strchr(if_tokens[i], '(');
if (opening_parenp == NULL) {
/* No opening parenthesis. Give up. */
break;
}
closing_parenp = strrchr(if_tokens[i], ')');
if (closing_parenp == NULL || closing_parenp <= opening_parenp) {
/* No closing parenthesis or invalid input. Give up. */
break;
}
*opening_parenp = '\0'; /* Split {name} from what follows */
*closing_parenp = '\0'; /* Terminate {property} */
if (strcmp(if_tokens[i], if_name) == 0) {
if (strlen(opening_parenp + 1) > 0) {
property = g_strdup(opening_parenp + 1);
}
break;
}
}
g_strfreev(if_tokens);
return property;
}
/*
* Find a property that should be an integral value, and return the
* value or, if it's not found or not a valid integral value, -1.
*/
static gint
capture_dev_get_if_int_property(const gchar *pref, const gchar *if_name)
{
gchar *property_string;
gint property;
property_string = capture_dev_get_if_property(pref, if_name);
if (property_string == NULL) {
/* No property found for this interface. */
return -1;
}
if (!ws_strtoi(property_string, NULL, &property)) {
/* Syntax error or range error */
g_free(property_string);
return -1;
}
g_free(property_string);
return property;
}
/*
* Find user-specified capture device description that matches interface
* name, if any.
*/
char *
capture_dev_user_descr_find(const gchar *if_name)
{
return capture_dev_get_if_property(prefs.capture_devices_descr, if_name);
}
gint
capture_dev_user_linktype_find(const gchar *if_name)
{
return capture_dev_get_if_int_property(prefs.capture_devices_linktypes, if_name);
}
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
gint
capture_dev_user_buffersize_find(const gchar *if_name)
{
return capture_dev_get_if_int_property(prefs.capture_devices_buffersize, if_name);
}
#endif
gboolean
capture_dev_user_snaplen_find(const gchar *if_name, gboolean *hassnap, int *snaplen)
{
gboolean found = FALSE;
gchar **if_tokens;
int i;
if (if_name == NULL || strlen(if_name) < 1) {
return FALSE;
}
if ((prefs.capture_devices_snaplen == NULL) ||
(*prefs.capture_devices_snaplen == '\0')) {
/* There are no snap lengths defined */
return FALSE;
}
/*
* Split the list into a sequence of items.
*
* XXX - this relies on the items not themselves containing commas.
*/
if_tokens = g_strsplit(prefs.capture_devices_snaplen, ",", -1);
for (i = 0; if_tokens[i] != NULL; i++) {
gchar *colonp;
const gchar *next;
gint value;
/*
* This one's a bit ugly.
* The syntax of the item is {name}:{hassnap}({snaplen}),
* where {hassnap} is 0 if the interface shouldn't have a snapshot
* length and 1 if it should, and {snaplen} is the maximum snapshot
* length if {hassnap} is 0 and the specified snapshot length if
* {hassnap} is 1.
*
* Sadly, : was a bad choice of separator, given that, on some OSes,
* an interface can have a colon in its name.
*
* So we look for the *last* colon in the string.
*/
colonp = strrchr(if_tokens[i], ':');
if (colonp == NULL) {
/* No separating colon. Give up. */
break;
}
*colonp = '\0'; /* Split {name} from what follows */
if (strcmp(if_tokens[i], if_name) == 0) {
/* OK, this matches. */
if (*(colonp + 1) == '0') {
/* {hassnap} is false, so just set the snaplen to WTAP_MAX_PACKET_SIZE_STANDARD. */
found = TRUE;
*hassnap = FALSE;
*snaplen = WTAP_MAX_PACKET_SIZE_STANDARD;
} else if (*(colonp + 1) == '1') {
/* {hassnap} is true, so extract {snaplen} */
if (*(colonp + 2) != '(') {
/* Not followed by a parenthesis. Give up. */
break;
}
if (!ws_strtoi(colonp + 3, &next, &value) ||
next == colonp + 3 || *next != ')' || value < 0) {
/* Syntax error or range error. Give up. */
break;
}
found = TRUE;
*hassnap = TRUE;
*snaplen = value;
} else {
/* Bad {hassnap}. Give up. */
break;
}
break;
}
}
g_strfreev(if_tokens);
return found;
}
gboolean
capture_dev_user_pmode_find(const gchar *if_name, gboolean *pmode)
{
int value;
value = capture_dev_get_if_int_property(prefs.capture_devices_pmode, if_name);
if (value == -1) {
/* Not found or bad. */
return FALSE;
}
*pmode = (value != 0);
return TRUE;
}
gchar*
capture_dev_user_cfilter_find(const gchar *if_name)
{
return capture_dev_get_if_property(prefs.capture_devices_filter, if_name);
}
/*
* Return as descriptive a name for an interface as we can get.
* If the user has specified a comment, use that. Otherwise,
* if capture_interface_list() supplies a description, use that,
* otherwise use the interface name.
*
* The result must be g_free()'d when you're done with it.
*
* Note: given that this calls capture_interface_list(), which attempts to
* open all adapters it finds in order to check whether they can be
* captured on, this is an expensive routine to call, so don't call it
* frequently.
*/
char *
get_interface_descriptive_name(const char *if_name)
{
char *descr;
GList *if_list;
GList *if_entry;
if_info_t *if_info;
int err;
/* Do we have a user-supplied description? */
descr = capture_dev_user_descr_find(if_name);
if (descr == NULL) {
/* No; try to construct a descriptive name. */
if (strcmp(if_name, "-") == 0) {
/*
* Strictly speaking, -X (extension) options are for modules, e.g. Lua
* and using one here stretches that definition. However, this doesn't
* waste a single-letter option on something that might be rarely used
* and is backward-compatible to 1.0.
*/
descr = g_strdup(ex_opt_get_nth("stdin_descr", 0));
if (!descr) {
descr = g_strdup("Standard input");
}
} else {
/* No, we don't have a user-supplied description; did we get
one from the OS or libpcap? */
if_list = capture_interface_list(&err, NULL, NULL);
if (if_list != NULL) {
if_entry = if_list;
do {
if_info = (if_info_t *)if_entry->data;
if (strcmp(if_info->name, if_name) == 0) {
if (if_info->friendly_name != NULL) {
/* We have a "friendly name"; return a copy of that
as the description - when we free the interface
list, that'll also free up the strings to which
it refers. */
descr = g_strdup(if_info->friendly_name);
} else if (if_info->vendor_description != NULL) {
/* We have no "friendly name", but we have a vendor
description; return a copy of that - when we free
the interface list, that'll also free up the strings
to which it refers. */
descr = g_strdup(if_info->vendor_description);
}
break;
}
} while ((if_entry = g_list_next(if_entry)) != NULL);
}
free_interface_list(if_list);
if (descr == NULL) {
/* The interface name is all we have, so just return a copy of that. */
descr = g_strdup(if_name);
}
}
}
return descr;
}
GList *
build_capture_combo_list(GList *if_list, gboolean do_hide)
{
GList *combo_list;
GList *if_entry;
if_info_t *if_info;
char *if_string;
gchar *descr;
combo_list = NULL;
if (if_list != NULL) {
/* Scan through the list and build a list of strings to display. */
for (if_entry = if_list; if_entry != NULL;
if_entry = g_list_next(if_entry)) {
if_info = (if_info_t *)if_entry->data;
/* Is this interface hidden and, if so, should we include it
anyway? */
if (!prefs_is_capture_device_hidden(if_info->name) || !do_hide) {
/* It's not hidden, or it is but we should include it in the list. */
/* Do we have a user-supplied description? */
descr = capture_dev_user_descr_find(if_info->name);
if (descr != NULL) {
/* Yes, we have a user-supplied description; use it. */
if_string = ws_strdup_printf("%s: %s", descr, if_info->name);
g_free(descr);
} else {
/* No, we don't have a user-supplied description; did we get
one from the OS or libpcap? */
if (if_info->vendor_description != NULL) {
/* Yes - use it. */
if_string = ws_strdup_printf("%s: %s",
if_info->vendor_description,
if_info->name);
} else {
/* No. */
if_string = g_strdup(if_info->name);
}
}
combo_list = g_list_prepend(combo_list, if_string);
}
}/*for*/
if(combo_list){
combo_list = g_list_reverse(combo_list);
}
}
return combo_list;
}
static void
free_if_string(gpointer data, gpointer user_data _U_)
{
g_free(data);
}
void
free_capture_combo_list(GList *combo_list)
{
if (combo_list != NULL) {
g_list_foreach(combo_list, free_if_string, NULL);
g_list_free(combo_list);
}
}
/*
* Given text that contains an interface name possibly prefixed by an
* interface description, extract the interface name.
*/
const char *
get_if_name(const char *if_text)
{
const char *if_name;
#ifdef _WIN32
/*
* We cannot assume that the interface name doesn't contain a space;
* some names on Windows OT do.
*
* We also can't assume it begins with "\Device\", either, as, on
* Windows OT, WinPcap doesn't put "\Device\" in front of the name.
*
* XXX - we don't support Windows OT any more; do we need to worry
* about this?
*
* As I remember, we can't assume that the interface description
* doesn't contain a colon, either; I think some do.
*
* We can probably assume that the interface *name* doesn't contain
* a colon, however; if any interface name does contain a colon on
* Windows, it'll be time to just get rid of the damn interface
* descriptions in the drop-down list, have just the names in the
* drop-down list, and have a "Browse..." button to browse for interfaces,
* with names, descriptions, IP addresses, blah blah blah available when
* possible.
*
* So we search backwards for a colon. If we don't find it, just
* return the entire string; otherwise, skip the colon and any blanks
* after it, and return that string.
*/
if_name = if_text + strlen(if_text);
for (;;) {
if (if_name == if_text) {
/* We're at the beginning of the string; return it. */
break;
}
if_name--;
if (*if_name == ':') {
/*
* We've found a colon.
* Unfortunately, a colon is used in the string "rpcap://",
* which is used in case of a remote capture.
* So we'll check to make sure the colon isn't followed by "//";
* it'll be followed by a blank if it separates the description
* and the interface name. (We don't wire in "rpcap", in case we
* support other protocols in the same syntax.)
* Unfortunately, another colon can be used in "rpcap://host:port/"
* before port. Check if colon is followed by digit.
*/
if ((strncmp(if_name, "://", 3) != 0) && !g_ascii_isdigit(if_name[1])) {
/*
* OK, we've found a colon followed neither by "//" nor by digit.
* Skip blanks following it.
*/
if_name++;
while (*if_name == ' ')
if_name++;
break;
}
}
/* Keep looking for a colon not followed by "//". */
}
#else
/*
* There's a space between the interface description and name, and
* the interface name shouldn't have a space in it (it doesn't, on
* UNIX systems); look backwards in the string for a space.
*
* (An interface name might, however, contain a colon in it, which
* is why we don't use the colon search on UNIX.)
*/
if_name = strrchr(if_text, ' ');
if (if_name == NULL) {
if_name = if_text;
} else {
if_name++;
}
#endif
return if_name;
}
/*
* Set the active DLT for a device appropriately.
*/
void
set_active_dlt(interface_t *device, int global_default_dlt)
{
GList *list;
gboolean found_active_dlt;
link_row *link;
/*
* If there's a preference for the link-layer header type for
* this interface, use it. If not, use the all-interface
* default; if that's not set on the command line, that will
* be -1, meaning "use per-interface defaults", otherwise
* we'll fail if it's not one of the types the interface
* supports.
*/
if ((device->active_dlt = capture_dev_user_linktype_find(device->name)) == -1) {
device->active_dlt = global_default_dlt;
}
/*
* Is that one of the supported link-layer header types?
* If not, set it to -1, so we'll fall back on the first supported
* link-layer header type.
*/
found_active_dlt = FALSE;
for (list = device->links; list != NULL; list = g_list_next(list)) {
link = (link_row *)(list->data);
if (link->dlt != -1 && link->dlt == device->active_dlt) {
found_active_dlt = TRUE;
break;
}
}
if (!found_active_dlt) {
device->active_dlt = -1;
}
if (device->active_dlt == -1) {
/* Fall back on the first supported DLT, if we have one. */
for (list = device->links; list != NULL; list = g_list_next(list)) {
link = (link_row *)(list->data);
if (link->dlt != -1) {
device->active_dlt = link->dlt;
break;
}
}
}
}
GString *
get_iface_list_string(capture_options *capture_opts, guint32 style)
{
GString *iface_list_string = g_string_new("");
guint i;
/*
* If we have a descriptive name for the interface, show that,
* rather than its raw name. On NT 5.x (2K/XP/Server2K3), the
* interface name is something like "\Device\NPF_{242423..."
* which is pretty useless to the normal user. On other platforms,
* it might be less cryptic, but if a more descriptive name is
* available, we should still use that.
*/
#ifdef _WIN32
if (capture_opts->ifaces->len < 2) {
#else
if (capture_opts->ifaces->len < 4) {
#endif
for (i = 0; i < capture_opts->ifaces->len; i++) {
if (i > 0) {
if (capture_opts->ifaces->len > 2) {
g_string_append_printf(iface_list_string, ",");
}
g_string_append_printf(iface_list_string, " ");
if (i == capture_opts->ifaces->len - 1) {
g_string_append_printf(iface_list_string, "and ");
}
}
interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
if (style & IFLIST_QUOTE_IF_DESCRIPTION)
g_string_append_printf(iface_list_string, "'");
if (interface_opts->display_name == NULL) {
/*
* We don't have a display name; generate one.
*/
if (interface_opts->descr == NULL) {
if (interface_opts->name != NULL)
interface_opts->descr = get_interface_descriptive_name(interface_opts->name);
else
interface_opts->descr = g_strdup("(Unknown)");
}
interface_opts->display_name = g_strdup(interface_opts->descr);
}
g_string_append_printf(iface_list_string, "%s", interface_opts->display_name);
if (style & IFLIST_QUOTE_IF_DESCRIPTION)
g_string_append_printf(iface_list_string, "'");
if (style & IFLIST_SHOW_FILTER) {
if (interface_opts->cfilter != NULL &&
strlen(interface_opts->cfilter) > 0) {
g_string_append_printf(iface_list_string, " (%s)", interface_opts->cfilter);
}
}
}
} else {
g_string_append_printf(iface_list_string, "%u interfaces", capture_opts->ifaces->len);
}
return iface_list_string;
}
#endif /* HAVE_LIBPCAP */ |
C/C++ | wireshark/ui/capture_ui_utils.h | /** @file
*
* Declarations of utilities for capture user interfaces
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __CAPTURE_UI_UTILS_H__
#define __CAPTURE_UI_UTILS_H__
#include "capture_opts.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @file
* GList of available capture interfaces.
*/
/**
* Find user-specified capture device description that matches interface
* name, if any.
*
* @param if_name The name of the interface.
*
* @return The device description (must be g_free'd later) or NULL
* if not found.
*/
char *capture_dev_user_descr_find(const gchar *if_name);
/**
* Find user-specified link-layer header type that matches interface
* name, if any.
*
* @param if_name The name of the interface.
*
* @return The link-layer header type (a DLT_) or -1 if not found.
*/
gint capture_dev_user_linktype_find(const gchar *if_name);
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
/**
* Find user-specified buffer size that matches interface
* name, if any.
*
* @param if_name The name of the interface.
*
* @return The buffer size or -1 if not found.
*/
gint capture_dev_user_buffersize_find(const gchar *if_name);
#endif
/**
* Find user-specified snap length that matches interface
* name, if any.
*
* @param if_name The name of the interface.
* @param hassnap Pointer to a variable to be set to TRUE if the
* interface should be given a snap length or FALSE if it shouldn't
* be given a snap length.
* @param snaplen Pointer to a variable to be set to the snap length
* if the interface should be given a snap length or the maximum
* snap length if it shouldn't be given a snap length.
*
* @return TRUE if found or FALSE if not found.
*/
gboolean capture_dev_user_snaplen_find(const gchar *if_name, gboolean *hassnap, int *snaplen);
/**
* Find user-specified promiscuous mode that matches interface
* name, if any.
*
* @param if_name The name of the interface.
* @param pmode Pointer to a variable to be set to TRUE if promiscuous
* mode should be used and FALSE if it shouldn't be used.
*
* @return TRUE if found or FALSE if not found.
*/
gboolean capture_dev_user_pmode_find(const gchar *if_name, gboolean *pmode);
/**
* Find user-specified capture filter that matches interface
* name, if any.
*
* This is deprecated and should not be used in new code.
*
* @param if_name The name of the interface.
*
* @return The capture filter (must be g_free'd later) or NULL if not found.
*/
gchar* capture_dev_user_cfilter_find(const gchar *if_name);
/** Return as descriptive a name for an interface as we can get.
* If the user has specified a comment, use that. Otherwise,
* if capture_interface_list() supplies a description, use that,
* otherwise use the interface name.
*
* @param if_name The name of the interface.
*
* @return The descriptive name (must be g_free'd later)
*/
char *get_interface_descriptive_name(const char *if_name);
/** Build the GList of available capture interfaces.
*
* @param if_list An interface list from capture_interface_list().
* @param do_hide Hide the "hidden" interfaces.
*
* @return A list of if_info_t structs (use free_capture_combo_list() later).
*/
GList *build_capture_combo_list(GList *if_list, gboolean do_hide);
/** Free the GList from build_capture_combo_list().
*
* @param combo_list the interface list from build_capture_combo_list()
*/
void free_capture_combo_list(GList *combo_list);
/** Given text that contains an interface name possibly prefixed by an
* interface description, extract the interface name.
*
* @param if_text A string containing the interface description + name.
* This is usually the data from one of the list elements returned by
* build_capture_combo_list().
*
* @return The raw interface name, without description (must NOT be g_free'd later)
*/
const char *get_if_name(const char *if_text);
/** Set the active DLT for a device appropriately.
*
* @param device the device on which to set the active DLT
* @param global_default_dlt the global default DLT
*/
extern void set_active_dlt(interface_t *device, int global_default_dlt);
/** Get a descriptive string for a list of interfaces.
*
* @param capture_opts The capture_options structure that contains the interfaces
* @param style flags to indicate the style of string to use:
*
* IFLIST_QUOTE_IF_DESCRIPTION: put the interface descriptive string in
* single quotes
*
* IFLIST_SHOW_FILTER: include the capture filters in the string
*
* @return A GString set to the descriptive string
*/
#define IFLIST_QUOTE_IF_DESCRIPTION 0x00000001
#define IFLIST_SHOW_FILTER 0x00000002
extern GString *get_iface_list_string(capture_options *capture_opts, guint32 style);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __CAPTURE_UI_UTILS_H__ */ |
Text | wireshark/ui/CMakeLists.txt | # CMakeLists.txt
#
# Wireshark - Network traffic analyzer
# By Gerald Combs <[email protected]>
# Copyright 1998 Gerald Combs
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
set(NONGENERATED_UI_SRC
alert_box.c
capture.c
capture_ui_utils.c
commandline.c
decode_as_utils.c
dissect_opts.c
export_pdu_ui_utils.c
help_url.c
failure_message.c
file_dialog.c
firewall_rules.c
iface_toolbar.c
iface_lists.c
io_graph_item.c
language.c
mcast_stream.c
packet_list_utils.c
packet_range.c
persfilepath_opt.c
preference_utils.c
profile.c
proto_hier_stats.c
recent.c
rtp_media.c
rtp_stream.c
rtp_stream_id.c
service_response_time.c
software_update.c
ssl_key_export.c
tap_export_pdu.c
tap-iax2-analysis.c
tap-rtp-analysis.c
tap-rtp-common.c
tap-sctp-analysis.c
tap-rlc-graph.c
tap-tcp-stream.c
text_import.c
text_import_regex.c
time_shift.c
util.c
voip_calls.c
)
# Enables visibility in IDEs
file(GLOB EXTRA_UI_HEADERS
rtp_media.h
rtp_stream.h
rtp_stream_id.h
tap-iax2-analysis.h
tap-rtp-analysis.h
)
set(UI_SRC ${NONGENERATED_UI_SRC})
add_lex_files(LEX_FILES UI_SRC
text_import_scanner.l
)
set_source_files_properties(
${NONGENERATED_UI_SRC}
PROPERTIES
COMPILE_FLAGS "${WERROR_COMMON_FLAGS}"
)
add_library(ui STATIC ${UI_SRC})
target_link_libraries(ui
PRIVATE
wsutil
wiretap
)
target_include_directories(ui
SYSTEM PRIVATE
${PCAP_INCLUDE_DIRS}
${WINSPARKLE_INCLUDE_DIRS}
)
add_library(summary STATIC summary.c)
target_link_libraries(summary
PRIVATE
wiretap
epan
wsutil
${GCRYPT_LIBRARIES}
)
target_include_directories(summary
SYSTEM PRIVATE
${GCRYPT_INCLUDE_DIRS}
)
set_target_properties(ui summary PROPERTIES
LINK_FLAGS "${WS_LINK_FLAGS}"
FOLDER "UI"
)
if(MSVC)
set_target_properties(ui summary PROPERTIES
LINK_FLAGS_DEBUG "${WS_MSVC_DEBUG_LINK_FLAGS}"
)
endif()
CHECKAPI(
NAME
ui-base
SWITCHES
SOURCES
${NONGENERATED_UI_SRC}
# Flex files not included due to use of malloc, free etc.
)
CHECKAPI(
NAME
ui-todo
SWITCHES
-M
SOURCES
${NONGENERATED_UI_SRC}
# Flex files not included due to use of malloc, free etc.
)
#
# Editor modelines - https://www.wireshark.org/tools/modelines.html
#
# Local variables:
# c-basic-offset: 8
# tab-width: 8
# indent-tabs-mode: t
# End:
#
# vi: set shiftwidth=8 tabstop=8 noexpandtab:
# :indentSize=8:tabSize=8:noTabs=false:
# |
C | wireshark/ui/commandline.c | /* commandline.c
* Common command line handling between GUIs
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ws_exit_codes.h>
#include <wsutil/ws_getopt.h>
#include <wsutil/version_info.h>
#include <wsutil/clopts_common.h>
#include <wsutil/cmdarg_err.h>
#include <wsutil/filesystem.h>
#include <wsutil/ws_assert.h>
#ifdef _WIN32
#include <wsutil/console_win32.h>
#endif
#include <epan/ex-opt.h>
#include <epan/packet.h>
#include <epan/proto.h>
#include <epan/prefs.h>
#include <epan/prefs-int.h>
#include <epan/stat_tap_ui.h>
#include "capture_opts.h"
#include "persfilepath_opt.h"
#include "preference_utils.h"
#include "recent.h"
#include "decode_as_utils.h"
#include "../file.h"
#include "ui/dissect_opts.h"
#include "ui/commandline.h"
commandline_param_info_t global_commandline_info;
capture_options global_capture_opts;
void
commandline_print_usage(gboolean for_help_option) {
FILE *output;
#ifdef _WIN32
create_console();
#endif
if (for_help_option) {
show_help_header("Interactively dump and analyze network traffic.");
output = stdout;
} else {
output = stderr;
}
fprintf(output, "\n");
fprintf(output, "Usage: wireshark [options] ... [ <infile> ]\n");
fprintf(output, "\n");
#ifdef HAVE_LIBPCAP
fprintf(output, "Capture interface:\n");
fprintf(output, " -i <interface>, --interface <interface>\n");
fprintf(output, " name or idx of interface (def: first non-loopback)\n");
fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
#ifdef HAVE_PCAP_CREATE
fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
#else
fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
#endif
fprintf(output, " -p, --no-promiscuous-mode\n");
fprintf(output, " don't capture in promiscuous mode\n");
#ifdef HAVE_PCAP_CREATE
fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
#endif
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
fprintf(output, " size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
#endif
fprintf(output, " -y <link type>, --linktype <link type>\n");
fprintf(output, " link layer type (def: first appropriate)\n");
fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
fprintf(output, " -L, --list-data-link-types\n");
fprintf(output, " print list of link-layer types of iface and exit\n");
fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
fprintf(output, "\n");
fprintf(output, "Capture display:\n");
fprintf(output, " -k start capturing immediately (def: do nothing)\n");
fprintf(output, " -S update packet display when new packets are captured\n");
fprintf(output, " --update-interval interval between updates with new packets (def: %dms)\n", DEFAULT_UPDATE_INTERVAL);
fprintf(output, " -l turn on automatic scrolling while -S is in use\n");
fprintf(output, "Capture stop conditions:\n");
fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
fprintf(output, " duration:NUM - stop after NUM seconds\n");
fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
fprintf(output, " files:NUM - stop after NUM files\n");
fprintf(output, " packets:NUM - stop after NUM packets\n");
/*fprintf(output, "\n");*/
fprintf(output, "Capture output:\n");
fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
fprintf(output, " packets:NUM - switch to next file after NUM packets\n");
fprintf(output, " interval:NUM - switch to next file when the time is\n");
fprintf(output, " an exact multiple of NUM secs\n");
#endif /* HAVE_LIBPCAP */
#ifdef HAVE_PCAP_REMOTE
fprintf(output, "RPCAP options:\n");
fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
#endif
/*fprintf(output, "\n");*/
fprintf(output, "Input file:\n");
fprintf(output, " -r <infile>, --read-file <infile>\n");
fprintf(output, " set the filename to read from (no pipes or stdin!)\n");
fprintf(output, "\n");
fprintf(output, "Processing:\n");
fprintf(output, " -R <read filter>, --read-filter <read filter>\n");
fprintf(output, " packet filter in Wireshark display filter syntax\n");
fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtdv\"\n");
fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
fprintf(output, " \"Decode As\", see the man page for details\n");
fprintf(output, " Example: tcp.port==8888,http\n");
fprintf(output, " --enable-protocol <proto_name>\n");
fprintf(output, " enable dissection of proto_name\n");
fprintf(output, " --disable-protocol <proto_name>\n");
fprintf(output, " disable dissection of proto_name\n");
fprintf(output, " --only-protocols <proto_name>\n");
fprintf(output, " Only enable dissection of these protocols, comma\n");
fprintf(output, " separated. Disable everything else\n");
fprintf(output, " --disable-all-protocols\n");
fprintf(output, " Disable dissection of all protocols\n");
fprintf(output, " --enable-heuristic <short_name>\n");
fprintf(output, " enable dissection of heuristic protocol\n");
fprintf(output, " --disable-heuristic <short_name>\n");
fprintf(output, " disable dissection of heuristic protocol\n");
fprintf(output, "\n");
fprintf(output, "User interface:\n");
fprintf(output, " -C <config profile> start with specified configuration profile\n");
fprintf(output, " -H hide the capture info dialog during packet capture\n");
fprintf(output, " -Y <display filter>, --display-filter <display filter>\n");
fprintf(output, " start with the given display filter\n");
fprintf(output, " -g <packet number> go to specified packet number after \"-r\"\n");
fprintf(output, " -J <jump filter> jump to the first packet matching the (display)\n");
fprintf(output, " filter\n");
fprintf(output, " -j search backwards for a matching packet after \"-J\"\n");
fprintf(output, " -t (a|ad|adoy|d|dd|e|r|u|ud|udoy)[.[N]]|.[N]\n");
fprintf(output, " format of time stamps (def: r: rel. to first)\n");
fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
fprintf(output, " -X <key>:<value> eXtension options, see man page for details\n");
fprintf(output, " -z <statistics> show various statistics, see man page for details\n");
fprintf(output, "\n");
fprintf(output, "Output:\n");
fprintf(output, " -w <outfile|-> set the output filename (or '-' for stdout)\n");
#ifdef HAVE_LIBPCAP
fprintf(output, " --capture-comment <comment>\n");
fprintf(output, " add a capture file comment, if supported\n");
#endif
fprintf(output, " --temp-dir <directory> write temporary files to this directory\n");
fprintf(output, " (default: %s)\n", g_get_tmp_dir());
fprintf(output, "\n");
ws_log_print_usage(output);
fprintf(output, "\n");
fprintf(output, "Miscellaneous:\n");
fprintf(output, " -h, --help display this help and exit\n");
fprintf(output, " -v, --version display version info and exit\n");
fprintf(output, " -P <key>:<path> persconf:path - personal configuration files\n");
fprintf(output, " persdata:path - personal data files\n");
fprintf(output, " -o <name>:<value> ... override preference or recent setting\n");
fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
#ifndef _WIN32
fprintf(output, " --display <X display> X display to use\n");
#endif
fprintf(output, " --fullscreen start Wireshark in full screen\n");
#ifdef _WIN32
destroy_console();
#endif
}
#define LONGOPT_FULL_SCREEN LONGOPT_BASE_GUI+1
#define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_GUI+2
#define OPTSTRING OPTSTRING_CAPTURE_COMMON OPTSTRING_DISSECT_COMMON "C:g:HhjJ:klm:o:P:r:R:Svw:X:Y:z:"
static const struct ws_option long_options[] = {
{"help", ws_no_argument, NULL, 'h'},
{"read-file", ws_required_argument, NULL, 'r' },
{"read-filter", ws_required_argument, NULL, 'R' },
{"display-filter", ws_required_argument, NULL, 'Y' },
{"version", ws_no_argument, NULL, 'v'},
{"fullscreen", ws_no_argument, NULL, LONGOPT_FULL_SCREEN },
{"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
LONGOPT_CAPTURE_COMMON
LONGOPT_DISSECT_COMMON
{0, 0, 0, 0 }
};
static const char optstring[] = OPTSTRING;
#ifndef HAVE_LIBPCAP
static void print_no_capture_support_error(void)
{
cmdarg_err("This version of Wireshark was not built with support for capturing packets.");
}
#endif
void commandline_early_options(int argc, char *argv[])
{
int opt;
#ifdef HAVE_LIBPCAP
int err;
GList *if_list;
gchar *err_str;
#else
gboolean capture_option_specified;
#endif
/*
* In order to have the -X opts assigned before the wslua machine starts
* we need to call getopt_long before epan_init() gets called.
*
* In addition, we process "console only" parameters (ones where we
* send output to the console and exit) here, so we don't start GUI
* if we're only showing command-line help or version information.
*
* XXX - this pre-scan is done before we start GUI, so we haven't
* run "GUI init function" on the arguments. That means that GUI-specific
* arguments have not been removed from the argument list; those arguments
* begin with "--", and will be treated as an error by getopt_long().
*
* We thus ignore errors - *and* set "ws_opterr" to 0 to suppress the
* error messages.
*
* In order to handle, for example, -o options, we also need to call it
* *after* epan_init() gets called, so that the dissectors have had a
* chance to register their preferences, so we have another getopt_long()
* call later.
*
* XXX - can we do this all with one getopt_long() call, saving the
* arguments we can't handle until after initializing libwireshark,
* and then process them after initializing libwireshark?
*
* Note that we don't want to initialize libwireshark until after the
* GUI is up, as that can take a while, and we want a window of some
* sort up to show progress while that's happening.
*/
ws_opterr = 0;
#ifndef HAVE_LIBPCAP
capture_option_specified = FALSE;
#endif
while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
switch (opt) {
case 'C': /* Configuration Profile */
if (profile_exists (ws_optarg, FALSE)) {
set_profile_name (ws_optarg);
} else if (profile_exists (ws_optarg, TRUE)) {
char *pf_dir_path, *pf_dir_path2, *pf_filename;
/* Copy from global profile */
if (create_persconffile_profile(ws_optarg, &pf_dir_path) == -1) {
cmdarg_err("Can't create directory\n\"%s\":\n%s.",
pf_dir_path, g_strerror(errno));
g_free(pf_dir_path);
exit(WS_EXIT_INVALID_FILE);
}
if (copy_persconffile_profile(ws_optarg, ws_optarg, TRUE, &pf_filename,
&pf_dir_path, &pf_dir_path2) == -1) {
cmdarg_err("Can't copy file \"%s\" in directory\n\"%s\" to\n\"%s\":\n%s.",
pf_filename, pf_dir_path2, pf_dir_path, g_strerror(errno));
g_free(pf_filename);
g_free(pf_dir_path);
g_free(pf_dir_path2);
exit(WS_EXIT_INVALID_FILE);
}
set_profile_name (ws_optarg);
} else {
cmdarg_err("Configuration Profile \"%s\" does not exist", ws_optarg);
exit(1);
}
break;
case 'D': /* Print a list of capture devices and exit */
#ifdef HAVE_LIBPCAP
if_list = capture_interface_list(&err, &err_str, NULL);
if (if_list == NULL) {
if (err == 0)
cmdarg_err("There are no interfaces on which a capture can be done");
else {
cmdarg_err("%s", err_str);
g_free(err_str);
}
exit(WS_EXIT_INVALID_INTERFACE);
}
#ifdef _WIN32
create_console();
#endif /* _WIN32 */
capture_opts_print_interfaces(if_list);
free_interface_list(if_list);
#ifdef _WIN32
destroy_console();
#endif /* _WIN32 */
exit(EXIT_SUCCESS);
#else /* HAVE_LIBPCAP */
capture_option_specified = TRUE;
#endif /* HAVE_LIBPCAP */
break;
case 'h': /* Print help and exit */
commandline_print_usage(TRUE);
exit(EXIT_SUCCESS);
break;
#ifdef _WIN32
case 'i':
if (strcmp(ws_optarg, "-") == 0)
set_stdin_capture(TRUE);
break;
#endif
case 'P': /* Personal file directory path settings - change these before the Preferences and alike are processed */
if (!persfilepath_opt(opt, ws_optarg)) {
cmdarg_err("-P flag \"%s\" failed (hint: is it quoted and existing?)", ws_optarg);
exit(EXIT_SUCCESS);
}
break;
case 'v': /* Show version and exit */
#ifdef _WIN32
create_console();
#endif
show_version();
#ifdef _WIN32
destroy_console();
#endif
exit(EXIT_SUCCESS);
break;
case 'X':
/*
* Extension command line options have to be processed before
* we call epan_init() as they are supposed to be used by dissectors
* or taps very early in the registration process.
*/
ex_opt_add(ws_optarg);
break;
case '?': /* Ignore errors - the "real" scan will catch them. */
break;
}
}
#ifndef HAVE_LUA
if (ex_opt_count("lua_script") > 0) {
cmdarg_err("This version of Wireshark was not built with support for Lua scripting.");
exit(1);
}
#endif
#ifndef HAVE_LIBPCAP
if (capture_option_specified) {
print_no_capture_support_error();
commandline_print_usage(FALSE);
exit(EXIT_SUCCESS);
}
#endif
}
void commandline_other_options(int argc, char *argv[], gboolean opt_reset)
{
int opt;
gboolean arg_error = FALSE;
#ifdef HAVE_LIBPCAP
const char *list_option_supplied = NULL;
int status;
#else
gboolean capture_option_specified;
#endif
/*
* To reset the options parser, set ws_optreset to 1 and set ws_optind to 1.
*
* Also reset ws_opterr to 1, so that error messages are printed by
* getopt_long().
*
* XXX - if we want to control all the command-line option errors, so
* that we can display them where we choose (e.g., in a window), we'd
* want to leave ws_opterr as 0, and produce our own messages using ws_optopt.
* We'd have to check the value of ws_optopt to see if it's a valid option
* letter, in which case *presumably* the error is "this option requires
* an argument but none was specified", or not a valid option letter,
* in which case *presumably* the error is "this option isn't valid".
* Some versions of getopt() let you supply a option string beginning
* with ':', which means that getopt() will return ':' rather than '?'
* for "this option requires an argument but none was specified", but
* not all do. But we're now using getopt_long() - what does it do?
*/
if (opt_reset) {
ws_optreset = 1;
ws_optind = 1;
ws_opterr = 1;
}
/* Initialize with default values */
global_commandline_info.jump_backwards = SD_FORWARD;
global_commandline_info.go_to_packet = 0;
global_commandline_info.jfilter = NULL;
global_commandline_info.cf_name = NULL;
global_commandline_info.rfilter = NULL;
global_commandline_info.dfilter = NULL;
#ifdef HAVE_LIBPCAP
global_commandline_info.start_capture = FALSE;
global_commandline_info.list_link_layer_types = FALSE;
global_commandline_info.list_timestamp_types = FALSE;
global_commandline_info.quit_after_cap = getenv("WIRESHARK_QUIT_AFTER_CAPTURE") ? TRUE : FALSE;
global_commandline_info.capture_comments = NULL;
#endif
global_commandline_info.full_screen = FALSE;
global_commandline_info.user_opts = NULL;
while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
switch (opt) {
/*** capture option specific ***/
case 'a': /* autostop criteria */
case 'b': /* Ringbuffer option */
case 'c': /* Capture xxx packets */
case 'f': /* capture filter */
case 'H': /* Hide capture info dialog box */
case 'p': /* Don't capture in promiscuous mode */
case 'i': /* Use interface x */
case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
case LONGOPT_CAPTURE_TMPDIR: /* capture temp directory */
case LONGOPT_UPDATE_INTERVAL: /* sync pipe update interval */
#ifdef HAVE_PCAP_CREATE
case 'I': /* Capture in monitor mode, if available */
#endif
#ifdef HAVE_PCAP_REMOTE
case 'A': /* Authentication */
#endif
case 's': /* Set the snapshot (capture) length */
case 'S': /* "Sync" mode: used for following file ala tail -f */
case 'w': /* Write to capture file xxx */
case 'y': /* Set the pcap data link type */
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
case 'B': /* Buffer size */
#endif
#ifdef HAVE_LIBPCAP
status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
if(status != 0) {
exit_application(status);
}
#else
capture_option_specified = TRUE;
arg_error = TRUE;
#endif
break;
/*** all non capture option specific ***/
case 'C':
/* Configuration profile settings were already processed just ignore them this time*/
break;
case 'j': /* Search backwards for a matching packet from filter in option J */
global_commandline_info.jump_backwards = SD_BACKWARD;
break;
case 'g': /* Go to packet with the given packet number */
global_commandline_info.go_to_packet = get_nonzero_guint32(ws_optarg, "go to packet");
break;
case 'J': /* Jump to the first packet which matches the filter criteria */
global_commandline_info.jfilter = ws_optarg;
break;
case 'k': /* Start capture immediately */
#ifdef HAVE_LIBPCAP
global_commandline_info.start_capture = TRUE;
#else
capture_option_specified = TRUE;
arg_error = TRUE;
#endif
break;
case 'l': /* Automatic scrolling in live capture mode */
#ifdef HAVE_LIBPCAP
recent.capture_auto_scroll = TRUE;
#else
capture_option_specified = TRUE;
arg_error = TRUE;
#endif
break;
case 'L': /* Print list of link-layer types and exit */
#ifdef HAVE_LIBPCAP
global_commandline_info.list_link_layer_types = TRUE;
list_option_supplied = "-L";
#else
capture_option_specified = TRUE;
arg_error = TRUE;
#endif
break;
case LONGOPT_LIST_TSTAMP_TYPES:
#ifdef HAVE_LIBPCAP
global_commandline_info.list_timestamp_types = TRUE;
list_option_supplied = "--list-time-stamp-types";
#else
capture_option_specified = TRUE;
arg_error = TRUE;
#endif
break;
case 'o': /* Override preference from command line */
{
char *errmsg = NULL;
switch (prefs_set_pref(ws_optarg, &errmsg)) {
case PREFS_SET_OK:
global_commandline_info.user_opts =
g_slist_prepend(global_commandline_info.user_opts,
g_strdup(ws_optarg));
break;
case PREFS_SET_SYNTAX_ERR:
cmdarg_err("Invalid -o flag \"%s\"%s%s", ws_optarg,
errmsg ? ": " : "", errmsg ? errmsg : "");
g_free(errmsg);
exit_application(1);
break;
case PREFS_SET_NO_SUCH_PREF:
/* not a preference, might be a recent setting */
switch (recent_set_arg(ws_optarg)) {
case PREFS_SET_OK:
break;
case PREFS_SET_SYNTAX_ERR:
/* shouldn't happen, checked already above */
cmdarg_err("Invalid -o flag \"%s\"", ws_optarg);
exit_application(1);
break;
case PREFS_SET_NO_SUCH_PREF:
case PREFS_SET_OBSOLETE:
cmdarg_err("-o flag \"%s\" specifies unknown preference/recent value",
ws_optarg);
exit_application(1);
break;
default:
ws_assert_not_reached();
}
break;
case PREFS_SET_OBSOLETE:
cmdarg_err("-o flag \"%s\" specifies obsolete preference",
ws_optarg);
exit_application(1);
break;
default:
ws_assert_not_reached();
}
break;
}
case 'P':
/* Path settings were already processed just ignore them this time*/
break;
case 'r': /* Read capture file xxx */
/* We may set "last_open_dir" to "cf_name", and if we change
"last_open_dir" later, we free the old value, so we have to
set "cf_name" to something that's been allocated. */
global_commandline_info.cf_name = g_strdup(ws_optarg);
break;
case 'R': /* Read file filter */
global_commandline_info.rfilter = ws_optarg;
break;
case 'X':
/* ext ops were already processed just ignore them this time*/
break;
case 'Y':
global_commandline_info.dfilter = ws_optarg;
break;
case 'z':
/* We won't call the init function for the stat this soon
as it would disallow MATE's fields (which are registered
by the preferences set callback) from being used as
part of a tap filter. Instead, we just add the argument
to a list of stat arguments. */
if (strcmp("help", ws_optarg) == 0) {
fprintf(stderr, "wireshark: The available statistics for the \"-z\" option are:\n");
list_stat_cmd_args();
exit_application(0);
}
if (!process_stat_cmd_arg(ws_optarg)) {
cmdarg_err("Invalid -z argument.");
cmdarg_err_cont(" -z argument must be one of :");
list_stat_cmd_args();
exit_application(1);
}
break;
case 'd': /* Decode as rule */
case 'K': /* Kerberos keytab file */
case 'n': /* No name resolution */
case 'N': /* Select what types of addresses/port #s to resolve */
case 't': /* time stamp type */
case 'u': /* Seconds type */
case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
case LONGOPT_ONLY_PROTOCOLS: /* enable dissection of these comma separated protocols only */
case LONGOPT_DISABLE_ALL_PROTOCOLS: /* disable dissection of all protocols */
if (!dissect_opts_handle_opt(opt, ws_optarg))
exit_application(1);
break;
case LONGOPT_FULL_SCREEN:
global_commandline_info.full_screen = TRUE;
break;
#ifdef HAVE_LIBPCAP
case LONGOPT_CAPTURE_COMMENT: /* capture comment */
if (global_commandline_info.capture_comments == NULL) {
global_commandline_info.capture_comments = g_ptr_array_new_with_free_func(g_free);
}
g_ptr_array_add(global_commandline_info.capture_comments, g_strdup(ws_optarg));
#else
capture_option_specified = TRUE;
arg_error = TRUE;
#endif
break;
default:
case '?': /* Bad flag - print usage message */
arg_error = TRUE;
break;
}
}
/* Since we prepended each option when processing `-o`, reverse the list
* in case the order of options becomes meaningful.
*/
global_commandline_info.user_opts = g_slist_reverse(global_commandline_info.user_opts);
if (!arg_error) {
argc -= ws_optind;
argv += ws_optind;
if (argc >= 1) {
if (global_commandline_info.cf_name != NULL) {
/*
* Input file name specified with "-r" *and* specified as a regular
* command-line argument.
*/
cmdarg_err("File name specified both with -r and regular argument");
arg_error = TRUE;
} else {
/*
* Input file name not specified with "-r", and a command-line argument
* was specified; treat it as the input file name.
*
* Yes, this is different from tshark, where non-flag command-line
* arguments are a filter, but this works better on GUI desktops
* where a command can be specified to be run to open a particular
* file - yes, you could have "-r" as the last part of the command,
* but that's a bit ugly.
*/
global_commandline_info.cf_name = g_strdup(argv[0]);
}
argc--;
argv++;
}
if (argc != 0) {
/*
* Extra command line arguments were specified; complain.
*/
cmdarg_err("Invalid argument: %s", argv[0]);
arg_error = TRUE;
}
}
if (arg_error) {
#ifndef HAVE_LIBPCAP
if (capture_option_specified) {
print_no_capture_support_error();
}
#endif
commandline_print_usage(FALSE);
exit_application(1);
}
#ifdef HAVE_LIBPCAP
if (global_commandline_info.start_capture && list_option_supplied) {
/* Specifying *both* is bogus. */
cmdarg_err("You can't specify both %s and a live capture.", list_option_supplied);
exit_application(1);
}
if (list_option_supplied) {
/* We're supposed to list the link-layer types for an interface;
did the user also specify a capture file to be read? */
if (global_commandline_info.cf_name) {
/* Yes - that's bogus. */
cmdarg_err("You can't specify %s and a capture file to be read.", list_option_supplied);
exit_application(1);
}
/* No - did they specify a ring buffer option? */
if (global_capture_opts.multi_files_on) {
cmdarg_err("Ring buffer requested, but a capture isn't being done.");
exit_application(1);
}
} else {
/* We're supposed to do a live capture; did the user also specify
a capture file to be read? */
if (global_commandline_info.start_capture && global_commandline_info.cf_name) {
/* Yes - that's bogus. */
cmdarg_err("You can't specify both a live capture and a capture file to be read.");
exit_application(1);
}
/* No - was the ring buffer option specified and, if so, does it make
sense? */
if (global_capture_opts.multi_files_on) {
/* Ring buffer works only under certain conditions:
a) ring buffer does not work with temporary files;
b) real_time_mode and multi_files_on are mutually exclusive -
real_time_mode takes precedence;
c) it makes no sense to enable the ring buffer if the maximum
file size is set to "infinite". */
if (global_capture_opts.save_file == NULL) {
cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
global_capture_opts.multi_files_on = FALSE;
}
if (!global_capture_opts.has_autostop_filesize &&
!global_capture_opts.has_file_duration &&
!global_capture_opts.has_file_interval &&
!global_capture_opts.has_file_packets) {
cmdarg_err("Ring buffer requested, but no maximum capture file size, duration, interval or packets were specified.");
/* XXX - this must be redesigned as the conditions changed */
}
}
}
#endif
}
/* Local function used by commandline_options_drop */
static int cl_find_custom(gconstpointer elem_data, gconstpointer search_data) {
return memcmp(elem_data, search_data, strlen((char *)search_data));
}
/* Drop any options the user specified on the command line with `-o`
* that have the given module and preference names
*/
void commandline_options_drop(const char *module_name, const char *pref_name) {
GSList *elem;
char *opt_prefix;
if (global_commandline_info.user_opts == NULL) return;
opt_prefix = ws_strdup_printf("%s.%s:", module_name, pref_name);
while (NULL != (elem = g_slist_find_custom(global_commandline_info.user_opts,
(gconstpointer)opt_prefix, cl_find_custom))) {
global_commandline_info.user_opts =
g_slist_remove_link(global_commandline_info.user_opts, elem);
g_free(elem->data);
g_slist_free_1(elem);
}
g_free(opt_prefix);
}
/* Reapply any options the user specified on the command line with `-o`
* Called in the Qt UI when reloading Lua plugins
* For https://gitlab.com/wireshark/wireshark/-/issues/12331
*/
void commandline_options_reapply(void) {
char *errmsg = NULL;
GSList *entry = NULL;
for (entry = global_commandline_info.user_opts; entry != NULL; entry = g_slist_next(entry)) {
/* Although these options are from the user-supplied command line,
* they were checked for validity before we added them to user_opts,
* so we don't check them again here. In the worst case, a pref is
* specified for a lua plugin which has been edited after Wireshark
* started and has had that pref removed; not worth exiting over.
* See #12331
*/
prefs_set_pref((char *)entry->data, &errmsg);
if (errmsg != NULL) {
g_free(errmsg);
errmsg = NULL;
}
}
}
/* Free memory used to hold user-specified command line options */
void commandline_options_free(void) {
g_slist_free_full(global_commandline_info.user_opts, g_free);
} |
C/C++ | wireshark/ui/commandline.h | /** @file
*
* Common command line handling between GUIs
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __COMMANDLINE_H__
#define __COMMANDLINE_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
extern void commandline_print_usage(gboolean for_help_option);
extern void commandline_early_options(int argc, char *argv[]);
/* Command-line options that don't have direct API calls to handle the data */
typedef struct commandline_param_info
{
#ifdef HAVE_LIBPCAP
gboolean list_link_layer_types;
gboolean list_timestamp_types;
gboolean start_capture;
gboolean quit_after_cap;
/*
* We currently don't support this as a way to add file comments
* to an existing capture file in Wireshark; we only support it
* for adding comments to live captures.
*/
GPtrArray *capture_comments;
#endif
e_prefs *prefs_p;
search_direction jump_backwards;
guint32 go_to_packet;
gchar* jfilter;
gchar* cf_name;
gchar* rfilter;
gchar* dfilter;
gboolean full_screen;
GSList *user_opts;
} commandline_param_info_t;
extern void commandline_other_options(int argc, char *argv[], gboolean opt_reset);
extern void commandline_options_drop(const char *module_name, const char *pref_name);
extern void commandline_options_reapply(void);
extern void commandline_options_free(void);
extern commandline_param_info_t global_commandline_info;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __COMMANDLINE_H__ */ |
C | wireshark/ui/decode_as_utils.c | /* decode_as_utils.c
*
* Routines to modify dissector tables on the fly.
*
* By David Hampton <[email protected]>
* Copyright 2001 David Hampton
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <stdlib.h>
#include "epan/decode_as.h"
#include "epan/packet.h"
#include "epan/prefs.h"
#include "epan/prefs-int.h"
#include "ui/decode_as_utils.h"
#include "ui/simple_dialog.h"
#include "wsutil/file_util.h"
#include "wsutil/filesystem.h"
#include <wsutil/ws_assert.h>
#include "wsutil/cmdarg_err.h"
/* XXX - We might want to switch this to a UAT */
static const char* prev_display_dissector_name = NULL;
/*
* For a dissector table, print on the stream described by output,
* its short name (which is what's used in the "-d" option) and its
* descriptive name.
*/
static void
display_dissector_table_names(const char *table_name, const char *ui_name,
gpointer output)
{
if ((prev_display_dissector_name == NULL) ||
(strcmp(prev_display_dissector_name, table_name) != 0)) {
fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
prev_display_dissector_name = table_name;
}
}
/*
* For a dissector handle, print on the stream described by output,
* the filter name (which is what's used in the "-d" option) and the full
* name for the protocol that corresponds to this handle.
*/
static void
display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
{
int proto_id;
const gchar *proto_filter_name;
const gchar *proto_ui_name;
proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
if (proto_id != -1) {
proto_filter_name = proto_get_protocol_filter_name(proto_id);
proto_ui_name = proto_get_protocol_name(proto_id);
ws_assert(proto_filter_name != NULL);
ws_assert(proto_ui_name != NULL);
if ((prev_display_dissector_name == NULL) ||
(strcmp(prev_display_dissector_name, proto_filter_name) != 0)) {
fprintf((FILE *)output, "\t%s (%s)\n",
proto_filter_name,
proto_ui_name);
prev_display_dissector_name = proto_filter_name;
}
}
}
/*
* Allow dissector key names to be sorted alphabetically
*/
static gint
compare_dissector_key_name(gconstpointer dissector_a, gconstpointer dissector_b)
{
return strcmp((const char*)dissector_a, (const char*)dissector_b);
}
/*
* Print all layer type names supported.
* We send the output to the stream described by the handle output.
*/
static void
fprint_all_layer_types(FILE *output)
{
prev_display_dissector_name = NULL;
dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output, (GCompareFunc)compare_dissector_key_name);
}
/*
* Print all protocol names supported for a specific layer type.
* table_name contains the layer type name in which the search is performed.
* We send the output to the stream described by the handle output.
*/
static void
fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
{
prev_display_dissector_name = NULL;
dissector_table_foreach_handle(table_name,
display_dissector_names,
(gpointer)output);
}
/*
* The protocol_name_search structure is used by find_protocol_name_func()
* to pass parameters and store results
*/
struct protocol_name_search{
const char *searched_name; /* Protocol filter name we are looking for */
dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
guint nb_match; /* How many dissectors matched searched_name */
};
typedef struct protocol_name_search *protocol_name_search_t;
/*
* This function parses all dissectors associated with a table to find the
* one whose protocol has the specified filter name. It is called
* as a reference function in a call to dissector_table_foreach_handle.
* The name we are looking for, as well as the results, are stored in the
* protocol_name_search struct pointed to by user_data.
* If called using dissector_table_foreach_handle, we actually parse the
* whole list of dissectors.
*/
static void
find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
{
int proto_id;
const gchar *protocol_filter_name;
protocol_name_search_t search_info;
ws_assert(handle);
search_info = (protocol_name_search_t)user_data;
proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
if (proto_id != -1) {
protocol_filter_name = proto_get_protocol_filter_name(proto_id);
ws_assert(protocol_filter_name != NULL);
if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
/* Found a match */
if (search_info->nb_match == 0) {
/* Record this handle only if this is the first match */
search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
}
search_info->nb_match++;
}
}
}
/*
* The function below parses the command-line parameters for the decode as
* feature (a string pointer by cl_param).
* It checks the format of the command-line, searches for a matching table
* and dissector. If a table/dissector match is not found, we display a
* summary of the available tables/dissectors (on stderr) and return FALSE.
* If everything is fine, we get the "Decode as" preference activated,
* then we return TRUE.
*/
gboolean decode_as_command_option(const gchar *cl_param)
{
gchar *table_name;
guint32 selector = 0, selector2 = 0;
gchar *decoded_param;
gchar *remaining_param;
gchar *selector_str = NULL;
gchar *dissector_str;
dissector_handle_t dissector_matching;
dissector_table_t table_matching;
ftenum_t dissector_table_selector_type;
struct protocol_name_search user_protocol_name;
guint64 i;
char op = '\0';
/* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
ws_assert(cl_param);
decoded_param = g_strdup(cl_param);
ws_assert(decoded_param);
/* The lines below will parse this string (modifying it) to extract all
necessary information. Note that decoded_param is still needed since
strings are not copied - we just save pointers. */
/* This section extracts a layer type (table_name) from decoded_param */
table_name = decoded_param; /* Layer type string starts from beginning */
remaining_param = strchr(table_name, '=');
if (remaining_param == NULL) {
/* Dissector tables of type FT_NONE aren't required to specify a value, so for now
just check for comma */
remaining_param = strchr(table_name, ',');
if (remaining_param == NULL) {
cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, DECODE_AS_ARG_TEMPLATE);
} else {
*remaining_param = '\0'; /* Terminate the layer type string (table_name) where ',' was detected */
}
/* If the argument does not follow the template, carry on anyway to check
if the table name is at least correct. If remaining_param is NULL,
we'll exit anyway further down */
}
else {
*remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
}
/* Remove leading and trailing spaces from the table name */
while (table_name[0] == ' ')
table_name++;
while (table_name[strlen(table_name) - 1] == ' ')
table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
/* The following part searches a table matching with the layer type specified */
table_matching = NULL;
/* Look for the requested table */
if (!(*(table_name))) { /* Is the table name empty, if so, don't even search for anything, display a message */
cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
}
else {
table_matching = find_dissector_table(table_name);
if (!table_matching) {
cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
}
}
if (!table_matching) {
/* Display a list of supported layer types to help the user, if the
specified layer type was not found */
cmdarg_err("Valid layer types are:");
fprint_all_layer_types(stderr);
}
if (remaining_param == NULL || !table_matching) {
/* Exit if the layer type was not found, or if no '=' separator was found
(see above) */
g_free(decoded_param);
return FALSE;
}
dissector_table_selector_type = get_dissector_table_selector_type(table_name);
if (dissector_table_selector_type != FT_NONE) {
if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
}
else {
remaining_param++; /* Move to the second '=' */
*remaining_param = '\0'; /* Remove the second '=' */
}
remaining_param++; /* Position after the layer type string */
/* This section extracts a selector value (selector_str) from decoded_param */
selector_str = remaining_param; /* Next part starts with the selector number */
remaining_param = strchr(selector_str, ',');
if (remaining_param == NULL) {
cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, DECODE_AS_ARG_TEMPLATE);
/* If the argument does not follow the template, carry on anyway to check
if the selector value is at least correct. If remaining_param is NULL,
we'll exit anyway further down */
}
else {
*remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
}
}
switch (dissector_table_selector_type) {
case FT_UINT8:
case FT_UINT16:
case FT_UINT24:
case FT_UINT32:
{
/* The selector for this table is an unsigned number. Parse it as such.
Skip leading spaces for backwards compatibility (previously sscanf was used). */
gchar *str = selector_str;
gchar *end;
guint64 val;
while (g_ascii_isspace(*str)) {
str++;
}
val = g_ascii_strtoull(str, &end, 0);
if (str == end || val > G_MAXUINT32) {
cmdarg_err("Invalid selector number \"%s\"", selector_str);
g_free(decoded_param);
return FALSE;
}
selector = (guint32) val;
if (*end == '\0') {
/* not a range, but a single (valid) value */
op = '\0';
selector2 = 0;
} else if (*end == ':' || *end == '-') {
/* range value such as "8888:3" or "8888-8890" */
op = *end;
str = end + 1;
val = g_ascii_strtoull(str, &end, 0);
if (str == end || val > G_MAXUINT32 || *end != '\0') {
cmdarg_err("Invalid selector numeric range \"%s\"", selector_str);
g_free(decoded_param);
return FALSE;
}
selector2 = (guint32) val;
if (op == ':') {
if ((selector2 == 0) || ((guint64)selector + selector2 - 1) > G_MAXUINT32) {
cmdarg_err("Invalid selector numeric range \"%s\"", selector_str);
g_free(decoded_param);
return FALSE;
}
}
else if (selector2 < selector) {
/* We could swap them for the user, but maybe it's better to call
* this out as an error in case it's not what was intended? */
cmdarg_err("Invalid selector numeric range \"%s\"", selector_str);
g_free(decoded_param);
return FALSE;
}
} else {
/* neither a valid single value, nor a range. */
cmdarg_err("Invalid selector number \"%s\"", selector_str);
g_free(decoded_param);
return FALSE;
}
break;
}
case FT_STRING:
case FT_STRINGZ:
case FT_UINT_STRING:
case FT_STRINGZPAD:
case FT_STRINGZTRUNC:
/* The selector for this table is a string. */
break;
case FT_NONE:
/* There is no selector for this table */
break;
default:
/* There are currently no dissector tables with any types other
than the ones listed above. */
ws_assert_not_reached();
}
if (remaining_param == NULL) {
/* Exit if no ',' separator was found (see above) */
cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
fprint_all_protocols_for_layer_types(stderr, table_name);
g_free(decoded_param);
return FALSE;
}
remaining_param++; /* Position after the selector number string */
/* This section extracts a protocol filter name (dissector_str) from decoded_param */
dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
/* Remove leading and trailing spaces from the dissector name */
while (dissector_str[0] == ' ')
dissector_str++;
while (dissector_str[strlen(dissector_str) - 1] == ' ')
dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
dissector_matching = NULL;
/* We now have a pointer to the handle for the requested table inside the variable table_matching */
if (!(*dissector_str)) { /* Is the dissector name empty, if so, don't even search for a matching dissector and display all dissectors found for the selected table */
cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
}
else {
header_field_info *hfi = proto_registrar_get_byalias(dissector_str);
user_protocol_name.nb_match = 0;
if (hfi) {
user_protocol_name.searched_name = hfi->abbrev;
} else {
user_protocol_name.searched_name = dissector_str;
}
user_protocol_name.matched_handle = NULL;
dissector_table_foreach_handle(table_name, find_protocol_name_func, &user_protocol_name); /* Go and perform the search for this dissector in the this table's dissectors' names and shortnames */
if (user_protocol_name.nb_match != 0) {
dissector_matching = user_protocol_name.matched_handle;
if (user_protocol_name.nb_match > 1) {
cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
}
}
else {
/* OK, check whether the problem is that there isn't any such
protocol, or that there is but it's not specified as a protocol
that's valid for that dissector table.
Note, we don't exit here, but dissector_matching will remain NULL,
so we exit below */
if (proto_get_id_by_filter_name(dissector_str) == -1) {
/* No such protocol */
cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
}
else {
cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
dissector_str, table_name);
}
}
}
if (!dissector_matching) {
cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
fprint_all_protocols_for_layer_types(stderr, table_name);
g_free(decoded_param);
return FALSE;
}
/* This is the end of the code that parses the command-line options.
All information is now stored in the variables:
table_name
selector
dissector_matching
The above variables that are strings are still pointing to areas within
decoded_parm. decoded_parm thus still needs to be kept allocated in
until we stop needing these variables
decoded_param will be deallocated at each exit point of this function */
/* We now have a pointer to the handle for the requested dissector
(requested protocol) inside the variable dissector_matching */
switch (dissector_table_selector_type) {
case FT_UINT8:
case FT_UINT16:
case FT_UINT24:
case FT_UINT32:
/* The selector for this table is an unsigned number. */
if (op == '\0') {
dissector_change_uint(table_name, selector, dissector_matching);
}
else if (op == ':') {
for (i = selector; i < (guint64)selector + selector2; i++) {
dissector_change_uint(table_name, (guint32)i, dissector_matching);
}
}
else { /* op == '-' */
for (i = selector; i <= selector2; i++) {
dissector_change_uint(table_name, (guint32)i, dissector_matching);
}
}
break;
case FT_STRING:
case FT_STRINGZ:
case FT_UINT_STRING:
case FT_STRINGZPAD:
case FT_STRINGZTRUNC:
/* The selector for this table is a string. */
dissector_change_string(table_name, selector_str, dissector_matching);
break;
case FT_NONE:
/* Just directly set the dissector found. */
dissector_change_payload(table_name, dissector_matching);
break;
default:
/* There are currently no dissector tables with any types other
than the ones listed above. */
ws_assert_not_reached();
}
g_free(decoded_param); /* "Decode As" rule has been successfully added */
return TRUE;
} |
C/C++ | wireshark/ui/decode_as_utils.h | /** @file
*
* "Decode As" UI utility routines.
*
* By David Hampton <[email protected]>
* Copyright 2001 David Hampton
*
* SPDX-License-Identifier: GPL-2.0-or-later*
*/
#ifndef __DECODE_AS_UTILS_H__
#define __DECODE_AS_UTILS_H__
#include "ws_symbol_export.h"
/** @file
* "Decode As" / "User Specified Decodes" dialog box.
* @ingroup main_ui_group
*/
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* This is the template for the decode as option; it is shared between the
* various functions that output the usage for this parameter.
*/
#define DECODE_AS_ARG_TEMPLATE "<layer_type>==<selector>,<decode_as_protocol>"
gboolean decode_as_command_option(const gchar *cl_param);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __DECODE_AS_UTILS_H__ */ |
C | wireshark/ui/dissect_opts.c | /* dissect_opts.c
* Routines for dissection options setting
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <epan/prefs.h>
#include <epan/timestamp.h>
#include <epan/addr_resolv.h>
#include <epan/disabled_protos.h>
#include "ui/decode_as_utils.h"
#if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
#include <epan/dissectors/read_keytab_file.h>
#endif
#include <wsutil/clopts_common.h>
#include <wsutil/cmdarg_err.h>
#include <wsutil/file_util.h>
#include <wsutil/ws_assert.h>
#include "ui/dissect_opts.h"
dissect_options global_dissect_options = {
.time_format = TS_NOT_SET,
.time_precision = TS_PREC_NOT_SET
};
gboolean
dissect_opts_handle_opt(int opt, char *optarg_str_p)
{
char badopt;
char *p, *dotp;
ts_precision tsp;
switch(opt) {
case 'd': /* Decode as rule */
if (!decode_as_command_option(optarg_str_p))
return FALSE;
break;
case 'K': /* Kerberos keytab file */
#if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
read_keytab_file(optarg_str_p);
#else
cmdarg_err("-K specified, but Kerberos keytab file support isn't present");
return FALSE;
#endif
break;
case 'n': /* No name resolution */
disable_name_resolution();
break;
case 'N': /* Select what types of addresses/port #s to resolve */
badopt = string_to_name_resolve(optarg_str_p, &gbl_resolv_flags);
if (badopt != '\0') {
cmdarg_err("-N specifies unknown resolving option '%c'; valid options are:",
badopt);
cmdarg_err_cont("\t'd' to enable address resolution from captured DNS packets\n"
"\t'g' to enable address geolocation information from MaxMind databases\n"
"\t'm' to enable MAC address resolution\n"
"\t'n' to enable network address resolution\n"
"\t'N' to enable using external resolvers (e.g., DNS)\n"
"\t for network address resolution\n"
"\t't' to enable transport-layer port number resolution\n"
"\t'v' to enable VLAN IDs to names resolution");
return FALSE;
}
break;
case 't': /* Time stamp type */
tsp = TS_PREC_NOT_SET;
dotp = strchr(optarg_str_p, '.');
if (dotp != NULL) {
/* Set dotp to NULL on errors. */
p = dotp;
switch(*++p) {
case '\0':
tsp = TS_PREC_AUTO;
break;
case '0':
tsp = TS_PREC_FIXED_SEC;
break;
case '1':
tsp = TS_PREC_FIXED_DSEC;
break;
case '2':
tsp = TS_PREC_FIXED_CSEC;
break;
case '3':
tsp = TS_PREC_FIXED_MSEC;
break;
case '6':
tsp = TS_PREC_FIXED_USEC;
break;
case '9':
tsp = TS_PREC_FIXED_NSEC;
break;
default:
dotp = NULL;
break;
}
/* If we saw a '.', reject if do not have only '.' or a single digit '.N'. */
if (dotp && *p != '\0' && *++p != '\0')
dotp = NULL;
if (dotp) {
/* Mask the '.' while checking format. */
*dotp = '\0';
} else {
cmdarg_err("Invalid .N time stamp precision \"%s\"; N must be 0, 1, 2, 3, 6, 9 or absent", optarg_str_p);
return FALSE;
}
}
if (strcmp(optarg_str_p, "r") == 0)
global_dissect_options.time_format = TS_RELATIVE;
else if (strcmp(optarg_str_p, "a") == 0)
global_dissect_options.time_format = TS_ABSOLUTE;
else if (strcmp(optarg_str_p, "ad") == 0)
global_dissect_options.time_format = TS_ABSOLUTE_WITH_YMD;
else if (strcmp(optarg_str_p, "adoy") == 0)
global_dissect_options.time_format = TS_ABSOLUTE_WITH_YDOY;
else if (strcmp(optarg_str_p, "d") == 0)
global_dissect_options.time_format = TS_DELTA;
else if (strcmp(optarg_str_p, "dd") == 0)
global_dissect_options.time_format = TS_DELTA_DIS;
else if (strcmp(optarg_str_p, "e") == 0)
global_dissect_options.time_format = TS_EPOCH;
else if (strcmp(optarg_str_p, "u") == 0)
global_dissect_options.time_format = TS_UTC;
else if (strcmp(optarg_str_p, "ud") == 0)
global_dissect_options.time_format = TS_UTC_WITH_YMD;
else if (strcmp(optarg_str_p, "udoy") == 0)
global_dissect_options.time_format = TS_UTC_WITH_YDOY;
else if (optarg_str_p != dotp) {
/* If (optarg_str_p == dotp), user only set precision. */
if (dotp)
*dotp = '.';
cmdarg_err("Invalid time stamp type \"%s\"; it must be one of:", optarg_str_p);
cmdarg_err_cont("\t\"a\" for absolute\n"
"\t\"ad\" for absolute with YYYY-MM-DD date\n"
"\t\"adoy\" for absolute with YYYY/DOY date\n"
"\t\"d\" for delta\n"
"\t\"dd\" for delta displayed\n"
"\t\"e\" for epoch\n"
"\t\"r\" for relative\n"
"\t\"u\" for absolute UTC\n"
"\t\"ud\" for absolute UTC with YYYY-MM-DD date\n"
"\t\"udoy\" for absolute UTC with YYYY/DOY date");
return FALSE;
}
if (dotp) {
*dotp = '.';
global_dissect_options.time_precision = tsp;
}
break;
case 'u': /* Seconds type */
if (strcmp(optarg_str_p, "s") == 0)
timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
else if (strcmp(optarg_str_p, "hms") == 0)
timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
else {
cmdarg_err("Invalid seconds type \"%s\"; it must be one of:", optarg_str_p);
cmdarg_err_cont("\t\"s\" for seconds\n"
"\t\"hms\" for hours, minutes and seconds");
return FALSE;
}
break;
case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
global_dissect_options.disable_protocol_slist = g_slist_append(global_dissect_options.disable_protocol_slist, optarg_str_p);
break;
case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
global_dissect_options.enable_heur_slist = g_slist_append(global_dissect_options.enable_heur_slist, optarg_str_p);
break;
case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
global_dissect_options.disable_heur_slist = g_slist_append(global_dissect_options.disable_heur_slist, optarg_str_p);
break;
case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disableed by default) */
global_dissect_options.enable_protocol_slist = g_slist_append(global_dissect_options.enable_protocol_slist, optarg_str_p);
break;
case LONGOPT_ONLY_PROTOCOLS: /* enable dissection of these comma separated protocols only */
proto_disable_all();
for (char *ps = strtok (optarg_str_p, ","); ps; ps = strtok(NULL, ",")){
global_dissect_options.enable_protocol_slist = g_slist_append(global_dissect_options.enable_protocol_slist, ps);
}
break;
case LONGOPT_DISABLE_ALL_PROTOCOLS: /* disable dissection of all protocols */
proto_disable_all();
break;
default:
/* the caller is responsible to send us only the right opt's */
ws_assert_not_reached();
}
return TRUE;
}
typedef gboolean (proto_set_func)(const char *);
static gboolean
process_enable_disable_list(GSList *list, proto_set_func callback)
{
gboolean success = TRUE;
gboolean rv;
GSList *iter;
char *c;
char *proto_name;
for (iter = list; iter != NULL; iter = g_slist_next(iter)) {
proto_name = (char *)iter->data;
c = strchr(proto_name, ',');
if (c == NULL) {
rv = callback(proto_name);
if (!rv) {
cmdarg_err("No such protocol %s", proto_name);
success = FALSE;
}
}
else {
char *start;
char save;
start = proto_name;
while(1) {
if (c != NULL) {
save = *c;
*c = '\0';
}
rv = callback(start);
if (!rv) {
cmdarg_err("No such protocol %s", start);
success = FALSE;
}
if (c != NULL) {
*c = save;
start = (save == ',' ? c+1 : c);
c = strchr(start, ',');
}
else {
break;
}
}
}
}
return success;
}
gboolean
setup_enabled_and_disabled_protocols(void)
{
gboolean success = TRUE;
success &= process_enable_disable_list(global_dissect_options.disable_protocol_slist,
proto_disable_proto_by_name);
success &= process_enable_disable_list(global_dissect_options.enable_protocol_slist,
proto_enable_proto_by_name);
success &= process_enable_disable_list(global_dissect_options.enable_heur_slist,
proto_enable_heuristic_by_name);
success &= process_enable_disable_list(global_dissect_options.disable_heur_slist,
proto_disable_heuristic_by_name);
return success;
} |
C/C++ | wireshark/ui/dissect_opts.h | /** @file
*
* Dissection options (parameters that affect dissection)
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/** @file
*
* Dissection options (parameters that affect dissection)
*
*/
#ifndef __DISSECT_OPTS_H__
#define __DISSECT_OPTS_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* Long options.
* We do not currently have long options corresponding to all short
* options; we should probably pick appropriate option names for them.
*/
#define LONGOPT_DISABLE_PROTOCOL LONGOPT_BASE_DISSECTOR+1
#define LONGOPT_ENABLE_HEURISTIC LONGOPT_BASE_DISSECTOR+2
#define LONGOPT_DISABLE_HEURISTIC LONGOPT_BASE_DISSECTOR+3
#define LONGOPT_ENABLE_PROTOCOL LONGOPT_BASE_DISSECTOR+4
#define LONGOPT_ONLY_PROTOCOLS LONGOPT_BASE_DISSECTOR+5
#define LONGOPT_DISABLE_ALL_PROTOCOLS LONGOPT_BASE_DISSECTOR+6
/*
* Options for dissecting common to all dissecting programs.
*/
#define LONGOPT_DISSECT_COMMON \
{"disable-protocol", ws_required_argument, NULL, LONGOPT_DISABLE_PROTOCOL }, \
{"enable-heuristic", ws_required_argument, NULL, LONGOPT_ENABLE_HEURISTIC }, \
{"disable-heuristic", ws_required_argument, NULL, LONGOPT_DISABLE_HEURISTIC }, \
{"enable-protocol", ws_required_argument, NULL, LONGOPT_ENABLE_PROTOCOL }, \
{"only-protocols", ws_required_argument, NULL, LONGOPT_ONLY_PROTOCOLS }, \
{"disable-all-protocols", ws_no_argument, NULL, LONGOPT_DISABLE_ALL_PROTOCOLS }, \
#define OPTSTRING_DISSECT_COMMON \
"d:K:nN:t:u:"
/** Capture options coming from user interface */
typedef struct dissect_options_tag {
ts_type time_format;
ts_precision time_precision;
GSList *enable_protocol_slist; //enable protocols that are disabled by default
GSList *disable_protocol_slist;
GSList *enable_heur_slist;
GSList *disable_heur_slist;
} dissect_options;
extern dissect_options global_dissect_options;
/*
* Handle a command line option.
* Returns TRUE if the option is valid, FALSE if not; an error message
* is reported with cmdarg_err() if it's not valid.
*/
extern gboolean
dissect_opts_handle_opt(int opt, char *optarg_str_p);
/*
* Set up disabled protocols and enabled/disabled heuristic protocols
* as per specified command-line options.
*
* Returns TRUE if all specified heuristic protocols exist, FALSE
* otherwise.
*/
extern gboolean
setup_enabled_and_disabled_protocols(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* dissect_opts.h */ |
C | wireshark/ui/export_pdu_ui_utils.c | /*
* export_pdu_ui_utils.c
* Routines for exported_pdu dissection
* Copyright 2013, Anders Broman <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include "globals.h"
#include "wsutil/os_version_info.h"
#include "wsutil/tempfile.h"
#include "wsutil/version_info.h"
#include <epan/tap.h>
#include <epan/prefs.h>
#include <epan/exported_pdu.h>
#include <epan/epan_dissect.h>
#include <wiretap/wtap.h>
#include <wiretap/wtap_opttypes.h>
#include "ui/alert_box.h"
#include "ui/simple_dialog.h"
#include "tap_export_pdu.h"
#include "export_pdu_ui_utils.h"
void
do_export_pdu(const char *filter, const gchar *temp_dir, const gchar *tap_name)
{
exp_pdu_t exp_pdu_tap_data;
char *error;
int import_file_fd;
int file_type_subtype;
char *capfile_name = NULL, *comment;
gboolean status;
int err;
gchar *err_info;
error = exp_pdu_pre_open(tap_name, filter, &exp_pdu_tap_data);
if (error) {
/* Error. We failed to attach to the tap. Clean up */
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", error);
g_free(error);
return;
}
/* Choose a random name for the temporary import buffer */
GError *err_tempfile = NULL;
import_file_fd = create_tempfile(temp_dir, &capfile_name, "Wireshark_PDU_", NULL, &err_tempfile);
if (import_file_fd < 0) {
failure_alert_box("Temporary file could not be created: %s", err_tempfile->message);
g_error_free(err_tempfile);
g_free(capfile_name);
return;
}
/* Write a pcapng file... */
file_type_subtype = wtap_pcapng_file_type_subtype();
/* ...with this comment */
comment = ws_strdup_printf("Dump of PDUs from %s", cfile.filename);
status = exp_pdu_open(&exp_pdu_tap_data, capfile_name, file_type_subtype,
import_file_fd, comment, &err, &err_info);
g_free(comment);
if (!status) {
cfile_dump_open_failure_alert_box(capfile_name ? capfile_name : "temporary file",
err, err_info, file_type_subtype);
g_free(capfile_name);
return;
}
/* Run the tap */
cf_retap_packets(&cfile);
if (!exp_pdu_close(&exp_pdu_tap_data, &err, &err_info)) {
cfile_close_failure_alert_box(capfile_name, err, err_info);
/*
* XXX - remove the temporary file and don't open it as
* the current capture?
*/
}
/* XXX: should this use the open_routine type in the cfile instead of WTAP_TYPE_AUTO? */
if (cf_open(&cfile, capfile_name, WTAP_TYPE_AUTO, TRUE /* temporary file */, &err) != CF_OK) {
/* cf_open() has put up a dialog box for the error */
g_free(capfile_name);
return;
}
switch (cf_read(&cfile, /*reloading=*/FALSE)) {
case CF_READ_OK:
case CF_READ_ERROR:
/* Just because we got an error, that doesn't mean we were unable
to read any of the file; we handle what we could get from the
file. */
break;
case CF_READ_ABORTED:
/* The user bailed out of re-reading the capture file; the
capture file has been closed - just free the capture file name
string and return (without changing the last containing
directory). */
break;
}
g_free(capfile_name);
} |
C/C++ | wireshark/ui/export_pdu_ui_utils.h | /** @file
*
* Routines for exported_pdu dissection
* Copyright 2013, Anders Broman <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef EXPORT_PDU_UI_UTILS_H
#define EXPORT_PDU_UI_UTILS_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
* Filters the current opened capture file into a temporary file. On success,
* the filtered file is opened into the UI.
*/
void do_export_pdu(const char *filter, const gchar *temp_dir, const gchar *tap_name);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* EXPORT_PDU_UI_UTILS_H */ |
C | wireshark/ui/failure_message.c | /* failure_message.c
* Routines to print various "standard" failure messages used in multiple
* places
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <string.h>
#include <errno.h>
#include <wiretap/wtap.h>
#include <wsutil/filesystem.h>
#include <wsutil/report_message.h>
#include <wsutil/cmdarg_err.h>
#include "ui/failure_message.h"
/*
* Generic error message.
*/
void
failure_message(const char *msg_format, va_list ap)
{
vcmdarg_err(msg_format, ap);
}
/*
* Error message for a failed attempt to open or create a file
* other than a capture file.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno; "for_writing" is TRUE if we're opening
* the file for writing and FALSE if we're opening it for reading.
*/
void
open_failure_message(const char *filename, int err, gboolean for_writing)
{
cmdarg_err(file_open_error_message(err, for_writing), filename);
}
/*
* Error message for a failed attempt to read from a file other than
* a capture file.
* "filename" is the name of the file being read from; "err" is assumed
* to be a UNIX-style errno.
*/
void
read_failure_message(const char *filename, int err)
{
cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
filename, g_strerror(err));
}
/*
* Error message for a failed attempt to write to a file other than
* a capture file.
* "filename" is the name of the file being written to; "err" is assumed
* to be a UNIX-style errno.
*/
void
write_failure_message(const char *filename, int err)
{
cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
filename, g_strerror(err));
}
static char *
input_file_description(const char *fname)
{
char *fstring;
if (strcmp(fname, "-") == 0) {
/* We're reading from the standard input */
fstring = g_strdup("standard input");
} else {
/* We're reading from a file */
fstring = ws_strdup_printf("file \"%s\"", fname);
}
return fstring;
}
static char *
output_file_description(const char *fname)
{
char *fstring;
if (strcmp(fname, "-") == 0) {
/* We're writing to the standard output */
fstring = g_strdup("standard output");
} else {
/* We're writing to a file */
fstring = ws_strdup_printf("file \"%s\"", fname);
}
return fstring;
}
/*
* Error message for a failed attempt to open a capture file for reading.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values.
*/
void
cfile_open_failure_message(const char *filename, int err, gchar *err_info)
{
if (err < 0) {
/*
* Wiretap error.
* Get a string that describes what we're opening.
*/
char *file_description = input_file_description(filename);
switch (err) {
case WTAP_ERR_NOT_REGULAR_FILE:
cmdarg_err("The %s is a \"special file\" or socket or other non-regular file.",
file_description);
break;
case WTAP_ERR_RANDOM_OPEN_PIPE:
cmdarg_err("The %s is a pipe or FIFO; %s can't read pipe or FIFO files in two-pass mode.",
file_description, get_friendly_program_name());
break;
case WTAP_ERR_FILE_UNKNOWN_FORMAT:
cmdarg_err("The %s isn't a capture file in a format %s understands.",
file_description, get_friendly_program_name());
break;
case WTAP_ERR_UNSUPPORTED:
cmdarg_err("The %s contains record data that %s doesn't support.\n"
"(%s)",
file_description, get_friendly_program_name(),
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
cmdarg_err("The %s is a capture for a network type that %s doesn't support.",
file_description, get_friendly_program_name());
break;
case WTAP_ERR_BAD_FILE:
cmdarg_err("The %s appears to be damaged or corrupt.\n"
"(%s)",
file_description,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_CANT_OPEN:
cmdarg_err("The %s could not be opened for some unknown reason.",
file_description);
break;
case WTAP_ERR_SHORT_READ:
cmdarg_err("The %s appears to have been cut short in the middle of a packet or other data.",
file_description);
break;
case WTAP_ERR_DECOMPRESS:
cmdarg_err("The %s cannot be decompressed; it may be damaged or corrupt."
"(%s)",
file_description,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_INTERNAL:
cmdarg_err("An internal error occurred opening the %s.\n"
"(%s)",
file_description,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED:
cmdarg_err("The %s cannot be decompressed; it is compressed in a way that we don't support."
"(%s)",
file_description,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
default:
cmdarg_err("The %s could not be opened: %s.",
file_description,
wtap_strerror(err));
break;
}
g_free(file_description);
} else
cmdarg_err(file_open_error_message(err, FALSE), filename);
}
/*
* Error message for a failed attempt to open a capture file for writing.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values;
* "file_type_subtype" is a WTAP_FILE_TYPE_SUBTYPE_ value for the type
* and subtype of file being opened.
*/
void
cfile_dump_open_failure_message(const char *filename, int err, gchar *err_info,
int file_type_subtype)
{
if (err < 0) {
/*
* Wiretap error.
* Get a string that describes what we're opening.
*/
char *file_description = output_file_description(filename);
switch (err) {
case WTAP_ERR_NOT_REGULAR_FILE:
cmdarg_err("The %s is a \"special file\" or socket or other non-regular file.",
file_description);
break;
case WTAP_ERR_CANT_WRITE_TO_PIPE:
cmdarg_err("The %s is a pipe, and \"%s\" capture files can't be written to a pipe.",
file_description,
wtap_file_type_subtype_name(file_type_subtype));
break;
case WTAP_ERR_UNWRITABLE_FILE_TYPE:
cmdarg_err("%s doesn't support writing capture files in that format.",
get_friendly_program_name());
break;
case WTAP_ERR_UNWRITABLE_ENCAP:
cmdarg_err("The capture file being read can't be written as a \"%s\" file.",
wtap_file_type_subtype_name(file_type_subtype));
break;
case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
cmdarg_err("The capture file being read can't be written as a \"%s\" file.",
wtap_file_type_subtype_name(file_type_subtype));
break;
case WTAP_ERR_CANT_OPEN:
cmdarg_err("The %s could not be created for some unknown reason.",
file_description);
break;
case WTAP_ERR_SHORT_WRITE:
cmdarg_err("A full header couldn't be written to the %s.",
file_description);
break;
case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
cmdarg_err("This file type cannot be written as a compressed file.");
break;
case WTAP_ERR_INTERNAL:
cmdarg_err("An internal error occurred creating the %s.\n"
"(%s)",
file_description,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
default:
cmdarg_err("The %s could not be created: %s.",
file_description,
wtap_strerror(err));
break;
}
g_free(file_description);
} else
cmdarg_err(file_open_error_message(err, TRUE), filename);
}
/*
* Error message for a failed attempt to read from a capture file.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values.
*/
void
cfile_read_failure_message(const char *filename, int err, gchar *err_info)
{
char *file_string;
/* Get a string that describes what we're reading from */
file_string = input_file_description(filename);
switch (err) {
case WTAP_ERR_UNSUPPORTED:
cmdarg_err("The %s contains record data that %s doesn't support.\n"
"(%s)",
file_string, get_friendly_program_name(),
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_SHORT_READ:
cmdarg_err("The %s appears to have been cut short in the middle of a packet.",
file_string);
break;
case WTAP_ERR_BAD_FILE:
cmdarg_err("The %s appears to be damaged or corrupt.\n"
"(%s)",
file_string,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_DECOMPRESS:
cmdarg_err("The %s cannot be decompressed; it may be damaged or corrupt.\n"
"(%s)",
file_string,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_INTERNAL:
cmdarg_err("An internal error occurred while reading the %s.\n(%s)",
file_string,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_DECOMPRESSION_NOT_SUPPORTED:
cmdarg_err("The %s cannot be decompressed; it is compressed in a way that we don't support.\n"
"(%s)",
file_string,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
default:
cmdarg_err("An error occurred while reading the %s: %s.",
file_string, wtap_strerror(err));
break;
}
g_free(file_string);
}
/*
* Error message for a failed attempt to write to a capture file.
* "in_filename" is the name of the file from which the record
* being written came; "out_filename" is the name of the file to
* which we're writing; "err" is assumed "err" is assumed to be a
* UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed to be
* a string giving further information for some WTAP_ERR_ values;
* "framenum" is the frame number of the record on which the error
* occurred; "file_type_subtype" is a WTAP_FILE_TYPE_SUBTYPE_ value
* for the type and subtype of file being written.
*/
void
cfile_write_failure_message(const char *in_filename, const char *out_filename,
int err, gchar *err_info,
guint32 framenum, int file_type_subtype)
{
char *in_file_string;
char *in_frame_string;
char *out_file_string;
/* Get a string that describes what we're reading from */
if (in_filename == NULL) {
in_frame_string = g_strdup("");
} else {
in_file_string = input_file_description(in_filename);
in_frame_string = ws_strdup_printf(" %u of %s", framenum,
in_file_string);
g_free(in_file_string);
}
/* Get a string that describes what we're writing to */
out_file_string = output_file_description(out_filename);
switch (err) {
case WTAP_ERR_UNWRITABLE_ENCAP:
/*
* This is a problem with the particular frame we're writing
* and the file type and subtype we're writing; note that,
* and report the frame number and file type/subtype.
*/
cmdarg_err("Frame%s has a network type that can't be saved in a \"%s\" file.",
in_frame_string,
wtap_file_type_subtype_name(file_type_subtype));
break;
case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
/*
* This is a problem with the particular frame we're writing and
* the file type and subtype we're writing; note that, and report
* the frame number and file type/subtype.
*/
cmdarg_err("Frame%s has a network type that differs from the network type of earlier packets, which isn't supported in a \"%s\" file.",
in_frame_string,
wtap_file_type_subtype_description(file_type_subtype));
break;
case WTAP_ERR_PACKET_TOO_LARGE:
/*
* This is a problem with the particular frame we're writing
* and the file type and subtype we're writing; note that,
* and report the frame number and file type/subtype.
*/
cmdarg_err("Frame%s is larger than %s supports in a \"%s\" file.",
in_frame_string, get_friendly_program_name(),
wtap_file_type_subtype_name(file_type_subtype));
break;
case WTAP_ERR_UNWRITABLE_REC_TYPE:
/*
* This is a problem with the particular record we're writing
* and the file type and subtype we're writing; note that,
* and report the record number and file type/subtype.
*/
cmdarg_err("Record%s has a record type that can't be saved in a \"%s\" file.",
in_frame_string,
wtap_file_type_subtype_name(file_type_subtype));
break;
case WTAP_ERR_UNWRITABLE_REC_DATA:
/*
* This is a problem with the particular record we're writing
* and the file type and subtype we're writing; note that,
* and report the record number and file type/subtype.
*/
cmdarg_err("Record%s has data that can't be saved in a \"%s\" file.\n"
"(%s)",
in_frame_string,
wtap_file_type_subtype_name(file_type_subtype),
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case WTAP_ERR_INTERNAL:
cmdarg_err("An internal error occurred while writing record%s to the %s.\n(%s)",
in_frame_string, out_file_string,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
case ENOSPC:
cmdarg_err("Not all the packets could be written to the %s because there is "
"no space left on the file system.",
out_file_string);
break;
#ifdef EDQUOT
case EDQUOT:
cmdarg_err("Not all the packets could be written to the %s because you are "
"too close to, or over your disk quota.",
out_file_string);
break;
#endif
case WTAP_ERR_SHORT_WRITE:
cmdarg_err("A full write couldn't be done to the %s.",
out_file_string);
break;
default:
cmdarg_err("An error occurred while writing to the %s: %s.",
out_file_string, wtap_strerror(err));
break;
}
g_free(in_frame_string);
g_free(out_file_string);
}
/*
* Error message for a failed attempt to close a capture file.
* "filename" is the name of the file being closed; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values.
*
* When closing a capture file:
*
* some information in the file that can't be determined until
* all packets have been written might be written to the file
* (such as a table of the file offsets of all packets);
*
* data buffered in the low-level file writing code might be
* flushed to the file;
*
* for remote file systems, data written to the file but not
* yet sent to the server might be sent to the server or, if
* that data was sent asynchronously, "out of space", "disk
* quota exceeded", or "I/O error" indications might have
* been received but not yet delivered, and the close operation
* could deliver them;
*
* so we have to check for write errors here.
*/
void
cfile_close_failure_message(const char *filename, int err, gchar *err_info)
{
char *file_string;
/* Get a string that describes what we're writing to */
file_string = output_file_description(filename);
switch (err) {
case ENOSPC:
cmdarg_err("Not all the packets could be written to the %s because there is "
"no space left on the file system.",
file_string);
break;
#ifdef EDQUOT
case EDQUOT:
cmdarg_err("Not all the packets could be written to the %s because you are "
"too close to, or over your disk quota.",
file_string);
break;
#endif
case WTAP_ERR_CANT_CLOSE:
cmdarg_err("The %s couldn't be closed for some unknown reason.",
file_string);
break;
case WTAP_ERR_SHORT_WRITE:
cmdarg_err("A full write couldn't be done to the %s.",
file_string);
break;
case WTAP_ERR_INTERNAL:
cmdarg_err("An internal error occurred closing the file \"%s\".\n"
"(%s)",
file_string,
err_info != NULL ? err_info : "no information supplied");
g_free(err_info);
break;
default:
cmdarg_err("An error occurred while closing the file %s: %s.",
file_string, wtap_strerror(err));
break;
}
g_free(file_string);
} |
C/C++ | wireshark/ui/failure_message.h | /** @file
*
* Routines to print various "standard" failure messages used in multiple
* places
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __FAILURE_MESSAGE_H__
#define __FAILURE_MESSAGE_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* Generic error message.
*/
extern void failure_message(const char *msg_format, va_list ap);
/*
* Error message for a failed attempt to open or create a file
* other than a capture file.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno; "for_writing" is TRUE if we're opening
* the file for writing and FALSE if we're opening it for reading.
*/
extern void open_failure_message(const char *filename, int err,
gboolean for_writing);
/*
* Error message for a failed attempt to read from a file other than
* a capture file.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno.
*/
extern void read_failure_message(const char *filename, int err);
/*
* Error message for a failed attempt to write to a file other than
* a capture file.
* "filename" is the name of the file being written to; "err" is assumed
* to be a UNIX-style errno.
*/
extern void write_failure_message(const char *filename, int err);
/*
* Error message for a failed attempt to open a capture file for input.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values.
*/
extern void cfile_open_failure_message(const char *filename, int err,
gchar *err_info);
/*
* Error message for a failed attempt to open a capture file for output.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values;
* "file_type_subtype" is a WTAP_FILE_TYPE_SUBTYPE_ value for the type
* and subtype of file being opened.
*/
extern void cfile_dump_open_failure_message(const char *filename, int err,
gchar *err_info,
int file_type_subtype);
/*
* Error message for a failed attempt to read from a capture file.
* "filename" is the name of the file being opened; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values.
*/
extern void cfile_read_failure_message(const char *filename, int err,
gchar *err_info);
/*
* Error message for a failed attempt to write to a capture file.
* "in_filename" is the name of the file from which the record
* being written came; "out_filename" is the name of the file to
* which we're writing; "err" is assumed "err" is assumed to be a
* UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed to be
* a string giving further information for some WTAP_ERR_ values;
* "framenum" is the frame number of the record on which the error
* occurred; "file_type_subtype" is a WTAP_FILE_TYPE_SUBTYPE_ value
* for the type and subtype of file being written.
*/
extern void cfile_write_failure_message(const char *in_filename,
const char *out_filename,
int err, gchar *err_info,
guint32 framenum,
int file_type_subtype);
/*
* Error message for a failed attempt to close a capture file.
* "filename" is the name of the file being closed; "err" is assumed
* to be a UNIX-style errno or a WTAP_ERR_ value; "err_info" is assumed
* to be a string giving further information for some WTAP_ERR_ values.
*
* When closing a capture file:
*
* some information in the file that can't be determined until
* all packets have been written might be written to the file
* (such as a table of the file offsets of all packets);
*
* data buffered in the low-level file writing code might be
* flushed to the file;
*
* for remote file systems, data written to the file but not
* yet sent to the server might be sent to the server or, if
* that data was sent asynchronously, "out of space", "disk
* quota exceeded", or "I/O error" indications might have
* been received but not yet delivered, and the close operation
* could deliver them;
*
* so we have to check for write errors here.
*/
extern void cfile_close_failure_message(const char *filename, int err,
gchar *err_info);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __FAILURE_MESSAGE_H__ */ |
C | wireshark/ui/file_dialog.c | /* file_dialog.c
* Common file dialog routines
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 2006 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <time.h>
#include <glib.h>
#include <wsutil/nstime.h>
#include <wiretap/wtap.h>
#include <epan/prefs.h>
#include "ui/file_dialog.h"
ws_file_preview_stats_status
get_stats_for_preview(wtap *wth, ws_file_preview_stats *stats,
int *err, gchar **err_info)
{
gint64 data_offset;
wtap_rec rec;
Buffer buf;
guint32 records;
guint32 data_records;
double start_time;
double stop_time;
gboolean have_times;
gboolean timed_out;
time_t time_preview, time_current;
double cur_time;
have_times = FALSE;
start_time = 0;
stop_time = 0;
records = 0;
data_records = 0;
timed_out = FALSE;
time(&time_preview);
wtap_rec_init(&rec);
ws_buffer_init(&buf, 1514);
while ((wtap_read(wth, &rec, &buf, err, err_info, &data_offset))) {
if (rec.presence_flags & WTAP_HAS_TS) {
cur_time = nstime_to_sec(&rec.ts);
if (!have_times) {
start_time = cur_time;
stop_time = cur_time;
have_times = TRUE;
}
if (cur_time < start_time) {
start_time = cur_time;
}
if (cur_time > stop_time){
stop_time = cur_time;
}
}
switch (rec.rec_type) {
case REC_TYPE_PACKET:
case REC_TYPE_FT_SPECIFIC_EVENT:
case REC_TYPE_FT_SPECIFIC_REPORT:
case REC_TYPE_SYSCALL:
case REC_TYPE_SYSTEMD_JOURNAL_EXPORT:
data_records++;
break;
}
records++;
if ((records % 1000) == 0) {
/* do we have a timeout? */
time(&time_current);
if (time_current-time_preview >= (time_t) prefs.gui_fileopen_preview) {
timed_out = TRUE;
break;
}
}
wtap_rec_reset(&rec);
}
stats->have_times = have_times;
stats->start_time = start_time;
stats->stop_time = stop_time;
stats->records = records;
stats->data_records = data_records;
wtap_rec_cleanup(&rec);
ws_buffer_free(&buf);
if (*err != 0) {
/* Read error. */
return PREVIEW_READ_ERROR;
}
return timed_out ? PREVIEW_TIMED_OUT : PREVIEW_SUCCEEDED;
} |
C/C++ | wireshark/ui/file_dialog.h | /** @file
*
* Common file dialog definitions
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 2006 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __FILE_DIALOG_H__
#define __FILE_DIALOG_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef enum {
SAVE,
SAVE_WITHOUT_COMMENTS,
SAVE_IN_ANOTHER_FORMAT,
CANCELLED
} check_savability_t;
typedef enum {
export_type_text = 1,
export_type_ps,
export_type_csv,
export_type_psml,
export_type_pdml,
export_type_carrays,
export_type_json
} export_type_e;
typedef struct {
gboolean have_times; /* TRUE if we have start and stop times */
double start_time; /* seconds, with nsec resolution */
double stop_time; /* seconds, with nsec resolution */
guint32 records; /* total number of records */
guint32 data_records; /* number of data records */
} ws_file_preview_stats;
typedef enum {
PREVIEW_SUCCEEDED,
PREVIEW_TIMED_OUT,
PREVIEW_READ_ERROR
} ws_file_preview_stats_status;
extern ws_file_preview_stats_status
get_stats_for_preview(wtap *wth, ws_file_preview_stats *stats,
int *err, gchar **err_info);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __FILE_DIALOG_H__ */ |
C | wireshark/ui/firewall_rules.c | /* firewall_rules_dlg.c
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/*
* Generate firewall ACL rules based on packet addresses and ports.
* For directional rules, an outside interface is assumed.
*
* There may be better ways to present the information, e.g. all rules
* in one huge text window, or some sort of tree view.
*/
/*
* To add a new product, add syntax functions modify the products[] array.
*
* To add a new syntax function, add its prototype above the products[]
* array, and add the function below with all the others.
*/
/* Copied from gtk/firewall_rules.c */
#include "config.h"
#include <glib.h>
#include "epan/address.h"
#include "firewall_rules.h"
static void sf_ipfw_mac(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_netfilter_mac(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ios_std_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ios_ext_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ipfilter_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ipfw_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_netfilter_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_pf_ipv4(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
/* XXX - Can you addresses-only filters using WFW/netsh? */
static void sf_ios_ext_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ipfilter_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ipfw_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_netfilter_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_pf_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_netsh_port_old(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_netsh_port_new(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ios_ext_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ipfilter_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_ipfw_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_netfilter_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_pf_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_netsh_ipv4_port_old(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
static void sf_netsh_ipv4_port_new(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
typedef struct _fw_product_t {
const char *name;
const char *rule_hint;
const char *comment_pfx;
syntax_func mac_func;
syntax_func ipv4_func;
syntax_func port_func;
syntax_func ipv4_port_func;
gboolean does_inbound;
} fw_product;
static fw_product products[] = {
{ "Cisco IOS (standard)", "Change NUMBER to a valid ACL number.", "!",
NULL, sf_ios_std_ipv4, NULL, NULL, FALSE },
{ "Cisco IOS (extended)", "Change NUMBER to a valid ACL number.", "!",
NULL, sf_ios_ext_ipv4, sf_ios_ext_port, sf_ios_ext_ipv4_port, TRUE },
{ "IP Filter (ipfilter)", "Change le0 to a valid interface if needed.", "#",
NULL, sf_ipfilter_ipv4, sf_ipfilter_port, sf_ipfilter_ipv4_port, TRUE },
{ "IPFirewall (ipfw)", "", "#",
sf_ipfw_mac, sf_ipfw_ipv4, sf_ipfw_port, sf_ipfw_ipv4_port, TRUE },
{ "Netfilter (iptables)", "Change eth0 to a valid interface if needed.", "#",
sf_netfilter_mac, sf_netfilter_ipv4, sf_netfilter_port,
sf_netfilter_ipv4_port, TRUE },
{ "Packet Filter (pf)", "$ext_if should be set to a valid interface.", "#",
NULL, sf_pf_ipv4, sf_pf_port, sf_pf_ipv4_port, TRUE },
{ "Windows Firewall (netsh old syntax)", "", "#",
NULL, NULL, sf_netsh_port_old, sf_netsh_ipv4_port_old, FALSE },
{ "Windows Firewall (netsh new syntax)", "", "#",
NULL, NULL, sf_netsh_port_new, sf_netsh_ipv4_port_new, FALSE }
};
#define NUM_PRODS (sizeof(products) / sizeof(fw_product))
size_t firewall_product_count(void)
{
return NUM_PRODS;
}
const char *firewall_product_name(size_t product_idx)
{
if (product_idx >= NUM_PRODS) return "Unknown";
return products[product_idx].name;
}
const char *firewall_product_rule_hint(size_t product_idx)
{
if (product_idx >= NUM_PRODS) return "";
return products[product_idx].rule_hint;
}
const char *firewall_product_comment_prefix(size_t product_idx)
{
if (product_idx >= NUM_PRODS) return "";
return products[product_idx].comment_pfx;
}
syntax_func firewall_product_mac_func(size_t product_idx)
{
if (product_idx >= NUM_PRODS) return NULL;
return products[product_idx].mac_func;
}
syntax_func firewall_product_ipv4_func(size_t product_idx)
{
if (product_idx >= NUM_PRODS) return NULL;
return products[product_idx].ipv4_func;
}
syntax_func firewall_product_port_func(size_t product_idx)
{
if (product_idx >= NUM_PRODS) return NULL;
return products[product_idx].port_func;
}
syntax_func firewall_product_ipv4_port_func(size_t product_idx)
{
if (product_idx >= NUM_PRODS) return NULL;
return products[product_idx].ipv4_port_func;
}
gboolean firewall_product_does_inbound(size_t product_idx)
{
if (product_idx >= NUM_PRODS) return FALSE;
return products[product_idx].does_inbound;
}
/* MAC */
#define IPFW_RULE(deny) ((deny) ? "deny" : "allow")
#define IPFW_DIR(inbound) ((inbound) ? "in" : "out")
static void sf_ipfw_mac(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "add %s MAC %s any %s",
IPFW_RULE(deny), addr, IPFW_DIR(inbound));
}
#define NF_RULE(deny) ((deny) ? "DROP" : "ACCEPT")
#define NF_DIR(inbound) ((inbound) ? "INPUT" : "OUTPUT")
static void sf_netfilter_mac(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "iptables --append %s --in-interface eth0 --mac-source %s --jump %s",
NF_DIR(inbound), addr, NF_RULE(deny));
}
/* IPv4 */
#define IOS_RULE(deny) ((deny) ? "deny" : "permit")
static void sf_ios_std_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound _U_, gboolean deny) {
g_string_append_printf(rtxt, "access-list NUMBER %s host %s", IOS_RULE(deny), addr);
}
static void sf_ios_ext_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) {
if (inbound)
g_string_append_printf(rtxt, "access-list NUMBER %s ip host %s any", IOS_RULE(deny), addr);
else
g_string_append_printf(rtxt, "access-list NUMBER %s ip any host %s", IOS_RULE(deny), addr);
}
#define IPFILTER_RULE(deny) ((deny) ? "block" : "pass")
#define IPFILTER_DIR(inbound) ((inbound) ? "in" : "out")
static void sf_ipfilter_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "%s %s on le0 from %s to any",
IPFILTER_RULE(deny), IPFILTER_DIR(inbound), addr);
}
static void sf_ipfw_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "add %s ip from %s to any %s",
IPFW_RULE(deny), addr, IPFW_DIR(inbound));
}
#define NF_ADDR_DIR(inbound) ((inbound) ? "--source" : "--destination")
static void sf_netfilter_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "iptables --append %s --in-interface eth0 %s %s/32 --jump %s",
NF_DIR(inbound), NF_ADDR_DIR(inbound), addr, NF_RULE(deny));
}
#define PF_RULE(deny) ((deny) ? "block" : "pass")
#define PF_DIR(inbound) ((inbound) ? "in" : "out")
static void sf_pf_ipv4(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype _U_, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "%s %s quick on $ext_if from %s to any",
PF_RULE(deny), PF_DIR(inbound), addr);
}
/* Port */
#define RT_TCP_UDP(ptype) ((ptype) == PT_TCP ? "tcp" : "udp")
static void sf_ios_ext_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound _U_, gboolean deny) {
g_string_append_printf(rtxt, "access-list NUMBER %s %s any any eq %u",
IOS_RULE(deny), RT_TCP_UDP(ptype), port);
}
static void sf_ipfilter_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "%s %s on le0 proto %s from any to any port = %u",
IPFILTER_RULE(deny), IPFILTER_DIR(inbound), RT_TCP_UDP(ptype), port);
}
static void sf_ipfw_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "add %s %s from any to any %u %s",
IPFW_RULE(deny), RT_TCP_UDP(ptype), port, IPFW_DIR(inbound));
}
#define NF_PORT_DIR(inbound) ((inbound) ? "--source-port" : "--destination-port")
static void sf_netfilter_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "iptables --append %s --in-interface eth0 --protocol %s %s %u --jump %s",
NF_DIR(inbound), RT_TCP_UDP(ptype), NF_PORT_DIR(inbound), port, NF_RULE(deny));
}
static void sf_pf_port(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "%s %s quick on $ext_if proto %s from any to any port %u",
PF_RULE(deny), PF_DIR(inbound), RT_TCP_UDP(ptype), port);
}
#define NETSH_RULE_OLD(deny) ((deny) ? "DISABLE" : "ENABLE")
static void sf_netsh_port_old(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound _U_, gboolean deny) {
g_string_append_printf(rtxt, "add portopening %s %u Wireshark %s",
RT_TCP_UDP(ptype), port, NETSH_RULE_OLD(deny));
}
#define NETSH_RULE_NEW(deny) ((deny) ? "block" : "allow")
static void sf_netsh_port_new(GString *rtxt, gchar *addr _U_, guint32 port, port_type ptype, gboolean inbound _U_, gboolean deny) {
g_string_append_printf(rtxt, "add rule name=\"Wireshark\" dir=in action=%s protocol=%s localport=%u",
NETSH_RULE_NEW(deny), RT_TCP_UDP(ptype), port);
}
/* IPv4 + port */
static void sf_ios_ext_ipv4_port(GString *rtxt, gchar *addr, guint32 port _U_, port_type ptype, gboolean inbound, gboolean deny) {
if (inbound)
g_string_append_printf(rtxt, "access-list NUMBER %s %s host %s eq %u any", IOS_RULE(deny), RT_TCP_UDP(ptype), addr, port);
else
g_string_append_printf(rtxt, "access-list NUMBER %s %s any host %s eq %u", IOS_RULE(deny), RT_TCP_UDP(ptype), addr, port);
}
static void sf_ipfilter_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny) {
if (inbound)
g_string_append_printf(rtxt, "%s %s on le0 proto %s from %s port = %u to any",
IPFILTER_RULE(deny), IPFILTER_DIR(inbound), RT_TCP_UDP(ptype), addr, port);
else
g_string_append_printf(rtxt, "%s %s on le0 proto %s from any to %s port = %u",
IPFILTER_RULE(deny), IPFILTER_DIR(inbound), RT_TCP_UDP(ptype), addr, port);
}
static void sf_ipfw_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "add %s %s from %s %u to any %s",
IPFW_RULE(deny), RT_TCP_UDP(ptype), addr, port, IPFW_DIR(inbound));
}
static void sf_pf_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "%s %s quick on $ext_if proto %s from %s to any port %u",
PF_RULE(deny), PF_DIR(inbound), RT_TCP_UDP(ptype), addr, port);
}
static void sf_netfilter_ipv4_port(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny) {
g_string_append_printf(rtxt, "iptables --append %s --in-interface eth0 --protocol %s %s %s/32 %s %u --jump %s",
NF_DIR(inbound), RT_TCP_UDP(ptype), NF_ADDR_DIR(inbound), addr, NF_PORT_DIR(inbound), port, NF_RULE(deny));
}
static void sf_netsh_ipv4_port_old(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound _U_, gboolean deny) {
g_string_append_printf(rtxt, "add portopening %s %u Wireshark %s %s",
RT_TCP_UDP(ptype), port, NETSH_RULE_OLD(deny), addr);
}
static void sf_netsh_ipv4_port_new(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound _U_, gboolean deny) {
g_string_append_printf(rtxt, "add rule name=\"Wireshark\" dir=in action=%s protocol=%s localport=%u remoteip=%s",
NETSH_RULE_NEW(deny), RT_TCP_UDP(ptype), port, addr);
} |
C/C++ | wireshark/ui/firewall_rules.h | /** @file
*
* Produce ACL rules for various products from a packet.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 2006 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __UI_FIREWALL_RULES_H__
#define __UI_FIREWALL_RULES_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Rule types */
typedef enum {
RT_NONE,
RT_MAC_SRC,
RT_MAC_DST,
RT_IPv4_SRC,
RT_IPv4_DST,
RT_PORT_SRC,
RT_PORT_DST,
RT_IPv4_PORT_SRC,
RT_IPv4_PORT_DST,
NUM_RULE_TYPES
} rule_type_e;
/** Fetch the number of firewall products.
* @return The number of firewall products. Should be used as the index for
* the rest of the functions below.
*/
size_t firewall_product_count(void);
/** Product name
* Given an index, return the product name.
* @param product_idx Product index.
* @return Product name or "Unknown".
*/
const char *firewall_product_name(size_t product_idx);
/** Product rule hint
* Given an index, return the product's rule hint.
* @param product_idx Product index.
* @return Product rule hint, e.g. "Change le0 to a valid interface." or "".
*/
const char *firewall_product_rule_hint(size_t product_idx);
/** Comment prefix
* @param product_idx Product index.
* @return The comment prefix, e.g. "#" or an empty string.
*/
const char *firewall_product_comment_prefix(size_t product_idx);
/* Syntax function prototypes */
typedef void (*syntax_func)(GString *rtxt, gchar *addr, guint32 port, port_type ptype, gboolean inbound, gboolean deny);
/** MAC filter function
* @param product_idx Product index.
* @return A pointer to the MAC filter function or NULL.
*/
syntax_func firewall_product_mac_func(size_t product_idx);
/** IPv4 filter function
* @param product_idx Product index.
* @return A pointer to the IPv4 filter function or NULL.
*/
syntax_func firewall_product_ipv4_func(size_t product_idx);
/** Port filter function
* @param product_idx Product index.
* @return A pointer to the port filter function or NULL.
*/
syntax_func firewall_product_port_func(size_t product_idx);
/** IPv4+port filter function
* @param product_idx Product index.
* @return A pointer to the IPv4+port filter function or NULL.
*/
syntax_func firewall_product_ipv4_port_func(size_t product_idx);
/** Product inbound support
* Given an index, return the product's ability to support inbound rules.
* @param product_idx Product index.
* @return TRUE or FALSE.
*/
gboolean firewall_product_does_inbound(size_t product_idx);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __UI_FIREWALL_RULES_H__ */ |
C | wireshark/ui/help_url.c | /* help_url.c
*
* Some content from gtk/help_dlg.c by Laurent Deniel <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 2000 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <string.h>
#include <glib.h>
#include "help_url.h"
#include "urls.h"
#include "wsutil/filesystem.h"
#include <wsutil/ws_assert.h>
// To do:
// - Automatically generate part or all of this, e.g. by parsing
// the DocBook XML or the chunked HTML.
/*
* Open the help dialog and show a specific HTML help page.
*/
gchar *
user_guide_url(const gchar *page) {
GString *url = g_string_new("");
#if defined(_WIN32)
/*
* The User's Guide is in a directory named "Wireshark User's Guide" in
* the program directory.
*/
GString *ug_dir = g_string_new("");
g_string_printf(ug_dir, "%s\\Wireshark User's Guide", get_datafile_dir());
if (g_file_test(ug_dir->str, G_FILE_TEST_IS_DIR)) {
g_string_printf(url, "file:///%s/%s", ug_dir->str, page);
}
g_string_free(ug_dir, TRUE);
#else
char *path = g_build_filename(get_doc_dir(), "wsug_html_chunked", page, NULL);
if (g_file_test(path, G_FILE_TEST_IS_REGULAR)) {
/* try to open the HTML page from the filesystem */
g_string_printf(url, "file://%s", path);
}
g_free(path);
path = NULL;
#endif /* _WIN32 */
/* Fall back to wireshark.org. */
if (url->len == 0) {
g_string_printf(url, WS_DOCS_URL "wsug_html_chunked/%s", page);
}
return g_string_free(url, FALSE);
}
gchar *
topic_action_url(topic_action_e action)
{
gchar *url;
switch(action) {
/* pages online at www.wireshark.org */
case(ONLINEPAGE_HOME):
url = g_strdup(WS_HOME_PAGE_URL);
break;
case(ONLINEPAGE_WIKI):
url = g_strdup(WS_WIKI_HOME_URL);
break;
case(ONLINEPAGE_DOWNLOAD):
url = g_strdup(WS_DOWNLOAD_URL);
break;
case(ONLINEPAGE_DOCS):
url = g_strdup(WS_DOCS_URL);
break;
case(ONLINEPAGE_USERGUIDE):
url = g_strdup(WS_DOCS_URL "wsug_html_chunked/");
break;
case(ONLINEPAGE_FAQ):
url = g_strdup(WS_FAQ_URL);
break;
case(ONLINEPAGE_ASK):
url = g_strdup(WS_Q_AND_A_URL);
break;
case(ONLINEPAGE_SAMPLE_FILES):
url = g_strdup(WS_WIKI_URL("SampleCaptures"));
break;
case(ONLINEPAGE_CAPTURE_SETUP):
url = g_strdup(WS_WIKI_URL("CaptureSetup"));
break;
case(ONLINEPAGE_NETWORK_MEDIA):
url = g_strdup(WS_WIKI_URL("CaptureSetup/NetworkMedia"));
break;
case(ONLINEPAGE_SAMPLE_CAPTURES):
url = g_strdup(WS_WIKI_URL("SampleCaptures"));
break;
case(ONLINEPAGE_SECURITY):
url = g_strdup(WS_WIKI_URL("Security"));
break;
case(ONLINEPAGE_CHIMNEY):
url = g_strdup(WS_WIKI_URL("CaptureSetup/Offloading#chimney"));
break;
/* local manual pages */
case(LOCALPAGE_MAN_WIRESHARK):
url = doc_file_url("wireshark.html");
break;
case(LOCALPAGE_MAN_WIRESHARK_FILTER):
url = doc_file_url("wireshark-filter.html");
break;
case(LOCALPAGE_MAN_CAPINFOS):
url = doc_file_url("capinfos.html");
break;
case(LOCALPAGE_MAN_DUMPCAP):
url = doc_file_url("dumpcap.html");
break;
case(LOCALPAGE_MAN_EDITCAP):
url = doc_file_url("editcap.html");
break;
case(LOCALPAGE_MAN_MERGECAP):
url = doc_file_url("mergecap.html");
break;
case(LOCALPAGE_MAN_RAWSHARK):
url = doc_file_url("rawshark.html");
break;
case(LOCALPAGE_MAN_REORDERCAP):
url = doc_file_url("reordercap.html");
break;
case(LOCALPAGE_MAN_TEXT2PCAP):
url = doc_file_url("text2pcap.html");
break;
case(LOCALPAGE_MAN_TSHARK):
url = doc_file_url("tshark.html");
break;
/* local help pages (User's Guide) */
case(HELP_CONTENT):
url = user_guide_url( "index.html");
break;
case(HELP_CAPTURE_OPTIONS):
url = user_guide_url("ChCapCaptureOptions.html");
break;
case(HELP_CAPTURE_FILTERS_DIALOG):
url = user_guide_url("ChWorkDefineFilterSection.html");
break;
case(HELP_DISPLAY_FILTERS_DIALOG):
url = user_guide_url("ChWorkDefineFilterSection.html");
break;
case(HELP_FILTER_EXPRESSION_DIALOG):
url = user_guide_url("ChWorkFilterAddExpressionSection.html");
break;
case(HELP_COLORING_RULES_DIALOG):
url = user_guide_url("ChCustColorizationSection.html");
break;
case(HELP_CONFIG_PROFILES_DIALOG):
url = user_guide_url("ChCustConfigProfilesSection.html");
break;
case(HELP_PRINT_DIALOG):
url = user_guide_url("ChIOPrintSection.html");
break;
case(HELP_FIND_DIALOG):
url = user_guide_url("ChWorkFindPacketSection.html");
break;
case(HELP_FIREWALL_DIALOG):
url = user_guide_url("ChUseToolsMenuSection.html");
break;
case(HELP_GOTO_DIALOG):
url = user_guide_url("ChWorkGoToPacketSection.html");
break;
case(HELP_CAPTURE_OPTIONS_DIALOG):
url = user_guide_url("ChCapCaptureOptions.html");
break;
case(HELP_CAPTURE_INFO_DIALOG):
url = user_guide_url("ChCapRunningSection.html");
break;
case(HELP_CAPTURE_MANAGE_INTERFACES_DIALOG):
url = user_guide_url("ChCapManageInterfacesSection.html");
break;
case(HELP_ENABLED_PROTOCOLS_DIALOG):
url = user_guide_url("ChCustProtocolDissectionSection.html");
break;
case(HELP_ENABLED_HEURISTICS_DIALOG):
url = user_guide_url("ChCustProtocolDissectionSection.html");
break;
case(HELP_DECODE_AS_DIALOG):
url = user_guide_url("ChCustProtocolDissectionSection.html");
break;
case(HELP_DECODE_AS_SHOW_DIALOG):
url = user_guide_url("ChCustProtocolDissectionSection.html");
break;
case(HELP_FOLLOW_STREAM_DIALOG):
url = user_guide_url("ChAdvFollowStreamSection.html");
break;
case(HELP_SHOW_PACKET_BYTES_DIALOG):
url = user_guide_url("ChAdvShowPacketBytes.html");
break;
case(HELP_EXPERT_INFO_DIALOG):
url = user_guide_url("ChAdvExpert.html");
break;
case(HELP_EXTCAP_OPTIONS_DIALOG):
url = doc_file_url("extcap.html");
break;
case(HELP_STATS_SUMMARY_DIALOG):
url = user_guide_url("ChStatSummary.html");
break;
case(HELP_STATS_PROTO_HIERARCHY_DIALOG):
url = user_guide_url("ChStatHierarchy.html");
break;
case(HELP_STATS_ENDPOINTS_DIALOG):
url = user_guide_url("ChStatEndpoints.html");
break;
case(HELP_STATS_CONVERSATIONS_DIALOG):
url = user_guide_url("ChStatConversations.html");
break;
case(HELP_STATS_IO_GRAPH_DIALOG):
url = user_guide_url("ChStatIOGraphs.html");
break;
case(HELP_STATS_LTE_MAC_TRAFFIC_DIALOG):
url = user_guide_url("ChTelLTE.html#ChTelLTEMACTraffic");
break;
case(HELP_STATS_LTE_RLC_TRAFFIC_DIALOG):
url = user_guide_url("ChTelLTE.html#ChTelLTERLCTraffic");
break;
case(HELP_STATS_TCP_STREAM_GRAPHS_DIALOG):
url = user_guide_url("ChStatTCPStreamGraphs.html");
break;
case(HELP_STATS_WLAN_TRAFFIC_DIALOG):
url = user_guide_url("ChWirelessWLANTraffic.html");
break;
case(HELP_FILESET_DIALOG):
url = user_guide_url("ChIOFileSetSection.html");
break;
case(HELP_CAPTURE_INTERFACE_OPTIONS_DIALOG):
url = user_guide_url("ChCustPreferencesSection.html#ChCustInterfaceOptionsSection");
break;
case(HELP_PREFERENCES_DIALOG):
url = user_guide_url("ChCustPreferencesSection.html");
break;
case(HELP_EXPORT_FILE_DIALOG):
case(HELP_EXPORT_FILE_WIN32_DIALOG):
url = user_guide_url("ChIOExportSection.html");
break;
case(HELP_EXPORT_BYTES_DIALOG):
url = user_guide_url("ChIOExportSection.html#ChIOExportSelectedDialog");
break;
case(HELP_EXPORT_OBJECT_LIST):
url = user_guide_url("ChIOExportSection.html#ChIOExportObjectsDialog");
break;
case(HELP_OPEN_DIALOG):
case(HELP_OPEN_WIN32_DIALOG):
url = user_guide_url("ChIOOpenSection.html");
break;
case(HELP_MERGE_DIALOG):
case(HELP_MERGE_WIN32_DIALOG):
url = user_guide_url("ChIOMergeSection.html");
break;
case(HELP_IMPORT_DIALOG):
url = user_guide_url("ChIOImportSection.html");
break;
case(HELP_SAVE_DIALOG):
case(HELP_SAVE_WIN32_DIALOG):
url = user_guide_url("ChIOSaveSection.html");
break;
case(HELP_TIME_SHIFT_DIALOG):
url = user_guide_url("ChWorkShiftTimePacketSection.html");
break;
case(HELP_TELEPHONY_VOIP_CALLS_DIALOG):
url = user_guide_url("ChTelVoipCalls.html");
break;
case(HELP_TELEPHONY_RTP_ANALYSIS_DIALOG):
url = user_guide_url("ChTelRTP.html#ChTelRTPAnalysis");
break;
case(HELP_TELEPHONY_RTP_STREAMS_DIALOG):
url = user_guide_url("ChTelRTP.html#ChTelRTPStreams");
break;
case(HELP_NEW_PACKET_DIALOG):
url = user_guide_url("ChapterWork.html#ChWorkPacketSepView");
break;
case(HELP_IAX2_ANALYSIS_DIALOG):
url = user_guide_url("ChTelIAX2Analysis.html");
break;
case(HELP_TELEPHONY_RTP_PLAYER_DIALOG):
url = user_guide_url("ChTelRTP.html#ChTelRtpPlayer");
break;
case(HELP_STAT_FLOW_GRAPH):
url = user_guide_url("ChStatFlowGraph.html");
break;
case(TOPIC_ACTION_NONE):
default:
url = g_strdup(WS_HOME_PAGE_URL);
ws_assert_not_reached();
}
return url;
} |
C/C++ | wireshark/ui/help_url.h | /** @file
*
* Some content from gtk/help_dlg.h by Laurent Deniel <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 2000 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later*
*/
#ifndef __HELP_URL_H__
#define __HELP_URL_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** @file help_url.h
* "Help" URLs.
*/
typedef enum {
TOPIC_ACTION_NONE,
/* pages online at www.wireshark.org */
ONLINEPAGE_HOME,
ONLINEPAGE_WIKI,
ONLINEPAGE_USERGUIDE,
ONLINEPAGE_FAQ,
ONLINEPAGE_DOWNLOAD,
ONLINEPAGE_DOCS,
ONLINEPAGE_SAMPLE_FILES,
ONLINEPAGE_CAPTURE_SETUP,
ONLINEPAGE_NETWORK_MEDIA,
ONLINEPAGE_SAMPLE_CAPTURES,
ONLINEPAGE_SECURITY,
ONLINEPAGE_CHIMNEY,
ONLINEPAGE_ASK,
/* local manual pages */
LOCALPAGE_MAN_WIRESHARK = 100,
LOCALPAGE_MAN_WIRESHARK_FILTER,
LOCALPAGE_MAN_CAPINFOS,
LOCALPAGE_MAN_DUMPCAP,
LOCALPAGE_MAN_EDITCAP,
LOCALPAGE_MAN_MERGECAP,
LOCALPAGE_MAN_RAWSHARK,
LOCALPAGE_MAN_REORDERCAP,
LOCALPAGE_MAN_TEXT2PCAP,
LOCALPAGE_MAN_TSHARK,
/* help pages (textfiles or local HTML User's Guide) */
HELP_CONTENT = 200,
HELP_GETTING_STARTED, /* currently unused */
HELP_CAPTURE_OPTIONS, /* currently unused */
HELP_CAPTURE_FILTERS_DIALOG,
HELP_DISPLAY_FILTERS_DIALOG,
HELP_FILTER_EXPRESSION_DIALOG,
HELP_COLORING_RULES_DIALOG,
HELP_CONFIG_PROFILES_DIALOG,
HELP_PRINT_DIALOG,
HELP_FIND_DIALOG,
HELP_FILESET_DIALOG,
HELP_FIREWALL_DIALOG,
HELP_GOTO_DIALOG,
HELP_CAPTURE_OPTIONS_DIALOG,
HELP_CAPTURE_MANAGE_INTERFACES_DIALOG,
HELP_ENABLED_PROTOCOLS_DIALOG,
HELP_ENABLED_HEURISTICS_DIALOG,
HELP_DECODE_AS_DIALOG,
HELP_DECODE_AS_SHOW_DIALOG,
HELP_FOLLOW_STREAM_DIALOG,
HELP_SHOW_PACKET_BYTES_DIALOG,
HELP_EXPERT_INFO_DIALOG,
HELP_EXTCAP_OPTIONS_DIALOG,
HELP_STATS_SUMMARY_DIALOG,
HELP_STATS_PROTO_HIERARCHY_DIALOG,
HELP_STATS_ENDPOINTS_DIALOG,
HELP_STATS_CONVERSATIONS_DIALOG,
HELP_STATS_IO_GRAPH_DIALOG,
HELP_STATS_LTE_MAC_TRAFFIC_DIALOG,
HELP_STATS_LTE_RLC_TRAFFIC_DIALOG,
HELP_STATS_TCP_STREAM_GRAPHS_DIALOG,
HELP_STATS_WLAN_TRAFFIC_DIALOG,
HELP_CAPTURE_INTERFACE_OPTIONS_DIALOG,
HELP_PREFERENCES_DIALOG,
HELP_CAPTURE_INFO_DIALOG,
HELP_EXPORT_FILE_DIALOG,
HELP_EXPORT_BYTES_DIALOG,
HELP_EXPORT_OBJECT_LIST,
HELP_OPEN_DIALOG,
HELP_MERGE_DIALOG,
HELP_IMPORT_DIALOG,
HELP_SAVE_DIALOG,
HELP_EXPORT_FILE_WIN32_DIALOG,
HELP_OPEN_WIN32_DIALOG,
HELP_MERGE_WIN32_DIALOG,
HELP_SAVE_WIN32_DIALOG,
HELP_TIME_SHIFT_DIALOG,
HELP_TELEPHONY_VOIP_CALLS_DIALOG,
HELP_TELEPHONY_RTP_ANALYSIS_DIALOG,
HELP_TELEPHONY_RTP_STREAMS_DIALOG,
HELP_NEW_PACKET_DIALOG,
HELP_IAX2_ANALYSIS_DIALOG,
HELP_TELEPHONY_RTP_PLAYER_DIALOG,
HELP_STAT_FLOW_GRAPH
} topic_action_e;
/** Given a page in the Wireshark User's Guide return its URL. If the
* attempt succeeds NULL will be returned.
*
* @param page A page in the User's Guide.
* @return A static URL or NULL. A non-NULL return value must be freed
* with g_free().
*/
gchar *user_guide_url(const gchar *page);
/** Given a topic action return its URL. If the attempt succeeds NULL
* will be returned.
*
* @param action Topic action.
* @return A static URL or NULL. A non-NULL return value must be freed
* with g_free().
*/
gchar *topic_action_url(topic_action_e action);
/** Open a specific topic (create a "Help" dialog box or open a webpage).
*
* @param topic the topic to display
*/
void topic_action(topic_action_e topic);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __HELP_URL_H__ */ |
C | wireshark/ui/iface_lists.c | /* iface_lists.c
* Code to manage the global list of interfaces and to update widgets/windows
* displaying items from those lists
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#ifdef HAVE_LIBPCAP
#include <string.h>
#include <glib.h>
#include <epan/prefs.h>
#include <epan/to_str.h>
#include <wsutil/wslog.h>
#include "ui/capture_ui_utils.h"
#include "ui/capture_globals.h"
#include "ui/iface_lists.h"
/*
* Try to populate the given device with options (like capture filter) from
* the capture options that are in use for an existing capture interface.
* Returns TRUE if the interface is selected for capture and FALSE otherwise.
*/
static gboolean
fill_from_ifaces (interface_t *device)
{
interface_options *interface_opts;
guint i;
for (i = 0; i < global_capture_opts.ifaces->len; i++) {
interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
if (strcmp(interface_opts->name, device->name) != 0) {
continue;
}
#if defined(HAVE_PCAP_CREATE)
device->buffer = interface_opts->buffer_size;
device->monitor_mode_enabled = interface_opts->monitor_mode;
#endif
device->pmode = interface_opts->promisc_mode;
device->has_snaplen = interface_opts->has_snaplen;
device->snaplen = interface_opts->snaplen;
g_free(device->cfilter);
device->cfilter = g_strdup(interface_opts->cfilter);
device->timestamp_type = g_strdup(interface_opts->timestamp_type);
if (interface_opts->linktype != -1) {
device->active_dlt = interface_opts->linktype;
}
return TRUE;
}
return FALSE;
}
static gchar *
get_iface_display_name(const gchar *description, const if_info_t *if_info)
{
/* Do we have a user-supplied description? */
if (description && description[0]) {
/*
* Yes - show both the user-supplied description and a name for the
* interface.
*/
#ifdef _WIN32
/*
* On Windows, if we have a friendly name, just show it
* rather than the name, as the name is a string made out
* of the device GUID, and not at all friendly.
*/
gchar *if_string = if_info->friendly_name ? if_info->friendly_name : if_info->name;
return ws_strdup_printf("%s: %s", description, if_string);
#else
/*
* On UN*X, show the interface name; it's short and somewhat
* friendly, and many UN*X users are used to interface names,
* so we should show it.
*/
return ws_strdup_printf("%s: %s", description, if_info->name);
#endif
}
if (if_info->friendly_name) {
/* We have a friendly name from the OS. */
#ifdef _WIN32
/*
* On Windows, if we have a friendly name, just show it,
* don't show the name, as that's a string made out of
* the device GUID, and not at all friendly.
*/
return ws_strdup_printf("%s", if_info->friendly_name);
#else
/*
* On UN*X, if we have a friendly name, show it along
* with the interface name; the interface name is short
* and somewhat friendly, and many UN*X users are used
* to interface names, so we should show it.
*/
return ws_strdup_printf("%s: %s", if_info->friendly_name, if_info->name);
#endif
}
if (if_info->vendor_description) {
/* We have a device description from libpcap. */
return ws_strdup_printf("%s: %s", if_info->vendor_description, if_info->name);
}
/* No additional descriptions found. */
return g_strdup(if_info->name);
}
/*
* Fetch the list of local interfaces with capture_interface_list()
* and set the list of "all interfaces" in *capture_opts to include
* those interfaces.
*/
void
scan_local_interfaces(void (*update_cb)(void))
{
scan_local_interfaces_filtered((GList *)0, update_cb);
}
/*
* Fetch the list of local interfaces with capture_interface_list()
* and set the list of "all interfaces" in *capture_opts to include
* those interfaces.
*/
void
scan_local_interfaces_filtered(GList * allowed_types, void (*update_cb)(void))
{
GList *if_entry, *lt_entry, *if_list;
if_info_t *if_info, temp;
gchar *descr;
if_capabilities_t *caps=NULL;
gboolean monitor_mode;
GSList *curr_addr;
int ips = 0, i;
guint count = 0, j;
if_addr_t *addr, *temp_addr;
link_row *link = NULL;
data_link_info_t *data_link_info;
interface_t device;
GString *ip_str = NULL;
interface_options *interface_opts;
gboolean found = FALSE;
static gboolean running = FALSE;
GHashTable *selected_devices;
if (running) {
/* scan_local_interfaces internally calls update_cb to process UI events
to avoid stuck UI while running possibly slow operations. A side effect
of this is that new interface changes can be detected before completing
the last one.
This return avoids recursive scan_local_interfaces operation. */
return;
}
running = TRUE;
/*
* Clear list of known interfaces (all_ifaces) that will be re-discovered on
* scanning, but remember their selection state.
*
* XXX shouldn't this copy settings (like capture filter) from the "old"
* device to the "new" device? Refreshing the interfaces list should
* probably just remove disappeared devices and add discovered devices.
*/
selected_devices = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
if (global_capture_opts.all_ifaces->len > 0) {
for (i = (int)global_capture_opts.all_ifaces->len-1; i >= 0; i--) {
device = g_array_index(global_capture_opts.all_ifaces, interface_t, i);
if (device.local && device.type != IF_PIPE && device.type != IF_STDIN) {
global_capture_opts.all_ifaces = g_array_remove_index(global_capture_opts.all_ifaces, i);
/*
* Device is about to be destroyed, unmark as selected. It will
* be reselected on rediscovery.
*/
if (device.selected) {
gchar *device_name = g_strdup(device.name);
/* g_hash_table_add() only exists since 2.32. */
g_hash_table_replace(selected_devices, device_name, device_name);
global_capture_opts.num_selected--;
}
capture_opts_free_interface_t(&device);
}
}
}
/* Retrieve list of interface information (if_info_t) into if_list. */
g_free(global_capture_opts.ifaces_err_info);
if_list = capture_interface_list(&global_capture_opts.ifaces_err,
&global_capture_opts.ifaces_err_info,
update_cb);
count = 0;
/*
* For each discovered interface name, create a new device and add extra
* information (like supported DLTs, assigned IP addresses).
*/
for (if_entry = if_list; if_entry != NULL; if_entry = g_list_next(if_entry)) {
memset(&device, 0, sizeof(device));
if_info = (if_info_t *)if_entry->data;
ips = 0;
if (strstr(if_info->name, "rpcap:")) {
continue;
}
/* Filter out all interfaces, which are not allowed to be scanned */
if (allowed_types != NULL)
{
if(g_list_find(allowed_types, GUINT_TO_POINTER((guint) if_info->type)) == NULL) {
continue;
}
}
device.name = g_strdup(if_info->name);
device.friendly_name = g_strdup(if_info->friendly_name);
device.vendor_description = g_strdup(if_info->vendor_description);
device.hidden = FALSE;
memset(&temp, 0, sizeof(temp));
temp.name = g_strdup(if_info->name);
temp.friendly_name = g_strdup(if_info->friendly_name);
temp.vendor_description = g_strdup(if_info->vendor_description);
temp.loopback = if_info->loopback;
temp.type = if_info->type;
temp.extcap = g_strdup(if_info->extcap);
/* Is this interface hidden and, if so, should we include it anyway? */
descr = capture_dev_user_descr_find(if_info->name);
device.display_name = get_iface_display_name(descr, if_info);
g_free(descr);
device.selected = FALSE;
if (prefs_is_capture_device_hidden(if_info->name)) {
device.hidden = TRUE;
}
device.type = if_info->type;
monitor_mode = prefs_capture_device_monitor_mode(if_info->name);
caps = capture_get_if_capabilities(if_info->name, monitor_mode, NULL, NULL, NULL, update_cb);
ip_str = g_string_new("");
for (; (curr_addr = g_slist_nth(if_info->addrs, ips)) != NULL; ips++) {
temp_addr = g_new0(if_addr_t, 1);
if (ips != 0) {
g_string_append(ip_str, "\n");
}
addr = (if_addr_t *)curr_addr->data;
if (addr) {
address addr_str;
char* temp_addr_str = NULL;
temp_addr->ifat_type = addr->ifat_type;
switch (addr->ifat_type) {
case IF_AT_IPv4:
temp_addr->addr.ip4_addr = addr->addr.ip4_addr;
set_address(&addr_str, AT_IPv4, 4, &addr->addr.ip4_addr);
temp_addr_str = address_to_str(NULL, &addr_str);
g_string_append(ip_str, temp_addr_str);
break;
case IF_AT_IPv6:
memcpy(temp_addr->addr.ip6_addr, addr->addr.ip6_addr, sizeof(addr->addr));
set_address(&addr_str, AT_IPv6, 16, addr->addr.ip6_addr);
temp_addr_str = address_to_str(NULL, &addr_str);
g_string_append(ip_str, temp_addr_str);
break;
default:
/* In case we add non-IP addresses */
break;
}
wmem_free(NULL, temp_addr_str);
} else {
g_free(temp_addr);
temp_addr = NULL;
}
if (temp_addr) {
temp.addrs = g_slist_append(temp.addrs, temp_addr);
}
}
device.addresses = g_strdup(ip_str->str);
g_string_free(ip_str, TRUE);
#ifdef HAVE_PCAP_REMOTE
device.local = TRUE;
device.remote_opts.src_type = CAPTURE_IFLOCAL;
device.remote_opts.remote_host_opts.remote_host = g_strdup(global_capture_opts.default_options.remote_host);
device.remote_opts.remote_host_opts.remote_port = g_strdup(global_capture_opts.default_options.remote_port);
device.remote_opts.remote_host_opts.auth_type = global_capture_opts.default_options.auth_type;
device.remote_opts.remote_host_opts.auth_username = g_strdup(global_capture_opts.default_options.auth_username);
device.remote_opts.remote_host_opts.auth_password = g_strdup(global_capture_opts.default_options.auth_password);
device.remote_opts.remote_host_opts.datatx_udp = global_capture_opts.default_options.datatx_udp;
device.remote_opts.remote_host_opts.nocap_rpcap = global_capture_opts.default_options.nocap_rpcap;
device.remote_opts.remote_host_opts.nocap_local = global_capture_opts.default_options.nocap_local;
#endif
#ifdef HAVE_PCAP_SETSAMPLING
device.remote_opts.sampling_method = global_capture_opts.default_options.sampling_method;
device.remote_opts.sampling_param = global_capture_opts.default_options.sampling_param;
#endif
device.links = NULL;
if (caps != NULL) {
#if defined(HAVE_PCAP_CREATE)
device.monitor_mode_enabled = monitor_mode;
device.monitor_mode_supported = caps->can_set_rfmon;
#endif
/*
* Process the list of link-layer header types.
*/
for (lt_entry = caps->data_link_types; lt_entry != NULL; lt_entry = g_list_next(lt_entry)) {
data_link_info = (data_link_info_t *)lt_entry->data;
link = g_new(link_row, 1);
if (data_link_info->description != NULL) {
link->dlt = data_link_info->dlt;
link->name = g_strdup(data_link_info->description);
} else {
link->dlt = -1;
link->name = ws_strdup_printf("%s (not supported)", data_link_info->name);
}
device.links = g_list_append(device.links, link);
}
/*
* Set the active DLT for the device appropriately.
*/
set_active_dlt(&device, global_capture_opts.default_options.linktype);
} else {
#if defined(HAVE_PCAP_CREATE)
device.monitor_mode_enabled = FALSE;
device.monitor_mode_supported = FALSE;
#endif
device.active_dlt = -1;
}
device.no_addresses = ips;
device.local = TRUE;
device.if_info = temp;
device.last_packets = 0;
if (!capture_dev_user_pmode_find(if_info->name, &device.pmode)) {
device.pmode = global_capture_opts.default_options.promisc_mode;
}
if (!capture_dev_user_snaplen_find(if_info->name, &device.has_snaplen,
&device.snaplen)) {
device.has_snaplen = global_capture_opts.default_options.has_snaplen;
device.snaplen = global_capture_opts.default_options.snaplen;
}
device.cfilter = g_strdup(global_capture_opts.default_options.cfilter);
device.timestamp_type = g_strdup(global_capture_opts.default_options.timestamp_type);
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
if ((device.buffer = capture_dev_user_buffersize_find(if_info->name)) == -1) {
device.buffer = global_capture_opts.default_options.buffer_size;
}
#endif
/* Copy interface options for active capture devices. */
gboolean selected = fill_from_ifaces(&device);
/* Restore device selection (for next capture). */
if (!device.selected && (selected || g_hash_table_lookup(selected_devices, device.name))) {
device.selected = TRUE;
global_capture_opts.num_selected++;
}
/* Extcap devices start with no cached args */
device.external_cap_args_settings = NULL;
if (global_capture_opts.all_ifaces->len <= count) {
g_array_append_val(global_capture_opts.all_ifaces, device);
count = global_capture_opts.all_ifaces->len;
} else {
g_array_insert_val(global_capture_opts.all_ifaces, count, device);
}
if (caps != NULL) {
free_if_capabilities(caps);
}
count++;
}
free_interface_list(if_list);
/*
* Pipes and stdin are not really discoverable interfaces, so re-add them to
* the list of all interfaces (all_ifaces).
*/
for (j = 0; j < global_capture_opts.ifaces->len; j++) {
interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
found = FALSE;
for (i = 0; i < (int)global_capture_opts.all_ifaces->len; i++) {
device = g_array_index(global_capture_opts.all_ifaces, interface_t, i);
/* Filter out all interfaces, which are not allowed to be scanned */
if (allowed_types != NULL && g_list_find(allowed_types, GINT_TO_POINTER(interface_opts->if_type)) == NULL) {
continue;
}
if (strcmp(device.name, interface_opts->name) == 0) {
found = TRUE;
break;
}
}
if (!found) { /* new interface, maybe a pipe */
memset(&device, 0, sizeof(device));
device.name = g_strdup(interface_opts->name);
device.vendor_description = g_strdup(interface_opts->hardware);
device.display_name = interface_opts->descr ?
ws_strdup_printf("%s: %s", device.name, interface_opts->descr) :
g_strdup(device.name);
device.hidden = FALSE;
device.selected = TRUE;
device.type = interface_opts->if_type;
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
device.buffer = interface_opts->buffer_size;
#endif
#if defined(HAVE_PCAP_CREATE)
device.monitor_mode_enabled = interface_opts->monitor_mode;
device.monitor_mode_supported = FALSE;
#endif
device.pmode = interface_opts->promisc_mode;
device.has_snaplen = interface_opts->has_snaplen;
device.snaplen = interface_opts->snaplen;
device.cfilter = g_strdup(interface_opts->cfilter);
device.timestamp_type = g_strdup(interface_opts->timestamp_type);
device.active_dlt = interface_opts->linktype;
device.addresses = NULL;
device.no_addresses = 0;
device.last_packets = 0;
device.links = NULL;
device.local = TRUE;
device.if_info.name = g_strdup(interface_opts->name);
device.if_info.friendly_name = NULL;
device.if_info.vendor_description = g_strdup(interface_opts->descr);
device.if_info.addrs = NULL;
device.if_info.loopback = FALSE;
device.if_info.extcap = g_strdup(interface_opts->extcap);
g_array_append_val(global_capture_opts.all_ifaces, device);
global_capture_opts.num_selected++;
}
}
g_hash_table_destroy(selected_devices);
running = FALSE;
}
/*
* Get the global interface list. Generate it if we haven't done so
* already. This can be quite time consuming the first time, so
* record how long it takes in the info log.
*/
void
fill_in_local_interfaces(void(*update_cb)(void))
{
fill_in_local_interfaces_filtered((GList *)0, update_cb);
}
/*
* Get the global interface list. Generate it if we haven't done so
* already. This can be quite time consuming the first time, so
* record how long it takes in the info log.
*/
void
fill_in_local_interfaces_filtered(GList * filter_list, void(*update_cb)(void))
{
gint64 start_time;
double elapsed;
static gboolean initialized = FALSE;
/* record the time we started, so we can log total time later */
start_time = g_get_monotonic_time();
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "fill_in_local_interfaces() starts");
if (!initialized) {
/* do the actual work */
scan_local_interfaces_filtered(filter_list, update_cb);
initialized = TRUE;
}
/* log how long it took */
elapsed = (g_get_monotonic_time() - start_time) / 1e6;
ws_log(LOG_DOMAIN_MAIN, LOG_LEVEL_INFO, "fill_in_local_interfaces() ends, taking %.3fs", elapsed);
}
void
hide_interface(gchar* new_hide)
{
gchar *tok;
guint i;
interface_t *device;
gboolean found = FALSE;
GList *hidden_devices = NULL, *entry;
if (new_hide != NULL) {
for (tok = strtok (new_hide, ","); tok; tok = strtok(NULL, ",")) {
hidden_devices = g_list_append(hidden_devices, tok);
}
}
for (i = 0; i < global_capture_opts.all_ifaces->len; i++) {
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
found = FALSE;
for (entry = hidden_devices; entry != NULL; entry = g_list_next(entry)) {
if (strcmp((char *)entry->data, device->name)==0) {
device->hidden = TRUE;
if (device->selected) {
device->selected = FALSE;
global_capture_opts.num_selected--;
}
found = TRUE;
break;
}
}
if (!found) {
device->hidden = FALSE;
}
}
g_list_free(hidden_devices);
g_free(new_hide);
}
void
update_local_interfaces(void)
{
interface_t *device;
gchar *descr;
guint i;
for (i = 0; i < global_capture_opts.all_ifaces->len; i++) {
device = &g_array_index(global_capture_opts.all_ifaces, interface_t, i);
device->type = capture_dev_user_linktype_find(device->name);
g_free(device->display_name);
descr = capture_dev_user_descr_find(device->name);
device->display_name = get_iface_display_name(descr, &device->if_info);
g_free (descr);
device->hidden = prefs_is_capture_device_hidden(device->name);
fill_from_ifaces(device);
}
}
#endif /* HAVE_LIBPCAP */ |
C/C++ | wireshark/ui/iface_lists.h | /** @file
*
* Declarations of routines to manage the global list of interfaces and to
* update widgets/windows displaying items from those lists
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __IFACE_LISTS_H__
#define __IFACE_LISTS_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifdef HAVE_LIBPCAP
/*
* Get the global interface list. Generate it if we haven't
* done so already.
*/
extern void fill_in_local_interfaces(void(*update_cb)(void));
/*
* Get the global interface list. Generate it if we haven't
* done so already.
* @param allowed_types only fill in types provided by the list
*/
extern void fill_in_local_interfaces_filtered(GList * allowed_types, void(*update_cb)(void));
/*
* Update the global interface list.
*/
extern void scan_local_interfaces(void (*update_cb)(void));
/*
* Update the global interface list.
* @param allowed_types only fill in types provided by the list
*/
extern void scan_local_interfaces_filtered(GList * allowed_types, void (*update_cb)(void));
/*
* Hide the interfaces
*/
extern void hide_interface(gchar* new_hide);
/*
* Update the global interface list from preferences.
*/
extern void update_local_interfaces(void);
#endif /* HAVE_LIBPCAP */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __IFACE_LISTS_H__ */ |
C | wireshark/ui/iface_toolbar.c | /* iface_toolbar.cpp
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include "iface_toolbar.h"
static iface_toolbar_add_cb_t iface_toolbar_add_cb;
static iface_toolbar_remove_cb_t iface_toolbar_remove_cb;
void iface_toolbar_add(const iface_toolbar *toolbar)
{
if (iface_toolbar_add_cb) {
iface_toolbar_add_cb(toolbar);
}
}
void iface_toolbar_remove(const gchar *menu_title)
{
if (iface_toolbar_remove_cb) {
iface_toolbar_remove_cb(menu_title);
}
}
gboolean iface_toolbar_use(void)
{
return iface_toolbar_add_cb ? TRUE : FALSE;
}
void iface_toolbar_register_cb(iface_toolbar_add_cb_t add_cb, iface_toolbar_remove_cb_t remove_cb)
{
iface_toolbar_add_cb = add_cb;
iface_toolbar_remove_cb = remove_cb;
} |
C/C++ | wireshark/ui/iface_toolbar.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __IFACE_TOOLBAR_H__
#define __IFACE_TOOLBAR_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef enum {
INTERFACE_TYPE_UNKNOWN,
INTERFACE_TYPE_BOOLEAN,
INTERFACE_TYPE_BUTTON,
INTERFACE_TYPE_SELECTOR,
INTERFACE_TYPE_STRING
} iface_toolbar_ctrl_type;
typedef enum {
INTERFACE_ROLE_UNKNOWN,
INTERFACE_ROLE_CONTROL,
INTERFACE_ROLE_HELP,
INTERFACE_ROLE_LOGGER,
INTERFACE_ROLE_RESTORE
} iface_toolbar_ctrl_role;
typedef struct _iface_toolbar_value {
int num;
gchar *value;
gchar *display;
gboolean is_default;
} iface_toolbar_value;
typedef struct _iface_toolbar_control {
int num;
iface_toolbar_ctrl_type ctrl_type;
iface_toolbar_ctrl_role ctrl_role;
gchar *display;
gchar *validation;
gboolean is_required;
gchar *tooltip;
gchar *placeholder;
union {
gboolean boolean;
gchar *string;
} default_value;
GList *values;
} iface_toolbar_control;
typedef struct _iface_toolbar {
gchar *menu_title;
gchar *help;
GList *ifnames;
GList *controls;
} iface_toolbar;
typedef void (*iface_toolbar_add_cb_t)(const iface_toolbar *);
typedef void (*iface_toolbar_remove_cb_t)(const gchar *);
void iface_toolbar_add(const iface_toolbar *toolbar);
void iface_toolbar_remove(const gchar *menu_title);
gboolean iface_toolbar_use(void);
void iface_toolbar_register_cb(iface_toolbar_add_cb_t, iface_toolbar_remove_cb_t);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __IFACE_TOOLBAR_H__ */ |
C | wireshark/ui/io_graph_item.c | /* io_graph_item.h
* Definitions and functions for I/O graph items
*
* Copied from gtk/io_stat.c, (c) 2002 Ronnie Sahlberg
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <epan/epan_dissect.h>
#include "ui/io_graph_item.h"
int get_io_graph_index(packet_info *pinfo, int interval) {
nstime_t time_delta;
/*
* Find in which interval this is supposed to go and store the interval index as idx
*/
time_delta = pinfo->rel_ts;
if (time_delta.nsecs<0) {
time_delta.secs--;
time_delta.nsecs += 1000000000;
}
if (time_delta.secs<0) {
return -1;
}
return (int) ((time_delta.secs*1000 + time_delta.nsecs/1000000) / interval);
}
GString *check_field_unit(const char *field_name, int *hf_index, io_graph_item_unit_t item_unit)
{
GString *err_str = NULL;
if (item_unit >= IOG_ITEM_UNIT_CALC_SUM) {
header_field_info *hfi;
const char *item_unit_names[NUM_IOG_ITEM_UNITS+1] = {
"Packets",
"Bytes",
"Bits",
"SUM",
"COUNT FRAMES",
"COUNT FIELDS",
"MAX",
"MIN",
"AVG",
"LOAD",
NULL
};
/* There was no field specified */
if ((field_name == NULL) || (field_name[0] == 0)) {
err_str = g_string_new("You didn't specify a field name.");
return err_str;
}
/* The field could not be found */
hfi = proto_registrar_get_byname(field_name);
if (hfi == NULL) {
err_str = g_string_new("");
g_string_printf(err_str, "There is no field named '%s'.", field_name);
return err_str;
}
if (hf_index) *hf_index = hfi->id;
/* Check that the type is compatible */
switch (hfi->type) {
case FT_UINT8:
case FT_UINT16:
case FT_UINT24:
case FT_UINT32:
case FT_UINT64:
case FT_INT8:
case FT_INT16:
case FT_INT24:
case FT_INT32:
case FT_INT64:
case FT_FLOAT:
case FT_DOUBLE:
/* These values support all calculations except LOAD */
switch (item_unit) {
case IOG_ITEM_UNIT_CALC_LOAD:
err_str = g_string_new("LOAD is only supported for relative-time fields.");
default:
break;
}
/* These types support all calculations */
break;
case FT_RELATIVE_TIME:
/* This type only supports COUNT, MAX, MIN, AVG */
switch (item_unit) {
case IOG_ITEM_UNIT_CALC_SUM:
case IOG_ITEM_UNIT_CALC_FRAMES:
case IOG_ITEM_UNIT_CALC_FIELDS:
case IOG_ITEM_UNIT_CALC_MAX:
case IOG_ITEM_UNIT_CALC_MIN:
case IOG_ITEM_UNIT_CALC_AVERAGE:
case IOG_ITEM_UNIT_CALC_LOAD:
break;
default:
ws_assert(item_unit < NUM_IOG_ITEM_UNITS);
err_str = g_string_new("");
g_string_printf(err_str, "\"%s\" is a relative-time field. %s calculations are not supported on it.",
field_name,
item_unit_names[item_unit]);
}
break;
default:
if ((item_unit != IOG_ITEM_UNIT_CALC_FRAMES) &&
(item_unit != IOG_ITEM_UNIT_CALC_FIELDS)) {
err_str = g_string_new("");
g_string_printf(err_str, "\"%s\" doesn't have integral or float values. %s calculations are not supported on it.",
field_name,
item_unit_names[item_unit]);
}
break;
}
}
return err_str;
}
// Adapted from get_it_value in gtk/io_stat.c.
double get_io_graph_item(const io_graph_item_t *items_, io_graph_item_unit_t val_units_, int idx, int hf_index_, const capture_file *cap_file, int interval_, int cur_idx_)
{
double value = 0; /* FIXME: loss of precision, visible on the graph for small values */
int adv_type;
const io_graph_item_t *item;
guint32 interval;
item = &items_[idx];
// Basic units
switch (val_units_) {
case IOG_ITEM_UNIT_PACKETS:
return item->frames;
case IOG_ITEM_UNIT_BYTES:
return (double) item->bytes;
case IOG_ITEM_UNIT_BITS:
return (double) (item->bytes * 8);
case IOG_ITEM_UNIT_CALC_FRAMES:
return item->frames;
case IOG_ITEM_UNIT_CALC_FIELDS:
return (double) item->fields;
default:
/* If it's COUNT_TYPE_ADVANCED but not one of the
* generic ones we'll get it when we switch on the
* adv_type below. */
break;
}
if (hf_index_ < 0) {
return 0;
}
// Advanced units
adv_type = proto_registrar_get_ftype(hf_index_);
switch (adv_type) {
case FT_INT8:
case FT_INT16:
case FT_INT24:
case FT_INT32:
case FT_INT40:
case FT_INT48:
case FT_INT56:
case FT_INT64:
case FT_UINT8:
case FT_UINT16:
case FT_UINT24:
case FT_UINT32:
case FT_UINT40:
case FT_UINT48:
case FT_UINT56:
case FT_UINT64:
case FT_DOUBLE:
switch (val_units_) {
case IOG_ITEM_UNIT_CALC_SUM:
value = item->double_tot;
break;
case IOG_ITEM_UNIT_CALC_MAX:
value = item->double_max;
break;
case IOG_ITEM_UNIT_CALC_MIN:
value = item->double_min;
break;
case IOG_ITEM_UNIT_CALC_AVERAGE:
if (item->fields) {
value = item->double_tot / item->fields;
} else {
value = 0;
}
break;
default:
break;
}
break;
case FT_FLOAT:
switch (val_units_) {
case IOG_ITEM_UNIT_CALC_SUM:
value = item->float_tot;
break;
case IOG_ITEM_UNIT_CALC_MAX:
value = item->float_max;
break;
case IOG_ITEM_UNIT_CALC_MIN:
value = item->float_min;
break;
case IOG_ITEM_UNIT_CALC_AVERAGE:
if (item->fields) {
value = (double)item->float_tot / item->fields;
} else {
value = 0;
}
break;
default:
break;
}
break;
case FT_RELATIVE_TIME:
switch (val_units_) {
case IOG_ITEM_UNIT_CALC_MAX:
value = nstime_to_sec(&item->time_max);
break;
case IOG_ITEM_UNIT_CALC_MIN:
value = nstime_to_sec(&item->time_min);
break;
case IOG_ITEM_UNIT_CALC_SUM:
value = nstime_to_sec(&item->time_tot);
break;
case IOG_ITEM_UNIT_CALC_AVERAGE:
if (item->fields) {
value = nstime_to_sec(&item->time_tot) / item->fields;
} else {
value = 0;
}
break;
case IOG_ITEM_UNIT_CALC_LOAD:
// "LOAD graphs plot the QUEUE-depth of the connection over time"
// (for response time fields such as smb.time, rpc.time, etc.)
// This interval is expressed in milliseconds.
if (idx == cur_idx_ && cap_file) {
interval = (guint32)(nstime_to_msec(&cap_file->elapsed_time) + 0.5);
interval -= (interval_ * idx);
} else {
interval = interval_;
}
value = nstime_to_msec(&item->time_tot) / interval;
break;
default:
break;
}
break;
default:
break;
}
return value;
} |
C/C++ | wireshark/ui/io_graph_item.h | /** @file
*
* Definitions and functions for I/O graph items
*
* Copied from gtk/io_stat.c, (c) 2002 Ronnie Sahlberg
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __IO_GRAPH_ITEM_H__
#define __IO_GRAPH_ITEM_H__
#include "cfile.h"
#include <wsutil/ws_assert.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef enum {
IOG_ITEM_UNIT_FIRST,
IOG_ITEM_UNIT_PACKETS = IOG_ITEM_UNIT_FIRST,
IOG_ITEM_UNIT_BYTES,
IOG_ITEM_UNIT_BITS,
IOG_ITEM_UNIT_CALC_SUM,
IOG_ITEM_UNIT_CALC_FRAMES,
IOG_ITEM_UNIT_CALC_FIELDS,
IOG_ITEM_UNIT_CALC_MAX,
IOG_ITEM_UNIT_CALC_MIN,
IOG_ITEM_UNIT_CALC_AVERAGE,
IOG_ITEM_UNIT_CALC_LOAD,
IOG_ITEM_UNIT_LAST = IOG_ITEM_UNIT_CALC_LOAD,
NUM_IOG_ITEM_UNITS
} io_graph_item_unit_t;
typedef struct _io_graph_item_t {
guint32 frames; /* always calculated, will hold number of frames*/
guint64 bytes; /* always calculated, will hold number of bytes*/
guint64 fields;
gint64 int_max;
gint64 int_min;
gint64 int_tot;
/* XXX - Why do we always use 64-bit ints but split floats between
* gfloat and gdouble?
*/
gfloat float_max;
gfloat float_min;
gfloat float_tot;
gdouble double_max;
gdouble double_min;
gdouble double_tot;
nstime_t time_max;
nstime_t time_min;
nstime_t time_tot;
guint32 first_frame_in_invl;
guint32 extreme_frame_in_invl; /* frame with min/max value */
guint32 last_frame_in_invl;
} io_graph_item_t;
/** Reset (zero) an io_graph_item_t.
*
* @param items [in,out] Array containing the items to reset.
* @param count [in] The number of items in the array.
*/
static inline void
reset_io_graph_items(io_graph_item_t *items, gsize count) {
io_graph_item_t *item;
gsize i;
for (i = 0; i < count; i++) {
item = &items[i];
item->frames = 0;
item->bytes = 0;
item->fields = 0;
item->int_max = 0;
item->int_min = 0;
item->int_tot = 0;
item->float_max = 0;
item->float_min = 0;
item->float_tot = 0;
item->double_max = 0;
item->double_min = 0;
item->double_tot = 0;
nstime_set_zero(&item->time_max);
nstime_set_zero(&item->time_min);
nstime_set_zero(&item->time_tot);
item->first_frame_in_invl = 0;
item->extreme_frame_in_invl = 0;
item->last_frame_in_invl = 0;
}
}
/** Get the interval (array index) for a packet
*
* It is up to the caller to determine if the return value is valid.
*
* @param [in] pinfo Packet of interest.
* @param [in] interval Time interval in milliseconds.
* @return Array index on success, -1 on failure.
*/
int get_io_graph_index(packet_info *pinfo, int interval);
/** Check field and item unit compatibility
*
* @param field_name [in] Header field name to check
* @param hf_index [out] Assigned the header field index corresponding to field_name if valid.
* Can be NULL.
* @param item_unit [in] The type of unit to calculate. From IOG_ITEM_UNITS.
* @return NULL if compatible, otherwise an error string. The string must
* be freed by the caller.
*/
GString *check_field_unit(const char *field_name, int *hf_index, io_graph_item_unit_t item_unit);
/** Get the value at the given interval (idx) for the current value unit.
*
* @param items [in] Array containing the item to get.
* @param val_units [in] The type of unit to calculate. From IOG_ITEM_UNITS.
* @param idx [in] Index of the item to get.
* @param hf_index [in] Header field index for advanced statistics.
* @param cap_file [in] Capture file.
* @param interval [in] Timing interval in ms.
* @param cur_idx [in] Current index.
*/
double get_io_graph_item(const io_graph_item_t *items, io_graph_item_unit_t val_units, int idx, int hf_index, const capture_file *cap_file, int interval, int cur_idx);
/** Update the values of an io_graph_item_t.
*
* Frame and byte counts are always calculated. If edt is non-NULL advanced
* statistics are calculated using hfindex.
*
* @param items [in,out] Array containing the item to update.
* @param idx [in] Index of the item to update.
* @param pinfo [in] Packet containing update information.
* @param edt [in] Dissection information for advanced statistics. May be NULL.
* @param hf_index [in] Header field index for advanced statistics.
* @param item_unit [in] The type of unit to calculate. From IOG_ITEM_UNITS.
* @param interval [in] Timing interval in ms.
* @return TRUE if the update was successful, otherwise FALSE.
*/
static inline gboolean
update_io_graph_item(io_graph_item_t *items, int idx, packet_info *pinfo, epan_dissect_t *edt, int hf_index, int item_unit, guint32 interval) {
io_graph_item_t *item = &items[idx];
/* Set the first and last frame num in current interval matching the target field+filter */
if (item->first_frame_in_invl == 0) {
item->first_frame_in_invl = pinfo->num;
}
item->last_frame_in_invl = pinfo->num;
if (edt && hf_index >= 0) {
GPtrArray *gp;
guint i;
gp = proto_get_finfo_ptr_array(edt->tree, hf_index);
if (!gp) {
return FALSE;
}
/* Update the appropriate counters. If fields == 0, this is the first seen
* value so set any min/max values accordingly. */
for (i=0; i < gp->len; i++) {
gint64 new_int64;
guint64 new_uint64;
float new_float;
double new_double;
const nstime_t *new_time;
switch (proto_registrar_get_ftype(hf_index)) {
case FT_UINT8:
case FT_UINT16:
case FT_UINT24:
case FT_UINT32:
new_uint64 = fvalue_get_uinteger(((field_info *)gp->pdata[i])->value);
if ((new_uint64 > (guint64)item->int_max) || (item->fields == 0)) {
item->int_max = new_uint64;
item->double_max = (gdouble)new_uint64;
if (item_unit == IOG_ITEM_UNIT_CALC_MAX) {
item->extreme_frame_in_invl = pinfo->num;
}
}
if ((new_uint64 < (guint64)item->int_min) || (item->fields == 0)) {
item->int_min = new_uint64;
item->double_min = (gdouble)new_uint64;
if (item_unit == IOG_ITEM_UNIT_CALC_MIN) {
item->extreme_frame_in_invl = pinfo->num;
}
}
item->int_tot += new_uint64;
item->double_tot += (gdouble)new_uint64;
item->fields++;
break;
case FT_INT8:
case FT_INT16:
case FT_INT24:
case FT_INT32:
new_int64 = fvalue_get_sinteger(((field_info *)gp->pdata[i])->value);
if ((new_int64 > item->int_max) || (item->fields == 0)) {
item->int_max = new_int64;
item->double_max = (gdouble)new_int64;
if (item_unit == IOG_ITEM_UNIT_CALC_MAX) {
item->extreme_frame_in_invl = pinfo->num;
}
}
if ((new_int64 < item->int_min) || (item->fields == 0)) {
item->int_min = new_int64;
item->double_min = (gdouble)new_int64;
if (item_unit == IOG_ITEM_UNIT_CALC_MIN) {
item->extreme_frame_in_invl = pinfo->num;
}
}
item->int_tot += new_int64;
item->double_tot += (gdouble)new_int64;
item->fields++;
break;
case FT_UINT40:
case FT_UINT48:
case FT_UINT56:
case FT_UINT64:
new_uint64 = fvalue_get_uinteger64(((field_info *)gp->pdata[i])->value);
if ((new_uint64 > (guint64)item->int_max) || (item->fields == 0)) {
item->int_max = new_uint64;
item->double_max = (gdouble)new_uint64;
if (item_unit == IOG_ITEM_UNIT_CALC_MAX) {
item->extreme_frame_in_invl = pinfo->num;
}
}
if ((new_uint64 < (guint64)item->int_min) || (item->fields == 0)) {
item->int_min = new_uint64;
item->double_min = (gdouble)new_uint64;
if (item_unit == IOG_ITEM_UNIT_CALC_MIN) {
item->extreme_frame_in_invl = pinfo->num;
}
}
item->int_tot += new_uint64;
item->double_tot += (gdouble)new_uint64;
item->fields++;
break;
case FT_INT40:
case FT_INT48:
case FT_INT56:
case FT_INT64:
new_int64 = fvalue_get_sinteger64(((field_info *)gp->pdata[i])->value);
if ((new_int64 > item->int_max) || (item->fields == 0)) {
item->int_max = new_int64;
item->double_max = (gdouble)new_int64;
if (item_unit == IOG_ITEM_UNIT_CALC_MAX) {
item->extreme_frame_in_invl = pinfo->num;
}
}
if ((new_int64 < item->int_min) || (item->fields == 0)) {
item->int_min = new_int64;
item->double_min = (gdouble)new_int64;
if (item_unit == IOG_ITEM_UNIT_CALC_MIN) {
item->extreme_frame_in_invl = pinfo->num;
}
}
item->int_tot += new_int64;
item->double_tot += (gdouble)new_int64;
item->fields++;
break;
case FT_FLOAT:
new_float = (gfloat)fvalue_get_floating(((field_info *)gp->pdata[i])->value);
if ((new_float > item->float_max) || (item->fields == 0)) {
item->float_max = new_float;
if (item_unit == IOG_ITEM_UNIT_CALC_MAX) {
item->extreme_frame_in_invl = pinfo->num;
}
}
if ((new_float < item->float_min) || (item->fields == 0)) {
item->float_min = new_float;
if (item_unit == IOG_ITEM_UNIT_CALC_MIN) {
item->extreme_frame_in_invl = pinfo->num;
}
}
item->float_tot += new_float;
item->fields++;
break;
case FT_DOUBLE:
new_double = fvalue_get_floating(((field_info *)gp->pdata[i])->value);
if ((new_double > item->double_max) || (item->fields == 0)) {
item->double_max = new_double;
if (item_unit == IOG_ITEM_UNIT_CALC_MAX) {
item->extreme_frame_in_invl = pinfo->num;
}
}
if ((new_double < item->double_min) || (item->fields == 0)) {
item->double_min = new_double;
if (item_unit == IOG_ITEM_UNIT_CALC_MIN) {
item->extreme_frame_in_invl = pinfo->num;
}
}
item->double_tot += new_double;
item->fields++;
break;
case FT_RELATIVE_TIME:
new_time = fvalue_get_time(((field_info *)gp->pdata[i])->value);
switch (item_unit) {
case IOG_ITEM_UNIT_CALC_LOAD:
{
guint64 t, pt; /* time in us */
int j;
/*
* Add the time this call spanned each interval according to its contribution
* to that interval.
*/
t = new_time->secs;
t = t * 1000000 + new_time->nsecs / 1000;
j = idx;
/*
* Handle current interval
*/
pt = pinfo->rel_ts.secs * 1000000 + pinfo->rel_ts.nsecs / 1000;
pt = pt % (interval * 1000);
if (pt > t) {
pt = t;
}
while (t) {
io_graph_item_t *load_item;
load_item = &items[j];
load_item->time_tot.nsecs += (int) (pt * 1000);
if (load_item->time_tot.nsecs > 1000000000) {
load_item->time_tot.secs++;
load_item->time_tot.nsecs -= 1000000000;
}
if (j == 0) {
break;
}
j--;
t -= pt;
if (t > (guint64) interval * 1000) {
pt = (guint64) interval * 1000;
} else {
pt = t;
}
}
break;
}
default:
if ( (new_time->secs > item->time_max.secs)
|| ( (new_time->secs == item->time_max.secs)
&& (new_time->nsecs > item->time_max.nsecs))
|| (item->fields == 0)) {
item->time_max = *new_time;
if (item_unit == IOG_ITEM_UNIT_CALC_MAX) {
item->extreme_frame_in_invl = pinfo->num;
}
}
if ( (new_time->secs<item->time_min.secs)
|| ( (new_time->secs == item->time_min.secs)
&& (new_time->nsecs < item->time_min.nsecs))
|| (item->fields == 0)) {
item->time_min = *new_time;
if (item_unit == IOG_ITEM_UNIT_CALC_MIN) {
item->extreme_frame_in_invl = pinfo->num;
}
}
nstime_add(&item->time_tot, new_time);
item->fields++;
}
break;
default:
if ((item_unit == IOG_ITEM_UNIT_CALC_FRAMES) ||
(item_unit == IOG_ITEM_UNIT_CALC_FIELDS)) {
/*
* It's not an integeresque type, but
* all we want to do is count it, so
* that's all right.
*/
item->fields++;
}
else {
/*
* "Can't happen"; see the "check that the
* type is compatible" check in
* filter_callback().
*/
ws_assert_not_reached();
}
break;
}
}
}
item->frames++;
item->bytes += pinfo->fd->pkt_len;
return TRUE;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __IO_GRAPH_ITEM_H__ */ |
C | wireshark/ui/language.c | /* language.c
* Language "preference" handling routines
* Copyright 2014, Michal Labedzki for Tieto Corporation
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <stdlib.h>
#include <errno.h>
#include <epan/prefs.h>
#include <epan/prefs-int.h>
#include <wsutil/filesystem.h>
#include <wsutil/file_util.h>
#include "ui/language.h"
#include "ui/simple_dialog.h"
#define LANGUAGE_FILE_NAME "language"
#define LANGUAGE_PREF_LANGUAGE "language"
char *language = NULL;
/* set one user's recent common file key/value pair */
static prefs_set_pref_e
read_language_pref(gchar *key, const gchar *value,
void *private_data _U_, gboolean return_range_errors _U_)
{
if (strcmp(key, LANGUAGE_PREF_LANGUAGE) == 0) {
g_free(language);
/*
* For backwards compatibility, treat "auto" as meaning "use the
* system language".
*
* To handle the old buggy code that didn't check whether "language"
* was null before trying to print it, treat "(null)" - which many,
* but *NOT* all, system printfs print for a null pointer (some
* printfs, such as the one in Solaris, *crash* with %s and a null
* pointer) - as meaning "use the system language".
*/
if (!value || !*value || strcmp(value, "auto") == 0 ||
strcmp(value, "(null)") == 0)
language = g_strdup(USE_SYSTEM_LANGUAGE);
else
language = g_strdup(value);
}
return PREFS_SET_OK;
}
void
read_language_prefs(void)
{
char *rf_path;
FILE *rf;
rf_path = get_persconffile_path(LANGUAGE_FILE_NAME, FALSE);
if ((rf = ws_fopen(rf_path, "r")) != NULL) {
read_prefs_file(rf_path, rf, read_language_pref, NULL);
fclose(rf);
}
g_free(rf_path);
}
gboolean
write_language_prefs(void)
{
char *pf_dir_path;
char *rf_path;
FILE *rf;
/* To do:
* - Split output lines longer than MAX_VAL_LEN
* - Create a function for the preference directory check/creation
* so that duplication can be avoided with filter.c
*/
/* Create the directory that holds personal configuration files, if
necessary. */
if (create_persconffile_dir(&pf_dir_path) == -1) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"Can't create directory\n\"%s\"\nfor language file: %s.", pf_dir_path,
g_strerror(errno));
g_free(pf_dir_path);
return FALSE;
}
rf_path = get_persconffile_path(LANGUAGE_FILE_NAME, FALSE);
if ((rf = ws_fopen(rf_path, "w")) == NULL) {
simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
"Can't open recent file\n\"%s\": %s.", rf_path,
g_strerror(errno));
g_free(rf_path);
return FALSE;
}
g_free(rf_path);
fputs("# Language settings file for Wireshark " VERSION ".\n"
"#\n"
"# This file is regenerated each time Wireshark is quit.\n"
"# So be careful, if you want to make manual changes here.\n"
"\n", rf);
fprintf(rf, LANGUAGE_PREF_LANGUAGE ": %s\n", language ? language : USE_SYSTEM_LANGUAGE);
fclose(rf);
return TRUE;
} |
C/C++ | wireshark/ui/language.h | /** @file
*
* Copyright 2014, Michal Labedzki for Tieto Corporation
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __LANGUAGE_H__
#define __LANGUAGE_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define USE_SYSTEM_LANGUAGE "system"
extern char *language;
extern void read_language_prefs(void);
extern int write_language_prefs(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* language.h */ |
C/C++ | wireshark/ui/last_open_dir.h | /** @file
*
* Routines to fetch the last directory in which a file was opened;
* its implementation is GUI-dependent, but the API isn't
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __UI_LAST_OPEN_DIR_H__
#define __UI_LAST_OPEN_DIR_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/** Get the latest opened directory.
*
* @return the dirname
*/
extern char *get_last_open_dir(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __UI_LAST_OPEN_DIR_H__ */ |
C/C++ | wireshark/ui/main_statusbar.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __MAIN_STATUSBAR_H__
#define __MAIN_STATUSBAR_H__
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void profile_bar_update(void);
void packets_bar_update(void);
void status_expert_update(void);
/** Update the capture comment icon in the statusbar, depending on the
* current capture comment (XXX - it's only available for GTK at the moment)
*/
void status_capture_comment_update(void);
/** Push a formatted message referring to the currently-selected field
* onto the statusbar.
*
* @param msg_format The format string for the message
*/
void statusbar_push_field_msg(const gchar *msg_format, ...)
G_GNUC_PRINTF(1, 2);
/** Pop a message referring to the currently-selected field off the statusbar.
*/
void statusbar_pop_field_msg(void);
/** Push a formatted message referring to the current filter onto the
* statusbar.
*
* @param msg_format The format string for the message
*/
void statusbar_push_filter_msg(const gchar *msg_format, ...)
G_GNUC_PRINTF(1, 2);
/** Pop a message referring to the current filter off the statusbar.
*/
void statusbar_pop_filter_msg(void);
/** Push a formatted temporary message onto the statusbar. The message
* is automatically removed at a later interval.
*
* @param msg_format The format string for the message
*/
void statusbar_push_temporary_msg(const gchar *msg_format, ...)
G_GNUC_PRINTF(1, 2);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __MAIN_STATUSBAR_H__ */ |
C | wireshark/ui/mcast_stream.c | /* mcast_stream.c
*
* Copyright 2006, Iskratel , Slovenia
* By Jakob Bratkovic <[email protected]> and
* Miha Jemec <[email protected]>
*
* based on rtp_stream.c
* Copyright 2003, Alcatel Business Systems
* By Lars Ruoff <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <glib.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "file.h"
#include <epan/epan.h>
#include <epan/address.h>
#include <epan/packet.h>
#include <epan/tap.h>
#include <epan/to_str.h>
#include "ui/mcast_stream.h"
gint32 mcast_stream_trigger = 50; /* limit for triggering the burst alarm (in packets per second) */
gint32 mcast_stream_bufferalarm = 10000; /* limit for triggering the buffer alarm (in bytes) */
guint16 mcast_stream_burstint = 100; /* burst interval in ms */
gint32 mcast_stream_emptyspeed = 5000; /* outgoing speed for single stream (kbps)*/
gint32 mcast_stream_cumulemptyspeed = 100000; /* outgoiong speed for all streams (kbps)*/
/* sliding window and buffer usage */
static gint32 buffsize = (int)((double)MAX_SPEED * 100 / 1000) * 2;
static guint16 comparetimes(nstime_t *t1, nstime_t *t2, guint16 burstint_lcl);
static void buffusagecalc(mcast_stream_info_t *strinfo, packet_info *pinfo, double emptyspeed_lcl);
static void slidingwindow(mcast_stream_info_t *strinfo, packet_info *pinfo);
/****************************************************************************/
/* GCompareFunc style comparison function for _mcast_stream_info */
static gint
mcast_stream_info_cmp(gconstpointer aa, gconstpointer bb)
{
const struct _mcast_stream_info* a = (const struct _mcast_stream_info *)aa;
const struct _mcast_stream_info* b = (const struct _mcast_stream_info *)bb;
if (a==b)
return 0;
if (a==NULL || b==NULL)
return 1;
if (addresses_equal(&(a->src_addr), &(b->src_addr))
&& (a->src_port == b->src_port)
&& addresses_equal(&(a->dest_addr), &(b->dest_addr))
&& (a->dest_port == b->dest_port))
return 0;
else
return 1;
}
/****************************************************************************/
/* when there is a [re]reading of packet's */
void
mcaststream_reset(mcaststream_tapinfo_t *tapinfo)
{
GList* list;
/* free the data items first */
list = g_list_first(tapinfo->strinfo_list);
while (list)
{
/* XYZ I don't know how to clean this */
/*g_free(list->element.buff); */
g_free(list->data);
list = g_list_next(list);
}
g_list_free(tapinfo->strinfo_list);
tapinfo->strinfo_list = NULL;
/* XYZ and why does the line below causes a crach? */
/*g_free(tapinfo->allstreams->element.buff);*/
g_free(tapinfo->allstreams);
tapinfo->allstreams = NULL;
tapinfo->npackets = 0;
return;
}
static void
mcaststream_reset_cb(void *ti_ptr)
{
mcaststream_tapinfo_t *tapinfo = (mcaststream_tapinfo_t *)ti_ptr;
if (tapinfo) {
if (tapinfo->tap_reset) {
tapinfo->tap_reset(tapinfo);
}
mcaststream_reset(tapinfo);
}
}
/****************************************************************************/
/* redraw the output */
static void
mcaststream_draw(void *ti_ptr)
{
mcaststream_tapinfo_t *tapinfo = (mcaststream_tapinfo_t *)ti_ptr;
/* XXX: see mcaststream_on_update in mcast_streams_dlg.c for comments
g_signal_emit_by_name(top_level, "signal_mcaststream_update");
*/
if (tapinfo && tapinfo->tap_draw) {
tapinfo->tap_draw(tapinfo);
}
return;
}
/****************************************************************************/
/* whenever a udp packet is seen by the tap listener */
tap_packet_status
mcaststream_packet(void *arg, packet_info *pinfo, epan_dissect_t *edt _U_, const void *arg2 _U_, tap_flags_t flags _U_)
{
mcaststream_tapinfo_t *tapinfo = (mcaststream_tapinfo_t *)arg;
mcast_stream_info_t tmp_strinfo;
mcast_stream_info_t *strinfo = NULL;
GList* list;
nstime_t delta;
double deltatime;
/*
* Restrict statistics to standard multicast IPv4 and IPv6 addresses.
* We might want to check for and allow ethernet addresses starting
* with 01:00:05 and 33:33 as well.
*/
switch (pinfo->net_dst.type) {
case AT_IPv4:
/* 224.0.0.0/4 */
if (pinfo->net_dst.len == 0 || (((const guint8*)pinfo->net_dst.data)[0] & 0xf0) != 0xe0)
return TAP_PACKET_DONT_REDRAW;
break;
case AT_IPv6:
/* ff00::/8 */
/* XXX This includes DHCPv6. */
if (pinfo->net_dst.len == 0 || ((const guint8*)pinfo->net_dst.data)[0] != 0xff)
return TAP_PACKET_DONT_REDRAW;
break;
default:
return TAP_PACKET_DONT_REDRAW;
}
/* gather infos on the stream this packet is part of */
copy_address(&(tmp_strinfo.src_addr), &(pinfo->net_src));
tmp_strinfo.src_port = pinfo->srcport;
copy_address(&(tmp_strinfo.dest_addr), &(pinfo->net_dst));
tmp_strinfo.dest_port = pinfo->destport;
/* check whether we already have a stream with these parameters in the list */
list = g_list_first(tapinfo->strinfo_list);
while (list)
{
if (mcast_stream_info_cmp(&tmp_strinfo, (mcast_stream_info_t*)(list->data))==0)
{
strinfo = (mcast_stream_info_t*)(list->data); /*found!*/
break;
}
list = g_list_next(list);
}
/* not in the list? then create a new entry */
if (!strinfo) {
/*printf("nov sip %s sp %d dip %s dp %d\n", address_to_display(NULL, &(pinfo->src)),
pinfo->srcport, address_to_display(NULL, &(pinfo->dst)), pinfo->destport);*/
tmp_strinfo.npackets = 0;
tmp_strinfo.apackets = 0;
tmp_strinfo.first_frame_num = pinfo->num;
tmp_strinfo.start_abs = pinfo->abs_ts;
tmp_strinfo.start_rel = pinfo->rel_ts;
tmp_strinfo.vlan_id = 0;
/* reset Mcast stats */
tmp_strinfo.average_bw = 0;
tmp_strinfo.total_bytes = 0;
/* reset slidingwindow and buffer parameters */
tmp_strinfo.element.buff = g_new(nstime_t, buffsize);
tmp_strinfo.element.first=0;
tmp_strinfo.element.last=0;
tmp_strinfo.element.burstsize=1;
tmp_strinfo.element.topburstsize=1;
tmp_strinfo.element.numbursts=0;
tmp_strinfo.element.burststatus=0;
tmp_strinfo.element.count=1;
tmp_strinfo.element.buffusage=pinfo->fd->pkt_len;
tmp_strinfo.element.topbuffusage=pinfo->fd->pkt_len;
tmp_strinfo.element.numbuffalarms=0;
tmp_strinfo.element.buffstatus=0;
tmp_strinfo.element.maxbw=0;
strinfo = g_new(mcast_stream_info_t, 1);
*strinfo = tmp_strinfo; /* memberwise copy of struct */
tapinfo->strinfo_list = g_list_append(tapinfo->strinfo_list, strinfo);
strinfo->element.buff = g_new(nstime_t, buffsize);
/* set time with the first packet */
if (tapinfo->npackets == 0) {
tapinfo->allstreams = g_new(mcast_stream_info_t, 1);
tapinfo->allstreams->element.buff =
g_new(nstime_t, buffsize);
tapinfo->allstreams->start_rel = pinfo->rel_ts;
tapinfo->allstreams->total_bytes = 0;
tapinfo->allstreams->element.first=0;
tapinfo->allstreams->element.last=0;
tapinfo->allstreams->element.burstsize=1;
tapinfo->allstreams->element.topburstsize=1;
tapinfo->allstreams->element.numbursts=0;
tapinfo->allstreams->element.burststatus=0;
tapinfo->allstreams->element.count=1;
tapinfo->allstreams->element.buffusage=pinfo->fd->pkt_len;
tapinfo->allstreams->element.topbuffusage=pinfo->fd->pkt_len;
tapinfo->allstreams->element.numbuffalarms=0;
tapinfo->allstreams->element.buffstatus=0;
tapinfo->allstreams->element.maxbw=0;
}
}
/* time between first and last packet in the group */
strinfo->stop_rel = pinfo->rel_ts;
nstime_delta(&delta, &strinfo->stop_rel, &strinfo->start_rel);
deltatime = nstime_to_sec(&delta);
/* calculate average bandwidth for this stream */
strinfo->total_bytes = strinfo->total_bytes + pinfo->fd->pkt_len;
/* increment the packets counter for this stream and calculate average pps */
++(strinfo->npackets);
if (deltatime > 0) {
strinfo->apackets = strinfo->npackets / deltatime;
strinfo->average_bw = ((double)(strinfo->total_bytes*8) / deltatime);
} else {
strinfo->apackets = strinfo->average_bw = 0.0;
}
/* time between first and last packet in any group */
tapinfo->allstreams->stop_rel = pinfo->rel_ts;
nstime_delta(&delta, &tapinfo->allstreams->stop_rel, &tapinfo->allstreams->start_rel);
deltatime = nstime_to_sec(&delta);
/* increment the packets counter of all streams */
++(tapinfo->npackets);
/* calculate average bandwidth for all streams */
tapinfo->allstreams->total_bytes = tapinfo->allstreams->total_bytes + pinfo->fd->pkt_len;
if (deltatime > 0)
tapinfo->allstreams->average_bw = ((double)(tapinfo->allstreams->total_bytes*8) / deltatime);
/* sliding window and buffercalc for this group*/
slidingwindow(strinfo, pinfo);
buffusagecalc(strinfo, pinfo, mcast_stream_emptyspeed*1000);
/* sliding window and buffercalc for all groups */
slidingwindow(tapinfo->allstreams, pinfo);
buffusagecalc(tapinfo->allstreams, pinfo, mcast_stream_cumulemptyspeed*1000);
/* end of sliding window */
return TAP_PACKET_REDRAW; /* refresh output */
}
/****************************************************************************/
/* TAP INTERFACE */
/****************************************************************************/
/****************************************************************************/
void
remove_tap_listener_mcast_stream(mcaststream_tapinfo_t *tapinfo)
{
if (tapinfo && tapinfo->is_registered) {
remove_tap_listener(tapinfo);
tapinfo->is_registered = FALSE;
}
}
/****************************************************************************/
GString *
register_tap_listener_mcast_stream(mcaststream_tapinfo_t *tapinfo)
{
GString *error_string;
if (!tapinfo) {
return NULL;
}
if (tapinfo->is_registered) {
return NULL;
}
error_string = register_tap_listener("udp", tapinfo,
NULL, 0, mcaststream_reset_cb, mcaststream_packet,
mcaststream_draw, NULL);
if (NULL == error_string) {
tapinfo->is_registered = TRUE;
}
return error_string;
}
/*******************************************************************************/
/* sliding window and buffer calculations */
/* compare two times */
static guint16
comparetimes(nstime_t *t1, nstime_t *t2, guint16 burstint_lcl)
{
if(((t2->secs - t1->secs)*1000 + (t2->nsecs - t1->nsecs)/1000000) > burstint_lcl){
return 1;
} else{
return 0;
}
}
/* calculate buffer usage */
static void
buffusagecalc(mcast_stream_info_t *strinfo, packet_info *pinfo, double emptyspeed_lcl)
{
gint32 cur, prev;
nstime_t *buffer;
nstime_t delta;
double timeelapsed;
buffer = strinfo->element.buff;
cur = strinfo->element.last;
if(cur == 0){
cur = buffsize - 1;
prev = cur - 1;
} else if(cur == 1){
prev = buffsize - 1;
cur = 0;
} else{
cur=cur-1;
prev=cur-1;
}
nstime_delta(&delta, &buffer[cur], &buffer[prev]);
timeelapsed = nstime_to_sec(&delta);
/* bytes added to buffer */
strinfo->element.buffusage+=pinfo->fd->pkt_len;
/* bytes cleared from buffer */
strinfo->element.buffusage-= (guint32) (timeelapsed * emptyspeed_lcl / 8);
if(strinfo->element.buffusage < 0) strinfo->element.buffusage=0;
if(strinfo->element.buffusage > strinfo->element.topbuffusage)
strinfo->element.topbuffusage = strinfo->element.buffusage;
/* check for buffer losses */
if((strinfo->element.buffusage >= mcast_stream_bufferalarm) && (strinfo->element.buffstatus == 0)){
strinfo->element.buffstatus = 1;
strinfo->element.numbuffalarms++;
} else if(strinfo->element.buffusage < mcast_stream_bufferalarm){
strinfo->element.buffstatus = 0;
}
return;
}
/* sliding window calculation */
static void
slidingwindow(mcast_stream_info_t *strinfo, packet_info *pinfo)
{
nstime_t *buffer;
gint32 diff;
buffer = strinfo->element.buff;
diff = strinfo->element.last - strinfo->element.first;
if(diff < 0) diff+=buffsize;
/* check if buffer is full */
if(diff >= (buffsize - 2)){
fprintf(stderr, "Warning: capture buffer full\n");
strinfo->element.first++;
if(strinfo->element.first >= buffsize) strinfo->element.first = strinfo->element.first % buffsize;
}
/* burst count */
buffer[strinfo->element.last] = pinfo->rel_ts;
while(comparetimes(&buffer[strinfo->element.first],
&buffer[strinfo->element.last], mcast_stream_burstint)){
strinfo->element.first++;
if(strinfo->element.first >= buffsize) strinfo->element.first = strinfo->element.first % buffsize;
diff--;
}
strinfo->element.burstsize = diff;
if(strinfo->element.burstsize > strinfo->element.topburstsize) {
strinfo->element.topburstsize = strinfo->element.burstsize;
strinfo->element.maxbw = (double)(strinfo->element.topburstsize) * 1000 / mcast_stream_burstint * pinfo->fd->pkt_len * 8;
}
strinfo->element.last++;
if(strinfo->element.last >= buffsize) strinfo->element.last = strinfo->element.last % buffsize;
/* trigger check */
if((strinfo->element.burstsize >= mcast_stream_trigger) && (strinfo->element.burststatus == 0)){
strinfo->element.burststatus = 1;
strinfo->element.numbursts++;
} else if(strinfo->element.burstsize < mcast_stream_trigger){
strinfo->element.burststatus = 0;
}
strinfo->element.count++;
} |
C/C++ | wireshark/ui/mcast_stream.h | /** @file
*
* Copyright 2006, Iskratel , Slovenia
* By Jakob Bratkovic <[email protected]> and
* Miha Jemec <[email protected]>
*
* based on rtp_stream.h
* Copyright 2003, Alcatel Business Systems
* By Lars Ruoff <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __MCAST_STREAM_H__
#define __MCAST_STREAM_H__
#include <epan/tap.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define MAX_SPEED 200000
/* typedefs for sliding window and buffer size */
typedef struct buffer{
nstime_t *buff; /* packet times */
gint32 first; /* pointer to the first element */
gint32 last; /* pointer to the last element */
gint32 burstsize; /* current burst */
gint32 topburstsize; /* maximum burst in the refresh interval*/
gint32 count; /* packet counter */
gint32 burststatus; /* burst status */
gint32 numbursts; /* number of bursts */
gint32 buffusage; /* buffer usage */
gint32 buffstatus; /* buffer status */
gint32 numbuffalarms; /* number of alarms triggered by buffer underruns */
gint32 topbuffusage; /* top buffer usage in refresh interval */
double maxbw; /* Maximum bandwidth usage. Bits/s */
} t_buffer;
/* defines an mcast stream */
typedef struct _mcast_stream_info {
address src_addr;
guint16 src_port;
address dest_addr;
guint16 dest_port;
guint32 npackets;
double apackets;
guint32 total_bytes;
double average_bw; /* Bits/s */
guint32 first_frame_num; /* frame number of first frame */
/* start of recording (GMT) of this stream */
nstime_t start_abs; /* absolute stream start time */
nstime_t start_rel; /* stream start time relative to first packet in capture */
nstime_t stop_rel; /* stream stop time relative to first packet in capture */
guint16 vlan_id;
/*for the sliding window */
t_buffer element;
} mcast_stream_info_t;
typedef struct _mcaststream_tapinfo mcaststream_tapinfo_t;
typedef void (*mcaststream_tap_reset_cb)(mcaststream_tapinfo_t *tapinfo);
typedef void (*mcaststream_tap_draw_cb)(mcaststream_tapinfo_t *tapinfo);
/* structure that holds the information about all detected streams */
/* struct holding all information of the tap */
struct _mcaststream_tapinfo {
gpointer user_data; /* User data pointer */
mcaststream_tap_reset_cb tap_reset; /**< tap reset callback */
mcaststream_tap_draw_cb tap_draw; /**< tap draw callback */
GList* strinfo_list; /* list of mcast_stream_info_t */
guint32 npackets; /* total number of mcast packets of all streams */
mcast_stream_info_t* allstreams; /* structure holding information common for all streams */
gboolean is_registered; /* if the tap listener is currently registered or not */
};
extern gint32 mcast_stream_trigger;
extern gint32 mcast_stream_bufferalarm;
extern guint16 mcast_stream_burstint;
extern gint32 mcast_stream_emptyspeed;
extern gint32 mcast_stream_cumulemptyspeed;
/****************************************************************************/
/* INTERFACE */
/*
* Registers the mcast_streams tap listener (if not already done).
* From that point on, the Mcast streams list will be updated with every redissection.
* This function is also the entry point for the initialization routine of the tap system.
* So whenever mcast_stream.c is added to the list of WIRESHARK_TAP_SRCs, the tap will be registered on startup.
* If not, it will be registered on demand by the mcast_streams and mcast_analysis functions that need it.
*/
GString * register_tap_listener_mcast_stream(mcaststream_tapinfo_t *tapinfo);
/*
* Removes the mcast_streams tap listener (if not already done)
* From that point on, the Mcast streams list won't be updated any more.
*/
void remove_tap_listener_mcast_stream(mcaststream_tapinfo_t *tapinfo);
/*
* Cleans up memory of mcast streams tap.
*/
void mcaststream_reset(mcaststream_tapinfo_t *tapinfo);
/*
* Tap callback (tap_packet_cb) for Mcast stream tap updates. Useful if for
* some reason you can't register the default listener, but want to make use
* of the existing Mcast calculations.
*/
tap_packet_status mcaststream_packet(void *tapdata, packet_info *pinfo, epan_dissect_t *edt, const void *data, tap_flags_t flags);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __MCAST_STREAM_H__ */ |
C | wireshark/ui/packet_list_utils.c | /* packet_list_utils.c
* Packet list display utilities
* Copied from gtk/packet_list.c
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include "packet_list_utils.h"
#include <epan/column.h>
gboolean
right_justify_column (gint col, capture_file *cf)
{
header_field_info *hfi;
gboolean right_justify = FALSE;
guint num_fields, *field_idx, ii;
guint right_justify_count = 0;
if (!cf) return FALSE;
switch (cf->cinfo.columns[col].col_fmt) {
case COL_NUMBER:
case COL_PACKET_LENGTH:
case COL_CUMULATIVE_BYTES:
case COL_DSCP_VALUE:
case COL_UNRES_DST_PORT:
case COL_UNRES_SRC_PORT:
case COL_DEF_DST_PORT:
case COL_DEF_SRC_PORT:
case COL_DELTA_TIME:
case COL_DELTA_TIME_DIS:
right_justify = TRUE;
break;
case COL_CUSTOM:
num_fields = g_slist_length(cf->cinfo.columns[col].col_custom_fields_ids);
for (ii = 0; ii < num_fields; ii++) {
field_idx = (guint *) g_slist_nth_data(cf->cinfo.columns[col].col_custom_fields_ids, ii);
hfi = proto_registrar_get_nth(*field_idx);
/* Check if this is a valid field and we have no strings lookup table */
if ((hfi != NULL) && ((hfi->strings == NULL) || !get_column_resolved(col))) {
/* Check for bool, framenum, double, float, relative time and decimal/octal integer types */
if ((hfi->type == FT_BOOLEAN) || (hfi->type == FT_FRAMENUM) || (hfi->type == FT_DOUBLE) ||
(hfi->type == FT_FLOAT) || (hfi->type == FT_RELATIVE_TIME) ||
(((FIELD_DISPLAY(hfi->display) == BASE_DEC) || (FIELD_DISPLAY(hfi->display) == BASE_OCT)) &&
(FT_IS_INT(hfi->type) || FT_IS_UINT(hfi->type))))
{
right_justify_count++;
}
}
}
if ((num_fields > 0) && (right_justify_count == num_fields)) {
/* All custom fields must meet the right-justify criteria */
right_justify = TRUE;
}
break;
default:
break;
}
return right_justify;
}
gboolean
resolve_column (gint col, capture_file *cf)
{
header_field_info *hfi;
gboolean resolve = FALSE;
guint num_fields, *field_idx, ii;
if (!cf) return FALSE;
switch (cf->cinfo.columns[col].col_fmt) {
case COL_CUSTOM:
num_fields = g_slist_length(cf->cinfo.columns[col].col_custom_fields_ids);
for (ii = 0; ii < num_fields; ii++) {
field_idx = (guint *) g_slist_nth_data(cf->cinfo.columns[col].col_custom_fields_ids, ii);
hfi = proto_registrar_get_nth(*field_idx);
/* Check if we have an OID, a (potentially) resolvable network
* address, a Boolean, or a strings table with integer values */
/* XXX: Should this checkbox be disabled if the Name Resolution
* preference for a given type is off?
*/
if ((hfi->type == FT_OID) || (hfi->type == FT_REL_OID) || (hfi->type == FT_ETHER) || (hfi->type == FT_IPv4) || (hfi->type == FT_IPv6) || (hfi->type == FT_FCWWN) || (hfi->type == FT_BOOLEAN) ||
((hfi->strings != NULL) &&
(FT_IS_INT(hfi->type) || FT_IS_UINT(hfi->type))))
{
resolve = TRUE;
break;
}
}
break;
default:
break;
}
return resolve;
} |
C/C++ | wireshark/ui/packet_list_utils.h | /** @file
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __PACKET_LIST_UTILS_H__
#define __PACKET_LIST_UTILS_H__
#include "cfile.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
* Check to see if a column should be right justified.
*
* @param [in] col The column number.
* @param [in] cf The capture file containing the packet data.
*
* @return TRUE if the column should be right justified, FALSE otherwise.
*/
gboolean right_justify_column (gint col, capture_file *cf);
/**
* Check to see if a column's data should be resolved.
*
* @param [in] col The column number.
* @param [in] cf The capture file containing the packet data.
*
* @return TRUE if resolution is required, FALSE otherwise.
*/
gboolean resolve_column (gint col, capture_file *cf);
/**
* @brief The following methods have to be implemented by any class that
* whishes to represent a packet list.
*/
/** Write all packet list geometry values to the recent file.
*
* @param rf recent file handle from caller
*/
extern void packet_list_recent_write_all(FILE *rf);
extern void packet_list_clear(void);
extern void packet_list_freeze(void);
extern void packet_list_recreate_visible_rows(void);
extern void packet_list_thaw(void);
extern guint packet_list_append(column_info *cinfo, frame_data *fdata);
extern void packet_list_queue_draw(void);
extern gboolean packet_list_select_row_from_data(frame_data *fdata_needle);
extern gboolean packet_list_multi_select_active(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __PACKET_LIST_UTILS_H__ */ |
C | wireshark/ui/packet_range.c | /* packet_range.c
* Packet range routines (save, print, ...)
*
* Dick Gooris <[email protected]>
* Ulf Lamping <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <string.h>
#include <glib.h>
#include <epan/frame_data.h>
#include "packet_range.h"
#include <wsutil/ws_assert.h>
static void
depended_frames_add(GHashTable* depended_table, frame_data_sequence *frames, frame_data *frame)
{
if (g_hash_table_add(depended_table, GUINT_TO_POINTER(frame->num)) && frame->dependent_frames) {
GHashTableIter iter;
gpointer key;
frame_data *depended_fd;
g_hash_table_iter_init(&iter, frame->dependent_frames);
while (g_hash_table_iter_next(&iter, &key, NULL)) {
depended_fd = frame_data_sequence_find(frames, GPOINTER_TO_UINT(key));
depended_frames_add(depended_table, frames, depended_fd);
}
}
}
/* (re-)calculate the packet counts (except the user specified range) */
static void packet_range_calc(packet_range_t *range) {
guint32 framenum;
guint32 mark_low;
guint32 mark_high;
guint32 displayed_mark_low;
guint32 displayed_mark_high;
frame_data *packet;
mark_low = 0;
mark_high = 0;
range->mark_range_cnt = 0;
range->ignored_cnt = 0;
range->ignored_selection_range_cnt = 0;
range->ignored_marked_cnt = 0;
range->ignored_mark_range_cnt = 0;
range->ignored_user_range_cnt = 0;
displayed_mark_low = 0;
displayed_mark_high = 0;
range->displayed_cnt = 0;
range->displayed_marked_cnt = 0;
range->displayed_mark_range_cnt = 0;
range->displayed_plus_dependents_cnt = 0;
range->displayed_mark_range_plus_depends_cnt = 0;
range->displayed_ignored_cnt = 0;
range->displayed_ignored_selection_range_cnt = 0;
range->displayed_ignored_marked_cnt = 0;
range->displayed_ignored_mark_range_cnt = 0;
range->displayed_ignored_user_range_cnt = 0;
ws_assert(range->cf != NULL);
/* XXX - this doesn't work unless you have a full set of frame_data
* structures for all packets in the capture, which is not,
* for example, the case when TShark is doing a one-pass
* read of a file or a live capture.
*
* It's also horribly slow on large captures, causing it to
* take a long time for the Save As dialog to pop up, for
* example. We should really keep these statistics in
* the capture_file structure, updating them whenever we
* filter the display, etc..
*/
if (range->cf->provider.frames != NULL) {
/* The next for-loop is used to obtain the amount of packets
* to be processed and is used to present the information in
* the Save/Print As widget.
* We have different types of ranges: All the packets, the number
* of packets of a marked range, a single packet, and a user specified
* packet range. The last one is not calculated here since this
* data must be entered in the widget by the user.
*/
for(framenum = 1; framenum <= range->cf->count; framenum++) {
packet = frame_data_sequence_find(range->cf->provider.frames, framenum);
if (range->cf->current_frame == packet && range->selection_range == NULL ) {
range_add_value(NULL, &(range->selection_range), framenum);
}
if (packet->passed_dfilter) {
range->displayed_cnt++;
}
if (packet->passed_dfilter ||
packet->dependent_of_displayed) {
range->displayed_plus_dependents_cnt++;
}
if (packet->marked) {
if (packet->ignored) {
range->ignored_marked_cnt++;
}
if (packet->passed_dfilter) {
range->displayed_marked_cnt++;
if (packet->ignored) {
range->displayed_ignored_marked_cnt++;
}
if (displayed_mark_low == 0) {
displayed_mark_low = framenum;
}
if (framenum > displayed_mark_high) {
displayed_mark_high = framenum;
}
depended_frames_add(range->displayed_marked_plus_depends, range->cf->provider.frames, packet);
}
if (mark_low == 0) {
mark_low = framenum;
}
if (framenum > mark_high) {
mark_high = framenum;
}
depended_frames_add(range->marked_plus_depends, range->cf->provider.frames, packet);
}
if (packet->ignored) {
range->ignored_cnt++;
if (packet->passed_dfilter) {
range->displayed_ignored_cnt++;
}
}
}
for(framenum = 1; framenum <= range->cf->count; framenum++) {
packet = frame_data_sequence_find(range->cf->provider.frames, framenum);
if (framenum >= mark_low &&
framenum <= mark_high)
{
range->mark_range_cnt++;
if (packet->ignored) {
range->ignored_mark_range_cnt++;
}
depended_frames_add(range->mark_range_plus_depends, range->cf->provider.frames, packet);
}
if (framenum >= displayed_mark_low &&
framenum <= displayed_mark_high)
{
if (packet->passed_dfilter) {
range->displayed_mark_range_cnt++;
if (packet->ignored) {
range->displayed_ignored_mark_range_cnt++;
}
}
depended_frames_add(range->displayed_mark_range_plus_depends, range->cf->provider.frames, packet);
}
}
range->marked_plus_depends_cnt = g_hash_table_size(range->marked_plus_depends);
range->displayed_marked_plus_depends_cnt = g_hash_table_size(range->displayed_marked_plus_depends);
range->mark_range_plus_depends_cnt = g_hash_table_size(range->mark_range_plus_depends);
range->displayed_mark_range_plus_depends_cnt = g_hash_table_size(range->displayed_mark_range_plus_depends);
}
}
/* (re-)calculate the user specified packet range counts */
static void packet_range_calc_user(packet_range_t *range) {
guint32 framenum;
frame_data *packet;
range->user_range_cnt = 0;
range->ignored_user_range_cnt = 0;
range->displayed_user_range_cnt = 0;
range->displayed_user_range_plus_depends_cnt = 0;
range->displayed_ignored_user_range_cnt = 0;
ws_assert(range->cf != NULL);
/* XXX - this doesn't work unless you have a full set of frame_data
* structures for all packets in the capture, which is not,
* for example, the case when TShark is doing a one-pass
* read of a file or a live capture.
*
* It's also horribly slow on large captures, causing it to
* take a long time for the Save As dialog to pop up, for
* example. This obviously can't be kept in the capture_file
* structure and recalculated whenever we filter the display
* or mark frames as ignored, as the results of this depend
* on what the user specifies. In some cases, limiting the
* frame_data structures at which we look to the ones specified
* by the user might help, but if most of the frames are in
* the range, that won't help. In that case, if we could
* examine the *complement* of the range, and *subtract* them
* from the statistics for the capture as a whole, that might
* help, but if the user specified about *half* the packets in
* the range, that won't help, either.
*/
if (range->cf->provider.frames != NULL) {
for(framenum = 1; framenum <= range->cf->count; framenum++) {
packet = frame_data_sequence_find(range->cf->provider.frames, framenum);
if (value_is_in_range(range->user_range, framenum)) {
range->user_range_cnt++;
if (packet->ignored) {
range->ignored_user_range_cnt++;
}
depended_frames_add(range->user_range_plus_depends, range->cf->provider.frames, packet);
if (packet->passed_dfilter) {
range->displayed_user_range_cnt++;
if (packet->ignored) {
range->displayed_ignored_user_range_cnt++;
}
depended_frames_add(range->displayed_user_range_plus_depends, range->cf->provider.frames, packet);
}
}
}
range->user_range_plus_depends_cnt = g_hash_table_size(range->user_range_plus_depends);
range->displayed_user_range_plus_depends_cnt = g_hash_table_size(range->displayed_user_range_plus_depends);
}
}
static void packet_range_calc_selection(packet_range_t *range) {
guint32 framenum;
frame_data *packet;
range->selection_range_cnt = 0;
range->ignored_selection_range_cnt = 0;
range->displayed_selection_range_cnt = 0;
range->displayed_ignored_selection_range_cnt = 0;
ws_assert(range->cf != NULL);
if (range->cf->provider.frames != NULL) {
for (framenum = 1; framenum <= range->cf->count; framenum++) {
packet = frame_data_sequence_find(range->cf->provider.frames, framenum);
if (value_is_in_range(range->selection_range, framenum)) {
range->selection_range_cnt++;
if (packet->ignored) {
range->ignored_selection_range_cnt++;
}
depended_frames_add(range->selected_plus_depends, range->cf->provider.frames, packet);
if (packet->passed_dfilter) {
range->displayed_selection_range_cnt++;
if (packet->ignored) {
range->displayed_ignored_selection_range_cnt++;
}
depended_frames_add(range->displayed_selected_plus_depends, range->cf->provider.frames, packet);
}
}
}
range->selected_plus_depends_cnt = g_hash_table_size(range->selected_plus_depends);
range->displayed_selected_plus_depends_cnt = g_hash_table_size(range->displayed_selected_plus_depends);
}
}
/* init the range struct */
void packet_range_init(packet_range_t *range, capture_file *cf) {
memset(range, 0, sizeof(packet_range_t));
range->process = range_process_all;
range->user_range = NULL;
range->selection_range = NULL;
range->cf = cf;
range->marked_plus_depends = g_hash_table_new(g_direct_hash, g_direct_equal);
range->displayed_marked_plus_depends = g_hash_table_new(g_direct_hash, g_direct_equal);
range->mark_range_plus_depends = g_hash_table_new(g_direct_hash, g_direct_equal);
range->displayed_mark_range_plus_depends = g_hash_table_new(g_direct_hash, g_direct_equal);
range->user_range_plus_depends = g_hash_table_new(g_direct_hash, g_direct_equal);
range->displayed_user_range_plus_depends = g_hash_table_new(g_direct_hash, g_direct_equal);
range->selected_plus_depends = g_hash_table_new(g_direct_hash, g_direct_equal);
range->displayed_selected_plus_depends = g_hash_table_new(g_direct_hash, g_direct_equal);
/* calculate all packet range counters */
packet_range_calc(range);
packet_range_calc_user(range);
packet_range_calc_selection(range);
}
void packet_range_cleanup(packet_range_t *range) {
wmem_free(NULL, range->user_range);
wmem_free(NULL, range->selection_range);
g_hash_table_destroy(range->marked_plus_depends);
g_hash_table_destroy(range->displayed_marked_plus_depends);
g_hash_table_destroy(range->mark_range_plus_depends);
g_hash_table_destroy(range->displayed_mark_range_plus_depends);
g_hash_table_destroy(range->user_range_plus_depends);
g_hash_table_destroy(range->displayed_user_range_plus_depends);
g_hash_table_destroy(range->selected_plus_depends);
g_hash_table_destroy(range->displayed_selected_plus_depends);
}
/* check whether the packet range is OK */
convert_ret_t packet_range_check(packet_range_t *range) {
if (range->process == range_process_user_range && range->user_range == NULL) {
/* Not valid - return the error. */
return range->user_range_status;
}
if (range->process == range_process_selected && range->selection_range == NULL) {
return range->selection_range_status;
}
return CVT_NO_ERROR;
}
/* init the processing run */
void packet_range_process_init(packet_range_t *range) {
/* Check that, if an explicit range was selected, it's valid. */
/* "enumeration" values */
range->marked_range_active = FALSE;
if (range->process_filtered == FALSE) {
range->marked_range_left = range->mark_range_cnt;
} else {
range->marked_range_left = range->displayed_mark_range_cnt;
}
/* XXX: We could set the count to whichever case is active so we
* could decrement it and return finished.
*/
}
/* do we have to process all packets? */
gboolean packet_range_process_all(packet_range_t *range) {
return range->process == range_process_all && !range->process_filtered && !range->remove_ignored;
}
static range_process_e
packet_range_process_packet_include_depends(packet_range_t *range, frame_data *fdata) {
switch(range->process) {
case(range_process_all):
if (range->process_filtered) {
if ((fdata->passed_dfilter || fdata->dependent_of_displayed) == FALSE) {
return range_process_next;
}
}
break;
case(range_process_selected):
if (range->process_filtered) {
if (!g_hash_table_contains(range->displayed_selected_plus_depends, GUINT_TO_POINTER(fdata->num))) {
return range_process_next;
}
} else {
if (!g_hash_table_contains(range->selected_plus_depends, GUINT_TO_POINTER(fdata->num))) {
return range_process_next;
}
}
break;
case(range_process_marked):
if (range->process_filtered) {
if (!g_hash_table_contains(range->displayed_marked_plus_depends, GUINT_TO_POINTER(fdata->num))) {
return range_process_next;
}
} else {
if (!g_hash_table_contains(range->marked_plus_depends, GUINT_TO_POINTER(fdata->num))) {
return range_process_next;
}
}
break;
case(range_process_marked_range):
if (range->process_filtered) {
if (!g_hash_table_contains(range->displayed_mark_range_plus_depends, GUINT_TO_POINTER(fdata->num))) {
return range_process_next;
}
} else {
if (!g_hash_table_contains(range->mark_range_plus_depends, GUINT_TO_POINTER(fdata->num))) {
return range_process_next;
}
}
break;
case(range_process_user_range):
if (range->process_filtered) {
if (!g_hash_table_contains(range->displayed_user_range_plus_depends, GUINT_TO_POINTER(fdata->num))) {
return range_process_next;
}
} else {
if (!g_hash_table_contains(range->user_range_plus_depends, GUINT_TO_POINTER(fdata->num))) {
return range_process_next;
}
}
break;
default:
ws_assert_not_reached();
}
/* We fell through the conditions above, so we accept this packet */
return range_process_this;
}
/* do we have to process this packet? */
range_process_e packet_range_process_packet(packet_range_t *range, frame_data *fdata) {
/* For ignored packets, since we don't dissect them, we don't know
* anything about packets they depend upon, which is helpful as we
* don't have to calculate more counts based on interaction terms. If
* someone wants to include those, then don't ignore the packet.
*/
if (range->remove_ignored && fdata->ignored) {
return range_process_next;
}
ws_assert(range->cf != NULL);
if (range->include_dependents) {
return packet_range_process_packet_include_depends(range, fdata);
}
switch(range->process) {
case(range_process_all):
break;
case(range_process_selected):
if (value_is_in_range(range->selection_range, fdata->num) == FALSE) {
return range_process_next;
}
break;
case(range_process_marked):
if (fdata->marked == FALSE) {
return range_process_next;
}
break;
case(range_process_marked_range):
if (range->marked_range_left == 0) {
return range_processing_finished;
}
if (fdata->marked == TRUE) {
range->marked_range_active = TRUE;
}
if (range->marked_range_active == FALSE ) {
return range_process_next;
}
if (!range->process_filtered ||
(range->process_filtered && fdata->passed_dfilter == TRUE))
{
range->marked_range_left--;
}
break;
case(range_process_user_range):
if (value_is_in_range(range->user_range, fdata->num) == FALSE) {
return range_process_next;
}
break;
default:
ws_assert_not_reached();
}
/* This packet has to pass the display filter but didn't?
* Try next (if we're including dependent packets we called the
* other function above).
*/
if ((range->process_filtered && fdata->passed_dfilter == FALSE)) {
return range_process_next;
}
/* We fell through the conditions above, so we accept this packet */
return range_process_this;
}
/******************** Range Entry Parser *********************************/
/* Converts a range string to a user range.
* The parameter 'es' points to the string to be converted, and is defined in
* the Save/Print-As widget.
*/
void packet_range_convert_str(packet_range_t *range, const gchar *es)
{
range_t *new_range;
convert_ret_t ret;
if (range->user_range != NULL)
wmem_free(NULL, range->user_range);
ws_assert(range->cf != NULL);
ret = range_convert_str(NULL, &new_range, es, range->cf->count);
if (ret != CVT_NO_ERROR) {
/* range isn't valid */
range->user_range = NULL;
range->user_range_status = ret;
range->user_range_cnt = 0;
range->user_range_plus_depends_cnt = 0;
range->ignored_user_range_cnt = 0;
range->displayed_user_range_cnt = 0;
range->displayed_ignored_user_range_cnt = 0;
range->displayed_user_range_plus_depends_cnt = 0;
return;
}
range->user_range = new_range;
g_hash_table_remove_all(range->user_range_plus_depends);
g_hash_table_remove_all(range->displayed_user_range_plus_depends);
/* calculate new user specified packet range counts */
packet_range_calc_user(range);
} /* packet_range_convert_str */
void packet_range_convert_selection_str(packet_range_t *range, const char *es)
{
range_t *new_range;
convert_ret_t ret;
if (range->selection_range != NULL)
wmem_free(NULL, range->selection_range);
ws_assert(range->cf != NULL);
ret = range_convert_str(NULL, &new_range, es, range->cf->count);
if (ret != CVT_NO_ERROR) {
/* range isn't valid */
range->selection_range = NULL;
range->selection_range_status = ret;
range->selection_range_cnt = 0;
range->selected_plus_depends_cnt = 0;
range->ignored_selection_range_cnt = 0;
range->displayed_selection_range_cnt = 0;
range->displayed_selected_plus_depends_cnt = 0;
range->displayed_ignored_selection_range_cnt = 0;
return;
}
range->selection_range = new_range;
g_hash_table_remove_all(range->selected_plus_depends);
g_hash_table_remove_all(range->displayed_selected_plus_depends);
/* calculate new user specified packet range counts */
packet_range_calc_selection(range);
} |
C/C++ | wireshark/ui/packet_range.h | /** @file
*
* Packet range routines (save, print, ...)
*
* Dick Gooris <[email protected]>
* Ulf Lamping <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef __PACKET_RANGE_H__
#define __PACKET_RANGE_H__
#include <glib.h>
#include <epan/range.h>
#include <epan/frame_data.h>
#include "cfile.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
extern guint32 curr_selected_frame;
typedef enum {
range_process_all,
range_process_selected,
range_process_marked,
range_process_marked_range,
range_process_user_range
} packet_range_e;
typedef struct packet_range_tag {
/* values coming from the UI */
packet_range_e process; /* which range to process */
gboolean process_filtered; /* captured or filtered packets */
gboolean remove_ignored; /* remove ignored packets */
gboolean include_dependents; /* True if packets which are dependents of others should be processed */
/* user specified range(s) and, if null, error status */
range_t *user_range;
convert_ret_t user_range_status;
/* calculated values */
range_t *selection_range; /* the currently selected packets */
convert_ret_t selection_range_status;
/* current packet counts (captured) */
capture_file *cf; /* Associated capture file. */
guint32 mark_range_cnt; /* packets in marked range */
guint32 user_range_cnt; /* packets in user specified range */
guint32 selection_range_cnt; /* packets in the selected range */
guint32 marked_plus_depends_cnt;
guint32 mark_range_plus_depends_cnt;
guint32 user_range_plus_depends_cnt;
guint32 selected_plus_depends_cnt;
guint32 ignored_cnt; /* packets ignored */
guint32 ignored_marked_cnt; /* packets ignored and marked */
guint32 ignored_mark_range_cnt; /* packets ignored in marked range */
guint32 ignored_user_range_cnt; /* packets ignored in user specified range */
guint32 ignored_selection_range_cnt; /* packets ignored in the selected range */
/* current packet counts (displayed) */
guint32 displayed_cnt;
guint32 displayed_plus_dependents_cnt;
guint32 displayed_marked_cnt;
guint32 displayed_mark_range_cnt;
guint32 displayed_user_range_cnt;
guint32 displayed_marked_plus_depends_cnt;
guint32 displayed_mark_range_plus_depends_cnt;
guint32 displayed_user_range_plus_depends_cnt;
guint32 displayed_selection_range_cnt;
guint32 displayed_selected_plus_depends_cnt;
guint32 displayed_ignored_cnt;
guint32 displayed_ignored_marked_cnt;
guint32 displayed_ignored_mark_range_cnt;
guint32 displayed_ignored_user_range_cnt;
guint32 displayed_ignored_selection_range_cnt;
/* Sets of the chosen frames plus any they depend on for each case */
GHashTable *marked_plus_depends;
GHashTable *displayed_marked_plus_depends;
GHashTable *mark_range_plus_depends;
GHashTable *displayed_mark_range_plus_depends;
GHashTable *user_range_plus_depends;
GHashTable *displayed_user_range_plus_depends;
GHashTable *selected_plus_depends;
GHashTable *displayed_selected_plus_depends;
/* "enumeration" values */
gboolean marked_range_active; /* marked range is currently processed */
guint32 marked_range_left; /* marked range packets left to do */
} packet_range_t;
typedef enum {
range_process_this, /* process this packet */
range_process_next, /* skip this packet, process next */
range_processing_finished /* stop processing, required packets done */
} range_process_e;
/* init the range structure */
extern void packet_range_init(packet_range_t *range, capture_file *cf);
/* Cleanup the range structure before the caller frees "range". */
extern void packet_range_cleanup(packet_range_t *range);
/* check whether the packet range is OK */
extern convert_ret_t packet_range_check(packet_range_t *range);
/* init the processing run */
extern void packet_range_process_init(packet_range_t *range);
/* do we have to process all packets? */
extern gboolean packet_range_process_all(packet_range_t *range);
/* do we have to process this packet? */
extern range_process_e packet_range_process_packet(packet_range_t *range, frame_data *fdata);
/* convert user given string to the internal user specified range representation */
extern void packet_range_convert_str(packet_range_t *range, const gchar *es);
/* convert user given string to the internal selection specified range representation */
extern void packet_range_convert_selection_str(packet_range_t *range, const gchar *es);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* __PACKET_RANGE_H__ */ |
C | wireshark/ui/persfilepath_opt.c | /* persfilepath_opt.c
* Routines to handle command-line options to set paths for directories
* containing personal files (configuration, saved captures)
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#include <string.h>
#include <errno.h>
#include <glib.h>
#include <wsutil/filesystem.h>
#include "ui/persfilepath_opt.h"
/*
* process command line option that affects the paths of the directories
* used for personal files (configuration, saved captures)
*/
gboolean
persfilepath_opt(int opt _U_, const char *optstr)
{
gchar *p, *colonp;
colonp = strchr(optstr, ':');
if (colonp == NULL) {
return FALSE;
}
p = colonp;
*p++ = '\0';
/*
* Skip over any white space (there probably won't be any, but
* as we allow it in the preferences file, we might as well
* allow it here).
*/
while (g_ascii_isspace(*p))
p++;
if (*p == '\0') {
/*
* Put the colon back, so if our caller uses, in an
* error message, the string they passed us, the message
* looks correct.
*/
*colonp = ':';
return FALSE;
}
/* directory should be existing */
/* XXX - is this a requirement? */
if(test_for_directory(p) != EISDIR) {
/*
* Put the colon back, so if our caller uses, in an
* error message, the string they passed us, the message
* looks correct.
*/
*colonp = ':';
return FALSE;
}
if (strcmp(optstr,"persconf") == 0) {
set_persconffile_dir(p);
} else if (strcmp(optstr,"persdata") == 0) {
set_persdatafile_dir(p);
} else {
/* XXX - might need to add the temp file path */
return FALSE;
}
*colonp = ':'; /* put the colon back */
return TRUE;
} |
C/C++ | wireshark/ui/persfilepath_opt.h | /** @file
*
* Definitions of routines to handle command-line options to set paths
* for directories containing personal files (configuration, saved
* captures)
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PERSFILEPATH_OPT_H
#define PERSFILEPATH_OPT_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* process command line option that affects the paths of the directories
* used for personal files (configuration, saved captures)
*/
extern gboolean persfilepath_opt(int opt, const char *optstr);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* PERSFILEPATH_OPT_H */ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.