gendispatch.pl 75.3 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (C) 2010-2015 Red Hat, Inc.
E
Eric Blake 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.  If not, see
# <http://www.gnu.org/licenses/>.
#
19 20 21 22 23 24 25 26 27
# This script parses remote_protocol.x or qemu_protocol.x and produces lots of
# boilerplate code for both ends of the remote connection.
#
# The first non-option argument specifies the prefix to be searched for, and
# output to, the boilerplate code.  The second non-option argument is the
# file you want to operate on.  For instance, to generate the dispatch table
# for both remote_protocol.x and qemu_protocol.x, you would run the
# following:
#
28
# gendispatch.pl -t remote ../src/remote/remote_protocol.x
29
# gendispatch.pl -t qemu ../src/remote/qemu_protocol.x
30 31
#
# By Richard Jones <rjones@redhat.com>
32
# Extended by Matthias Bolte <matthias.bolte@googlemail.com>
33 34 35

use strict;

36
use Getopt::Long;
37

38 39 40 41 42
my $mode = "debug";
my $res = GetOptions("mode=s" => \$mode);

die "cannot parse command line options" unless $res;

43
die "unknown mode '$mode', expecting 'client', 'server', " .
44 45
    "'aclheader', 'aclbody', 'aclsym', 'aclapi' or 'debug'"
    unless $mode =~ /^(client|server|aclheader|aclbody|aclsym|aclapi|debug)$/;
46

47 48
my $structprefix = shift or die "missing struct prefix argument";
my $procprefix = shift or die "missing procedure prefix argument";
49 50 51
my $protocol = shift or die "missing protocol argument";
my @autogen;

52
my $connect_ptr = $structprefix eq "admin" ? "virAdmConnectPtr" : "virConnectPtr";
53
my $prefix = ($structprefix eq "admin") ? "admin" : "vir";
54 55 56 57 58 59 60 61 62 63 64 65 66 67

sub fixup_name {
    my $name = shift;

    $name =~ s/Nwfilter/NWFilter/;
    $name =~ s/Xml$/XML/;
    $name =~ s/Uri$/URI/;
    $name =~ s/Uuid$/UUID/;
    $name =~ s/Id$/ID/;
    $name =~ s/Mac$/MAC/;
    $name =~ s/Cpu$/CPU/;
    $name =~ s/Os$/OS/;
    $name =~ s/Nmi$/NMI/;
    $name =~ s/Pm/PM/;
68
    $name =~ s/Fstrim$/FSTrim/;
69 70
    $name =~ s/Fsfreeze$/FSFreeze/;
    $name =~ s/Fsthaw$/FSThaw/;
71
    $name =~ s/Fsinfo$/FSInfo/;
72
    $name =~ s/Iothread$/IOThread/;
O
Osier Yang 已提交
73 74
    $name =~ s/Scsi/SCSI/;
    $name =~ s/Wwn$/WWN/;
75
    $name =~ s/Dhcp$/DHCP/;
76 77 78

    return $name;
}
79 80 81 82

# Convert name_of_call to NameOfCall.
sub name_to_ProcName {
    my $name = shift;
83
    my $forcefix = $structprefix eq "admin";
84 85

    my @elems;
86 87 88

    if ($forcefix || $name =~ /_/ ||
        (lc $name) eq "open" || (lc $name) eq "close") {
89 90 91
        @elems = split /_/, $name;
        @elems = map lc, @elems;
        @elems = map ucfirst, @elems;
92
    } else {
93
        @elems = $name;
94 95 96 97 98 99 100 101 102 103
    }
    @elems = map { fixup_name($_) } @elems;
    my $procname = join "", @elems;

    return $procname;
}

sub name_to_TypeName {
    my $name = shift;

104
    my @elems = split /_/, $name;
105
    @elems = map lc, @elems;
106
    @elems = map ucfirst, @elems;
107 108 109
    @elems = map { fixup_name($_) } @elems;
    my $typename = join "", @elems;
    return $typename;
110 111
}

112 113 114 115 116 117 118 119 120 121 122 123 124
sub push_privconn {
    my $args = shift;

    if (!@$args) {
        if ($structprefix eq "admin") {
            push(@$args, "priv->dmn");
        } else {
            push(@$args, "priv->conn");
        }
    }
}


125 126
# Read the input file (usually remote_protocol.x) and form an
# opinion about the name, args and return type of each RPC.
127
my ($name, $ProcName, $id, $flags, %calls, @calls, %opts);
128

129
my $collect_args_members = 0;
130
my $collect_ret_members = 0;
131
my $collect_opts = 0;
132 133
my $last_name;

134 135 136
open PROTOCOL, "<$protocol" or die "cannot open $protocol: $!";

while (<PROTOCOL>) {
137 138 139 140 141 142
    if ($collect_args_members) {
        if (/^};/) {
            $collect_args_members = 0;
        } elsif ($_ =~ m/^\s*(.*\S)\s*$/) {
            push(@{$calls{$name}->{args_members}}, $1);
        }
143 144 145 146 147 148
    } elsif ($collect_ret_members) {
        if (/^};/) {
            $collect_ret_members = 0;
        } elsif ($_ =~ m/^\s*(.*\S)\s*$/) {
            push(@{$calls{$name}->{ret_members}}, $1);
        }
149
    } elsif ($collect_opts) {
150
        if (m,^\s*\*\s*\@(\w+)\s*:\s*((?:\w|:|\!|\|)+)\s*$,) {
151 152 153 154 155 156 157
            if ($1 eq "acl" ||
                $1 eq "aclfilter") {
                $opts{$1} = [] unless exists $opts{$1};
                push @{$opts{$1}}, $2;
            } else {
                $opts{$1} = $2;
            }
158 159 160 161 162 163 164 165 166 167
        } elsif (m,^\s*\*/\s*$,) {
            $collect_opts = 0;
        } elsif (m,^\s*\*\s*$,) {
            # pass
        } else {
            die "cannot parse $_";
        }
    } elsif (m,/\*\*,) {
        %opts = ();
        $collect_opts = 1;
168 169 170 171
    } elsif (/^struct (${structprefix}_(.*)_args)/ ||
             /^struct (${structprefix}(.*)Args)/) {
        my $structname = $1;
        $name = $2;
172
        $ProcName = name_to_ProcName ($name);
173 174 175
        $name = lc $name;
        $name =~ s/_//g;
        die "duplicate definition of $_"
176 177 178 179 180
            if exists $calls{$name};

        $calls{$name} = {
            name => $name,
            ProcName => $ProcName,
181
            args => $structname,
182 183
            args_members => [],
            ret => "void"
184 185
        };

186
        $collect_args_members = 1;
187
        $collect_ret_members = 0;
188
        $last_name = $name;
189 190 191 192 193
    } elsif (/^struct (${structprefix}_(.*)_ret)\s+{(.*)$/ ||
             /^struct (${structprefix}(.*)Ret)\s+{(.*)$/) {
        my $structname = $1;
        $name = $2;
        $flags = $3;
194
        $ProcName = name_to_ProcName ($name);
195 196
        $name = lc $name;
        $name =~ s/_//g;
197 198

        if (exists $calls{$name}) {
199
            $calls{$name}->{ret} = $structname;
200 201 202 203 204
        } else {
            $calls{$name} = {
                name => $name,
                ProcName => $ProcName,
                args => "void",
205
                ret => $structname,
206
                ret_members => []
207 208
            }
        }
209

210
        if ($flags ne "") {
211 212 213 214 215 216 217
            if (!($flags =~ m/^\s*\/\*\s*insert@(\d+)\s*\*\/\s*$/)) {
                die "invalid generator flags for $calls{$name}->{ret}";
            }

            $calls{$name}->{ret_offset} = int($1);
        }

218
        $collect_args_members = 0;
219 220
        $collect_ret_members = 1;
        $last_name = $name;
221 222 223 224
    } elsif (/^struct (${structprefix}_(.*)_msg)/ ||
             /^struct (${structprefix}(.*)Msg)/) {
        my $structname = $1;
        $name = $2;
225
        $ProcName = name_to_ProcName ($name);
226 227
        $name = lc $name;
        $name =~ s/_//g;
228 229 230
        $calls{$name} = {
            name => $name,
            ProcName => $ProcName,
231
            msg => $structname,
232 233 234
        };

        $collect_args_members = 0;
235
        $collect_ret_members = 0;
236
    } elsif (/^\s*(${procprefix}_PROC_(.*?))\s*=\s*(\d+)\s*,?\s*$/) {
237 238 239
        my $constname = $1;
        $name = $2;
        $id = $3;
240
        $ProcName = name_to_ProcName ($name);
241 242
        $name = lc $name;
        $name =~ s/_//g;
243

244 245 246 247 248 249 250 251 252 253 254 255
        if (!exists $calls{$name}) {
            # that the argument and return value cases have not yet added
            # this procedure to the calls hash means that it has no arguments
            # and no return value. add it to the calls hash now because all
            # procedures have to be listed in the calls hash
            $calls{$name} = {
                name => $name,
                ProcName => $ProcName,
                args => "void",
                ret => "void"
            }
        }
256
        $calls{$name}->{constname} = $constname;
257

258 259 260
        if (!exists $opts{generate}) {
            die "'\@generate' annotation missing for $constname";
        }
261

262 263 264
        if ($opts{generate} !~ /^(both|server|client|none)$/) {
            die "'\@generate' annotation value '$opts{generate}' invalid";
        }
265

266 267 268 269 270 271 272
        if ($opts{generate} eq "both") {
            push(@autogen, $ProcName);
        } elsif ($mode eq "server" && ($opts{generate} eq "server")) {
            push(@autogen, $ProcName);
        } elsif ($mode eq "client" && ($opts{generate} eq "client")) {
            push(@autogen, $ProcName);
        }
273

274 275 276 277 278 279 280 281 282
        if (exists $opts{readstream}) {
            $calls{$name}->{streamflag} = "read";
            $calls{$name}->{streamoffset} = int($opts{readstream});
        } elsif (exists $opts{writestream}) {
            $calls{$name}->{streamflag} = "write";
            $calls{$name}->{streamoffset} = int($opts{writestream});
        } else {
            $calls{$name}->{streamflag} = "none";
        }
283

284 285
        $calls{$name}->{acl} = $opts{acl};
        $calls{$name}->{aclfilter} = $opts{aclfilter};
286

287 288 289 290 291 292
        # for now, we distinguish only two levels of priority:
        # low (0) and high (1)
        if (exists $opts{priority}) {
            if ($opts{priority} eq "high") {
                $calls{$name}->{priority} = 1;
            } elsif ($opts{priority} eq "low") {
293
                $calls{$name}->{priority} = 0;
294 295
            } else {
                die "\@priority annotation value '$opts{priority}' invalid for $constname"
296
            }
297 298
        } else {
            $calls{$name}->{priority} = 0;
299 300
        }

301
        $calls[$id] = $calls{$name};
302 303

        $collect_args_members = 0;
304
        $collect_ret_members = 0;
305 306
    } else {
        $collect_args_members = 0;
307
        $collect_ret_members = 0;
308 309 310
    }
}

311 312
close(PROTOCOL);

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
# this hash contains the procedures that are allowed to map [unsigned] hyper
# to [unsigned] long for legacy reasons in their signature and return type.
# this list is fixed. new procedures and public APIs have to map [unsigned]
# hyper to [unsigned] long long
my $long_legacy = {
    DomainGetInfo               => { ret => { maxMem => 1, memory => 1 } },
    DomainMigrate               => { arg => { flags => 1, resource => 1 } },
    DomainMigrate2              => { arg => { flags => 1, resource => 1 } },
    DomainMigrateBegin3         => { arg => { flags => 1, resource => 1 } },
    DomainMigrateConfirm3       => { arg => { flags => 1, resource => 1 } },
    DomainMigrateDirect         => { arg => { flags => 1, resource => 1 } },
    DomainMigrateFinish         => { arg => { flags => 1 } },
    DomainMigrateFinish2        => { arg => { flags => 1 } },
    DomainMigrateFinish3        => { arg => { flags => 1 } },
    DomainMigratePeer2Peer      => { arg => { flags => 1, resource => 1 } },
    DomainMigratePerform        => { arg => { flags => 1, resource => 1 } },
    DomainMigratePerform3       => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepare        => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepare2       => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepare3       => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepareTunnel  => { arg => { flags => 1, resource => 1 } },
    DomainMigratePrepareTunnel3 => { arg => { flags => 1, resource => 1 } },
    DomainMigrateToURI          => { arg => { flags => 1, resource => 1 } },
    DomainMigrateToURI2         => { arg => { flags => 1, resource => 1 } },
    DomainMigrateVersion1       => { arg => { flags => 1, resource => 1 } },
    DomainMigrateVersion2       => { arg => { flags => 1, resource => 1 } },
    DomainMigrateVersion3       => { arg => { flags => 1, resource => 1 } },
    DomainMigrateSetMaxSpeed    => { arg => { bandwidth => 1 } },
    DomainSetMaxMemory          => { arg => { memory => 1 } },
    DomainSetMemory             => { arg => { memory => 1 } },
    DomainSetMemoryFlags        => { arg => { memory => 1 } },
344 345
    ConnectGetLibVersion        => { ret => { lib_ver => 1 } },
    ConnectGetVersion           => { ret => { hv_ver => 1 } },
346
    NodeGetInfo                 => { ret => { memory => 1 } },
347
    DomainBlockCommit           => { arg => { bandwidth => 1 } },
348
    DomainBlockPull             => { arg => { bandwidth => 1 } },
349
    DomainBlockRebase           => { arg => { bandwidth => 1 } },
350
    DomainBlockJobSetSpeed      => { arg => { bandwidth => 1 } },
351
    DomainMigrateGetMaxSpeed    => { ret => { bandwidth => 1 } },
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
};

sub hyper_to_long
{
    my $proc_name = shift;
    my $ret_or_arg = shift;
    my $member = shift;

    if ($long_legacy->{$proc_name} and
        $long_legacy->{$proc_name}->{$ret_or_arg} and
        $long_legacy->{$proc_name}->{$ret_or_arg}->{$member}) {
        return 1;
    } else {
        return 0
    }
}

369 370 371
#----------------------------------------------------------------------
# Output

372 373
if ($mode eq "aclsym") {
    print <<__EOF__;
374
# Automatically generated from $protocol by gendispatch.pl.
375 376
# Do not edit this file.  Any changes you make will be lost.
__EOF__
377 378 379
} elsif ($mode eq "aclapi") {
    print <<__EOF__;
<!--
380
  -  Automatically generated from $protocol by gendispatch.pl.
381 382 383
  -  Do not edit this file.  Any changes you make will be lost.
  -->
__EOF__
384 385
} else {
    print <<__EOF__;
386
/* Automatically generated from $protocol by gendispatch.pl.
387 388 389
 * Do not edit this file.  Any changes you make will be lost.
 */
__EOF__
390
}
391 392

# Debugging.
393
if ($mode eq "debug") {
394 395 396 397 398
    my @keys = sort (keys %calls);
    foreach (@keys) {
        print "$_:\n";
        print "        name $calls{$_}->{name} ($calls{$_}->{ProcName})\n";
        print "        $calls{$_}->{args} -> $calls{$_}->{ret}\n";
399
        print "        priority -> $calls{$_}->{priority}\n";
400 401 402
    }
}

E
Eric Blake 已提交
403
# Bodies for dispatch functions ("remote_dispatch.h").
404
elsif ($mode eq "server") {
405
    my %generate = map { $_ => 1 } @autogen;
406 407 408
    my @keys = sort (keys %calls);

    foreach (@keys) {
409 410
        my $call = $calls{$_};

411
        # skip things which are REMOTE_MESSAGE
412
        next if $call->{msg};
413

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
        my $name = $structprefix . "Dispatch" . $call->{ProcName};
        my $argtype = $call->{args};
        my $rettype = $call->{ret};

        my $argann = $argtype ne "void" ? "" : " ATTRIBUTE_UNUSED";
        my $retann = $rettype ne "void" ? "" : " ATTRIBUTE_UNUSED";

        # First we print out a function declaration for the
        # real dispatcher body
        print "static int ${name}(\n";
        print "    virNetServerPtr server,\n";
        print "    virNetServerClientPtr client,\n";
        print "    virNetMessagePtr msg,\n";
        print "    virNetMessageErrorPtr rerr";
        if ($argtype ne "void") {
            print ",\n    $argtype *args";
        }
        if ($rettype ne "void") {
            print ",\n    $rettype *ret";
        }
        print ");\n";


        # Next we print out a generic wrapper method which has
        # fixed function signature, for use in the dispatcher
        # table. This simply callers the real dispatcher method
        print "static int ${name}Helper(\n";
        print "    virNetServerPtr server,\n";
        print "    virNetServerClientPtr client,\n";
        print "    virNetMessagePtr msg,\n";
        print "    virNetMessageErrorPtr rerr,\n";
        print "    void *args$argann,\n";
        print "    void *ret$retann)\n";
        print "{\n";
448 449
        print "  int rv;\n";
        print "  virThreadJobSet(\"$name\");\n";
450 451
        print "  VIR_DEBUG(\"server=%p client=%p msg=%p rerr=%p args=%p ret=%p\",\n";
        print "            server, client, msg, rerr, args, ret);\n";
452
        print "  rv = $name(server, client, msg, rerr";
453 454 455 456 457 458 459
        if ($argtype ne "void") {
            print ", args";
        }
        if ($rettype ne "void") {
            print ", ret";
        }
        print ");\n";
460 461
        print "  virThreadJobClear(rv);\n";
        print "  return rv;\n";
462 463 464 465
        print "}\n";

        # Finally we print out the dispatcher method body impl
        # (if possible)
466 467 468 469 470
        if (!exists($generate{$call->{ProcName}})) {
            print "/* ${structprefix}Dispatch$call->{ProcName} body has " .
                  "to be implemented manually */\n\n\n\n";
            next;
        }
471 472 473

        my $has_node_device = 0;
        my @vars_list = ();
474
        my @optionals_list = ();
475 476
        my @getters_list = ();
        my @args_list = ();
477
        my @prepare_ret_list = ();
478
        my @ret_list = ();
479
        my @free_list = ();
480
        my @free_list_on_error = ("virNetMessageSaveError(rerr);");
481

482
        # handle arguments to the function
483
        if ($argtype ne "void") {
484
            # node device is special, as it's identified by name
485 486
            if ($argtype =~ m/^remote_node_device_/ and
                !($argtype =~ m/^remote_node_device_lookup_by_name_/) and
O
Osier Yang 已提交
487 488
                !($argtype =~ m/^remote_node_device_create_xml_/) and
                !($argtype =~ m/^remote_node_device_lookup_scsi_host_by_wwn_/)) {
489 490 491
                $has_node_device = 1;
                push(@vars_list, "virNodeDevicePtr dev = NULL");
                push(@getters_list,
492
                     "    if (!(dev = virNodeDeviceLookupByName(priv->conn, args->name)))\n" .
493 494 495
                     "        goto cleanup;\n");
                push(@args_list, "dev");
                push(@free_list,
496
                     "    virObjectUnref(dev);");
497 498
            }

499
            foreach my $args_member (@{$call->{args_members}}) {
500 501 502
                if ($args_member =~ m/^remote_nonnull_string name;/ and $has_node_device) {
                    # ignore the name arg for node devices
                    next
503
                } elsif ($args_member =~ m/^remote_nonnull_(domain|network|storage_pool|storage_vol|interface|secret|nwfilter) (\S+);/) {
504
                    my $type_name = name_to_TypeName($1);
505 506

                    push(@vars_list, "vir${type_name}Ptr $2 = NULL");
507
                    push(@getters_list,
508
                         "    if (!($2 = get_nonnull_$1(priv->conn, args->$2)))\n" .
509
                         "        goto cleanup;\n");
510
                    push(@args_list, "$2");
511
                    push(@free_list,
512
                         "    virObjectUnref($2);");
513 514 515 516
                } elsif ($args_member =~ m/^remote_nonnull_domain_snapshot /) {
                    push(@vars_list, "virDomainPtr dom = NULL");
                    push(@vars_list, "virDomainSnapshotPtr snapshot = NULL");
                    push(@getters_list,
517
                         "    if (!(dom = get_nonnull_domain(priv->conn, args->snap.dom)))\n" .
518 519 520 521 522 523
                         "        goto cleanup;\n" .
                         "\n" .
                         "    if (!(snapshot = get_nonnull_domain_snapshot(dom, args->snap)))\n" .
                         "        goto cleanup;\n");
                    push(@args_list, "snapshot");
                    push(@free_list,
524 525
                         "    virObjectUnref(snapshot);\n" .
                         "    virObjectUnref(dom);");
526 527 528 529 530 531
                } elsif ($args_member =~ m/^(?:(admin|remote)_string|remote_uuid) (\S+)<\S+>;/) {
                    push_privconn(\@args_list);
                    push(@args_list, "args->$2.$2_val");
                    push(@args_list, "args->$2.$2_len");
                } elsif ($args_member =~ m/^(?:opaque|(admin|remote)_nonnull_string) (\S+)<\S+>;(.*)$/) {
                    push_privconn(\@args_list);
532

533
                    my $cast = "";
534 535
                    my $arg_name = $2;
                    my $annotation = $3;
536 537 538 539 540 541 542 543 544 545 546

                    if ($annotation ne "") {
                        if ($annotation =~ m/\s*\/\*\s*(.*)\s*\*\//) {
                            $cast = $1;
                        } else {
                            die "malformed cast annotation for argument: $args_member";
                        }
                    }

                    push(@args_list, "${cast}args->$arg_name.${arg_name}_val");
                    push(@args_list, "args->$arg_name.${arg_name}_len");
547
                } elsif ($args_member =~ m/^(?:unsigned )?int (\S+)<\S+>;/) {
548
                    push_privconn(\@args_list);
549 550 551

                    push(@args_list, "args->$1.$1_val");
                    push(@args_list, "args->$1.$1_len");
552 553
                } elsif ($args_member =~ m/^remote_typed_param (\S+)<(\S+)>;/) {
                    push(@vars_list, "virTypedParameterPtr $1 = NULL");
E
Eric Blake 已提交
554
                    push(@vars_list, "int n$1 = 0");
555 556 557
                    if ($call->{ProcName} eq "NodeSetMemoryParameters") {
                        push(@args_list, "priv->conn");
                    }
558 559 560 561 562 563 564
                    push(@args_list, "$1");
                    push(@args_list, "n$1");
                    push(@getters_list, "    if (($1 = remoteDeserializeTypedParameters(args->$1.$1_val,\n" .
                                        "                                                   args->$1.$1_len,\n" .
                                        "                                                   $2,\n" .
                                        "                                                   &n$1)) == NULL)\n" .
                                        "        goto cleanup;\n");
565
                    push(@free_list, "    virTypedParamsFree($1, n$1);");
566 567 568 569
                } elsif ($args_member =~ m/<\S+>;/ or $args_member =~ m/\[\S+\];/) {
                    # just make all other array types fail
                    die "unhandled type for argument value: $args_member";
                } elsif ($args_member =~ m/^remote_uuid (\S+);/) {
570
                    push_privconn(\@args_list);
571

572
                    push(@args_list, "(unsigned char *) args->$1");
573 574
                } elsif ($args_member =~ m/^(admin|remote)_string (\S+);/) {
                    push_privconn(\@args_list);
575

576 577 578 579 580
                    push(@vars_list, "char *$2");
                    push(@optionals_list, "$2");
                    push(@args_list, "$2");
                } elsif ($args_member =~ m/^(admin|remote)_nonnull_string (\S+);/) {
                    push_privconn(\@args_list);
581

582
                    push(@args_list, "args->$2");
583
                } elsif ($args_member =~ m/^(unsigned )?int (\S+);/) {
584
                    push_privconn(\@args_list);
585

586 587
                    push(@args_list, "args->$2");
                } elsif ($args_member =~ m/^(unsigned )?hyper (\S+);/) {
588
                    push_privconn(\@args_list);
589 590 591 592 593 594 595 596 597 598 599 600 601

                    my $arg_name = $2;

                    if (hyper_to_long($call->{ProcName}, "arg", $arg_name)) {
                        my $type_name = $1; $type_name .= "long";
                        my $sign = ""; $sign = "U" if ($1);

                        push(@vars_list, "$type_name $arg_name");
                        push(@getters_list, "    HYPER_TO_${sign}LONG($arg_name, args->$arg_name);\n");
                        push(@args_list, "$arg_name");
                    } else {
                        push(@args_list, "args->$arg_name");
                    }
602
                } elsif ($args_member =~ m/^(\/)?\*/) {
603 604 605
                    # ignore comments
                } else {
                    die "unhandled type for argument value: $args_member";
606 607 608 609
                }
            }
        }

610
        # handle return values of the function
611 612 613
        my $single_ret_var = "undefined";
        my $single_ret_by_ref = 0;
        my $single_ret_check = " == undefined";
614 615 616 617
        my $single_ret_as_list = 0;
        my $single_ret_list_name = "undefined";
        my $single_ret_list_max_var = "undefined";
        my $single_ret_list_max_define = "undefined";
618 619
        my $multi_ret = 0;

620
        if ($rettype ne "void" and
621
            scalar(@{$call->{ret_members}}) > 1) {
622 623
            $multi_ret = 1;
        }
624

625
        if ($rettype ne "void") {
626
            foreach my $ret_member (@{$call->{ret_members}}) {
627
                if ($multi_ret) {
628
                    if ($ret_member =~ m/^(unsigned )?(char|short|int|hyper) (\S+)\[\S+\];/) {
629 630 631 632
                        if ($2 eq "hyper" and hyper_to_long($call->{ProcName}, "ret", $3)) {
                            die "legacy [u]long hyper arrays aren't supported";
                        }

633
                        push(@ret_list, "memcpy(ret->$3, tmp.$3, sizeof(ret->$3));");
634 635
                    } elsif ($ret_member =~ m/^(unsigned )?(char|short|int|hyper) (\S+);/) {
                        push(@ret_list, "ret->$3 = tmp.$3;");
636 637 638
                    } else {
                        die "unhandled type for multi-return-value: $ret_member";
                    }
639
                } elsif ($ret_member =~ m/^(admin|remote)_nonnull_string (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
640
                    push(@vars_list, "int len");
641 642 643
                    splice(@args_list, int($4), 0, ("ret->$2.$2_val"));
                    push(@ret_list, "ret->$2.$2_len = len;");
                    push(@free_list_on_error, "VIR_FREE(ret->$2.$2_val);");
644 645 646 647
                    $single_ret_var = "len";
                    $single_ret_by_ref = 0;
                    $single_ret_check = " < 0";
                    $single_ret_as_list = 1;
648 649 650 651
                    $single_ret_list_name = $2;
                    $single_ret_list_max_var = "max$2";
                    $single_ret_list_max_define = $3;
                } elsif ($ret_member =~ m/^(admin|remote)_nonnull_string (\S+)<\S+>;/) {
652
                    # error out on unannotated arrays
653 654
                    die "$1_nonnull_string array without insert@<offset> annotation: $ret_member";
                } elsif ($ret_member =~ m/^(admin|remote)_nonnull_string (\S+);/) {
655
                    if ($call->{ProcName} eq "ConnectGetType") {
656 657
                        # SPECIAL: virConnectGetType returns a constant string that must
                        #          not be freed. Therefore, duplicate the string here.
658
                        push(@vars_list, "const char *$2");
659
                        push(@ret_list, "/* We have to VIR_STRDUP because remoteDispatchClientRequest will");
660
                        push(@ret_list, " * free this string after it's been serialised. */");
661
                        push(@ret_list, "if (VIR_STRDUP(ret->type, type) < 0)");
662 663
                        push(@ret_list, "    goto cleanup;");
                    } else {
664 665
                        push(@vars_list, "char *$2");
                        push(@ret_list, "ret->$2 = $2;");
666 667
                    }

668
                    $single_ret_var = $2;
669 670
                    $single_ret_by_ref = 0;
                    $single_ret_check = " == NULL";
671 672 673 674 675 676
                } elsif ($ret_member =~ m/^(admin|remote)_string (\S+);/) {
                    push(@vars_list, "char *$2 = NULL");
                    push(@vars_list, "char **$2_p = NULL");
                    push(@ret_list, "ret->$2 = $2_p;");
                    push(@free_list, "    VIR_FREE($2);");
                    push(@free_list_on_error, "VIR_FREE($2_p);");
677
                    push(@prepare_ret_list,
678
                         "if (VIR_ALLOC($2_p) < 0)\n" .
679
                         "        goto cleanup;\n" .
680
                         "\n" .
681
                         "    if (VIR_STRDUP(*$2_p, $2) < 0)\n".
682
                         "        goto cleanup;\n");
683

684
                    $single_ret_var = $2;
685 686
                    $single_ret_by_ref = 0;
                    $single_ret_check = " == NULL";
687
                } elsif ($ret_member =~ m/^remote_nonnull_(domain|network|storage_pool|storage_vol|interface|node_device|secret|nwfilter|domain_snapshot) (\S+);/) {
688
                    my $type_name = name_to_TypeName($1);
689

690 691 692 693 694 695 696 697 698 699
                    if ($call->{ProcName} eq "DomainCreateWithFlags") {
                        # SPECIAL: virDomainCreateWithFlags updates the given
                        #          domain object instead of returning a new one
                        push(@ret_list, "make_nonnull_$1(&ret->$2, $2);");
                        $single_ret_var = undef;
                        $single_ret_by_ref = 1;
                    } else {
                        push(@vars_list, "vir${type_name}Ptr $2 = NULL");
                        push(@ret_list, "make_nonnull_$1(&ret->$2, $2);");
                        push(@free_list,
700
                             "    virObjectUnref($2);");
701 702 703 704
                        $single_ret_var = $2;
                        $single_ret_by_ref = 0;
                        $single_ret_check = " == NULL";
                    }
705
                } elsif ($ret_member =~ m/^int (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
706
                    push(@vars_list, "int len");
707
                    splice(@args_list, int($3), 0, ("ret->$1.$1_val"));
708
                    push(@ret_list, "ret->$1.$1_len = len;");
709
                    push(@free_list_on_error, "VIR_FREE(ret->$1.$1_val);");
710 711 712 713 714 715 716
                    $single_ret_var = "len";
                    $single_ret_by_ref = 0;
                    $single_ret_check = " < 0";
                    $single_ret_as_list = 1;
                    $single_ret_list_name = $1;
                    $single_ret_list_max_var = "max$1";
                    $single_ret_list_max_define = $2;
717 718 719
                } elsif ($ret_member =~ m/^int (\S+)<\S+>;/) {
                    # error out on unannotated arrays
                    die "int array without insert@<offset> annotation: $ret_member";
720
                } elsif ($ret_member =~ m/^int (\S+);/) {
721 722 723 724
                    push(@vars_list, "int $1");
                    push(@ret_list, "ret->$1 = $1;");
                    $single_ret_var = $1;

725
                    if ($call->{ProcName} =~ m/GetAutostart$/) {
726 727 728
                        $single_ret_by_ref = 1;
                    } else {
                        $single_ret_by_ref = 0;
729

730
                        if ($call->{ProcName} eq "CPUCompare") {
731 732 733 734
                            $single_ret_check = " == VIR_CPU_COMPARE_ERROR";
                        } else {
                            $single_ret_check = " < 0";
                        }
735
                    }
736
                } elsif ($ret_member =~ m/^(?:unsigned )?hyper (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
737 738 739 740
                    if (hyper_to_long($call->{ProcName}, "ret", $1)) {
                        die "legacy [u]long hyper arrays aren't supported";
                    }

741 742
                    push(@vars_list, "int len");
                    push(@ret_list, "ret->$1.$1_len = len;");
743
                    push(@free_list_on_error, "VIR_FREE(ret->$1.$1_val);");
744 745 746 747
                    $single_ret_var = "len";
                    $single_ret_by_ref = 0;
                    $single_ret_as_list = 1;
                    $single_ret_list_name = $1;
748
                    $single_ret_list_max_var = "max$1";
749 750
                    $single_ret_list_max_define = $2;

751
                    if ($call->{ProcName} eq "NodeGetCellsFreeMemory") {
752
                        $single_ret_check = " <= 0";
753
                        splice(@args_list, int($3), 0, ("(unsigned long long *)ret->$1.$1_val"));
754 755
                    } else {
                        $single_ret_check = " < 0";
756
                        splice(@args_list, int($3), 0, ("ret->$1.$1_val"));
757
                    }
758
                } elsif ($ret_member =~ m/^(?:unsigned )?hyper (\S+)<\S+>;/) {
759 760
                    # error out on unannotated arrays
                    die "hyper array without insert@<offset> annotation: $ret_member";
761
                } elsif ($ret_member =~ m/^(unsigned )?hyper (\S+);(?:\s*\/\*\s*insert@(\d+)\s*\*\/)?/) {
762
                    my $type_name = $1;
763
                    my $ret_name = $2;
764
                    my $ret_assign;
765
                    my $insert = $3;
766

767 768 769 770 771 772 773 774 775
                    if (hyper_to_long($call->{ProcName}, "ret", $ret_name)) {
                        my $sign = ""; $sign = "U" if ($1);

                        $type_name .= "long";
                        $ret_assign = "HYPER_TO_${sign}LONG(ret->$ret_name, $ret_name);";
                    } else {
                        $type_name .= "long long";
                        $ret_assign = "ret->$ret_name = $ret_name;";
                    }
776 777

                    push(@vars_list, "$type_name $ret_name");
778
                    push(@ret_list, $ret_assign);
779 780 781 782 783 784 785

                    if ($insert) {
                        splice(@args_list, int($insert), 0, "&$ret_name");
                        $single_ret_var = undef;
                    } else {
                        $single_ret_var = $ret_name;
                    }
786

787 788
                    if ($call->{ProcName} eq "DomainGetMaxMemory" or
                        $call->{ProcName} eq "NodeGetFreeMemory") {
789 790 791
                        # SPECIAL: virDomainGetMaxMemory and virNodeGetFreeMemory
                        #          return the actual value directly and 0 indicates
                        #          an error
792 793 794 795 796
                        $single_ret_by_ref = 0;
                        $single_ret_check = " == 0";
                    } else {
                        $single_ret_by_ref = 1;
                    }
797 798 799 800 801 802 803 804 805 806 807 808
                } elsif ($ret_member =~ m/^opaque (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
                    push(@vars_list, "char *$1 = NULL");
                    push(@vars_list, "int $1_len = 0");
                    splice(@args_list, int($3), 0, ("&$1", "&$1_len"));
                    push(@ret_list, "ret->$1.$1_val = $1;");
                    push(@ret_list, "ret->$1.$1_len = $1_len;");
                    push(@free_list_on_error, "VIR_FREE($1);");
                    $single_ret_var = undef;
                    $single_ret_by_ref = 1;
                } elsif ($ret_member =~ m/^opaque (\S+)<\S+>;/) {
                    # error out on unannotated arrays
                    die "opaque array without insert@<offset> annotation: $ret_member";
809 810
                } elsif ($ret_member =~ m/^(\/)?\*/) {
                    # ignore comments
811 812
                } else {
                    die "unhandled type for return value: $ret_member";
813 814 815 816
                }
            }
        }

817
        # select struct type for multi-return-value functions
818
        if ($multi_ret) {
819 820 821 822
            if (!(defined $call->{ret_offset})) {
                die "multi-return-value without insert@<offset> annotation: $call->{ret}";
            }

823
            push_privconn(\@args_list);
824

825
            my $struct_name = $call->{ProcName};
826 827
            $struct_name =~ s/Get//;

828 829 830 831
            splice(@args_list, $call->{ret_offset}, 0, ("&tmp"));

            if ($call->{ProcName} eq "DomainBlockStats" ||
                $call->{ProcName} eq "DomainInterfaceStats") {
832 833 834
                # SPECIAL: virDomainBlockStats and virDomainInterfaceStats
                #          have a 'Struct' suffix on the actual struct name
                #          and take the struct size as additional argument
835
                $struct_name .= "Struct";
836
                splice(@args_list, $call->{ret_offset} + 1, 0, ("sizeof(tmp)"));
837 838 839 840 841
            }

            push(@vars_list, "vir$struct_name tmp");
        }

842
        if ($call->{streamflag} ne "none") {
843
            splice(@args_list, $call->{streamoffset}, 0, ("st"));
844
            push(@free_list_on_error, "if (stream) {");
845 846 847
            push(@free_list_on_error, "    virStreamAbort(st);");
            push(@free_list_on_error, "    daemonFreeClientStream(client, stream);");
            push(@free_list_on_error, "} else {");
848
            push(@free_list_on_error, "    virObjectUnref(st);");
849 850 851
            push(@free_list_on_error, "}");
        }

852
        # print functions signature
853 854 855 856 857
        print "static int $name(\n";
        print "    virNetServerPtr server ATTRIBUTE_UNUSED,\n";
        print "    virNetServerClientPtr client,\n";
        print "    virNetMessagePtr msg ATTRIBUTE_UNUSED,\n";
        print "    virNetMessageErrorPtr rerr";
858
        if ($argtype ne "void") {
859 860
            print ",\n    $argtype *args";
        }
861
        if ($rettype ne "void") {
862 863 864
            print ",\n    $rettype *ret";
        }
        print ")\n";
865 866 867 868 869

        # print function body
        print "{\n";
        print "    int rv = -1;\n";

870 871 872
        foreach my $var (@vars_list) {
            print "    $var;\n";
        }
873 874 875 876 877 878

        if ($structprefix eq "admin") {
            print "    struct daemonAdmClientPrivate *priv =\n";
        } else {
            print "    struct daemonClientPrivate *priv =\n";
        }
879
        print "        virNetServerClientGetPrivateData(client);\n";
880

881
        if ($call->{streamflag} ne "none") {
882 883
            print "    virStreamPtr st = NULL;\n";
            print "    daemonClientStreamPtr stream = NULL;\n";
884 885
        }

886
        print "\n";
887 888 889 890 891 892 893

        if ($structprefix eq "admin") {
            print "    if (!priv->dmn) {\n";
        } else {
            print "    if (!priv->conn) {\n";
        }

894
        print "        virReportError(VIR_ERR_INTERNAL_ERROR, \"%s\", _(\"connection not open\"));\n";
895 896 897 898
        print "        goto cleanup;\n";
        print "    }\n";
        print "\n";

899 900
        if ($single_ret_as_list) {
            print "    if (args->$single_ret_list_max_var > $single_ret_list_max_define) {\n";
901 902
            print "        virReportError(VIR_ERR_INTERNAL_ERROR,\n";
            print "                       \"%s\", _(\"max$single_ret_list_name > $single_ret_list_max_define\"));\n";
903 904 905 906 907
            print "        goto cleanup;\n";
            print "    }\n";
            print "\n";
        }

908 909
        print join("\n", @getters_list);

910 911 912
        if (@getters_list) {
            print "\n";
        }
913

914 915 916 917 918 919 920 921
        foreach my $optional (@optionals_list) {
            print "    $optional = args->$optional ? *args->$optional : NULL;\n";
        }

        if (@optionals_list) {
            print "\n";
        }

922
        if ($call->{streamflag} ne "none") {
923 924 925
            print "    if (!(st = virStreamNew(priv->conn, VIR_STREAM_NONBLOCK)))\n";
            print "        goto cleanup;\n";
            print "\n";
926
            print "    if (!(stream = daemonCreateClientStream(client, st, remoteProgram, &msg->header)))\n";
927 928 929 930
            print "        goto cleanup;\n";
            print "\n";
        }

931
        if ($rettype eq "void") {
932
            print "    if ($prefix$call->{ProcName}(";
933 934 935 936
            print join(', ', @args_list);
            print ") < 0)\n";
            print "        goto cleanup;\n";
            print "\n";
937
        } elsif (!$multi_ret) {
938
            my $proc_name = $call->{ProcName};
939

940
            push_privconn(\@args_list);
941

942 943 944
            if ($structprefix eq "qemu" &&
                $call->{ProcName} =~ /^(Connect)?Domain/) {
                $proc_name =~ s/^((Connect)?Domain)/${1}Qemu/;
945
            }
946 947 948
            if ($structprefix eq "lxc" && $call->{ProcName} =~ /^Domain/) {
                $proc_name =~ s/^(Domain)/${1}Lxc/;
            }
949

950 951 952
            if ($single_ret_as_list) {
                print "    /* Allocate return buffer. */\n";
                print "    if (VIR_ALLOC_N(ret->$single_ret_list_name.${single_ret_list_name}_val," .
953
                      " args->$single_ret_list_max_var) < 0)\n";
954 955 956 957
                print "        goto cleanup;\n";
                print "\n";
            }

958
            if ($single_ret_by_ref) {
959
                print "    if ($prefix$proc_name(";
960
                print join(', ', @args_list);
961 962 963 964 965 966

                if (defined $single_ret_var) {
                    print ", &$single_ret_var";
                }

                print ") < 0)\n";
967
            } else {
968
                print "    if (($single_ret_var = $prefix$proc_name(";
969 970 971 972 973 974
                print join(', ', @args_list);
                print "))$single_ret_check)\n";
            }

            print "        goto cleanup;\n";
            print "\n";
975
        } else {
976
            print "    if (vir$call->{ProcName}(";
977 978 979 980
            print join(', ', @args_list);
            print ") < 0)\n";
            print "        goto cleanup;\n";
            print "\n";
981
        }
982

983
        if ($call->{streamflag} ne "none") {
984
            print "    if (daemonAddClientStream(client, stream, ";
985 986

            if ($call->{streamflag} eq "write") {
987
                print "false";
988
            } else {
989
                print "true";
990 991
            }

992 993 994 995 996
            print ") < 0)\n";
            print "        goto cleanup;\n";
            print "\n";
        }

997 998 999 1000 1001 1002
        if (@prepare_ret_list) {
            print "    ";
            print join("\n    ", @prepare_ret_list);
            print "\n";
        }

1003 1004
        if (@ret_list) {
            print "    ";
1005
            print join("\n    ", @ret_list);
1006
            print "\n";
1007 1008 1009 1010 1011
        }

        print "    rv = 0;\n";
        print "\n";
        print "cleanup:\n";
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
        print "    if (rv < 0)";

        if (scalar(@free_list_on_error) > 1) {
            print " {";
        }

        print "\n        ";
        print join("\n        ", @free_list_on_error);
        print "\n";

        if (scalar(@free_list_on_error) > 1) {
            print "    }\n";
        }
1025 1026 1027

        print join("\n", @free_list);

1028 1029 1030 1031
        if (@free_list) {
            print "\n";
        }

1032
        print "    return rv;\n";
1033
        print "}\n\n\n\n";
1034
    }
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045


    # Finally we write out the huge dispatch table which lists
    # the dispatch helper method. the XDR proc for processing
    # args and return values, and the size of the args and
    # return value structs. All methods are marked as requiring
    # authentication. Methods are selectively relaxed in the
    # daemon code which registers the program.

    print "virNetServerProgramProc ${structprefix}Procs[] = {\n";
    for ($id = 0 ; $id <= $#calls ; $id++) {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
        my ($comment, $name, $argtype, $arglen, $argfilter, $retlen, $retfilter, $priority);

        if (defined $calls[$id] && !$calls[$id]->{msg}) {
            $comment = "/* Method $calls[$id]->{ProcName} => $id */";
            $name = $structprefix . "Dispatch" . $calls[$id]->{ProcName} . "Helper";
            my $argtype = $calls[$id]->{args};
            my $rettype = $calls[$id]->{ret};
            $arglen = $argtype ne "void" ? "sizeof($argtype)" : "0";
            $retlen = $rettype ne "void" ? "sizeof($rettype)" : "0";
            $argfilter = $argtype ne "void" ? "xdr_$argtype" : "xdr_void";
            $retfilter = $rettype ne "void" ? "xdr_$rettype" : "xdr_void";
        } else {
            if ($calls[$id]->{msg}) {
                $comment = "/* Async event $calls[$id]->{ProcName} => $id */";
            } else {
                $comment = "/* Unused $id */";
            }
            $name = "NULL";
            $arglen = $retlen = 0;
            $argfilter = "xdr_void";
            $retfilter = "xdr_void";
        }
1068

1069 1070
    $priority = defined $calls[$id]->{priority} ? $calls[$id]->{priority} : 0;

1071
        print "{ $comment\n   ${name},\n   $arglen,\n   (xdrproc_t)$argfilter,\n   $retlen,\n   (xdrproc_t)$retfilter,\n   true,\n   $priority\n},\n";
1072 1073 1074
    }
    print "};\n";
    print "size_t ${structprefix}NProcs = ARRAY_CARDINALITY(${structprefix}Procs);\n";
1075
}
1076

1077
# Bodies for client functions ("remote_client_bodies.h").
1078
elsif ($mode eq "client") {
1079
    my %generate = map { $_ => 1 } @autogen;
1080 1081 1082 1083 1084 1085 1086 1087
    my @keys = sort (keys %calls);

    foreach (@keys) {
        my $call = $calls{$_};

        # skip things which are REMOTE_MESSAGE
        next if $call->{msg};

1088 1089
        # skip procedures not on generate list
        next if ! exists($generate{$call->{ProcName}});
1090

1091 1092
        my $argtype = $call->{args};
        my $rettype = $call->{ret};
1093

1094
        # handle arguments to the function
1095 1096
        my @args_list = ();
        my @vars_list = ();
1097
        my @args_check_list = ();
1098
        my @setters_list = ();
1099
        my @setters_list2 = ();
1100
        my @free_list = ();
1101
        my $priv_src = "conn";
1102
        my $call_args = "&args";
1103

1104
        if ($argtype eq "void") {
1105
            $call_args = "NULL";
1106
        } else {
1107
            push(@vars_list, "$argtype args");
1108 1109 1110 1111 1112

            my $is_first_arg = 1;
            my $has_node_device = 0;

            # node device is special
1113 1114 1115
            if ($argtype =~ m/^remote_node_/ and
                !($argtype =~ m/^remote_node_device_lookup_by_name_/) and
                !($argtype =~ m/^remote_node_device_create_xml_/)) {
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
                $has_node_device = 1;
            }

            foreach my $args_member (@{$call->{args_members}}) {
                if ($args_member =~ m/^remote_nonnull_string name;/ and $has_node_device) {
                    $priv_src = "dev->conn";
                    push(@args_list, "virNodeDevicePtr dev");
                    push(@setters_list, "args.name = dev->name;");
                } elsif ($args_member =~ m/^remote_nonnull_(domain|network|storage_pool|storage_vol|interface|secret|nwfilter|domain_snapshot) (\S+);/) {
                    my $name = $1;
1126
                    my $arg_name = $2;
1127
                    my $type_name = name_to_TypeName($name);
1128 1129 1130

                    if ($is_first_arg) {
                        if ($name eq "domain_snapshot") {
1131
                            $priv_src = "$arg_name->domain->conn";
1132
                        } else {
1133
                            $priv_src = "$arg_name->conn";
1134 1135 1136
                        }
                    }

1137 1138 1139 1140 1141
                    push(@args_list, "vir${type_name}Ptr $arg_name");
                    push(@setters_list, "make_nonnull_$1(&args.$arg_name, $arg_name);");
                } elsif ($args_member =~ m/^remote_uuid (\S+);/) {
                    push(@args_list, "const unsigned char *$1");
                    push(@setters_list, "memcpy(args.$1, $1, VIR_UUID_BUFLEN);");
1142 1143 1144 1145
                } elsif ($args_member =~ m/^(admin|remote)_string (\S+);/) {
                    push(@args_list, "const char *$2");
                    push(@setters_list, "args.$2 = $2 ? (char **)&$2 : NULL;");
                } elsif ($args_member =~ m/^(admin|remote)_nonnull_string (\S+)<(\S+)>;(.*)$/) {
1146
                    my $type_name = "const char **";
1147 1148 1149
                    my $arg_name = $2;
                    my $limit = $3;
                    my $annotation = $4;
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162

                    if ($annotation ne "") {
                        if ($annotation =~ m/\s*\/\*\s*\((.*)\)\s*\*\//) {
                            $type_name = $1;
                        } else {
                            die "malformed cast annotation for argument: $args_member";
                        }
                    }

                    push(@args_list, "$type_name$arg_name");
                    push(@args_list, "unsigned int ${arg_name}len");
                    push(@setters_list, "args.$arg_name.${arg_name}_val = (char **)$arg_name;");
                    push(@setters_list, "args.$arg_name.${arg_name}_len = ${arg_name}len;");
1163 1164 1165 1166
                    push(@args_check_list, { name => "\"$arg_name\"", arg => "${arg_name}len", limit => $3 });
                } elsif ($args_member =~ m/^(admin|remote)_nonnull_string (\S+);/) {
                    push(@args_list, "const char *$2");
                    push(@setters_list, "args.$2 = (char *)$2;");
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
                } elsif ($args_member =~ m/^opaque (\S+)<(\S+)>;(.*)$/) {
                    my $type_name = "const char *";
                    my $arg_name = $1;
                    my $limit = $2;
                    my $annotation = $3;

                    if ($annotation ne "") {
                        if ($annotation =~ m/\s*\/\*\s*\((.*)\)\s*\*\//) {
                            $type_name = $1;
                        } else {
                            die "malformed cast annotation for argument: $args_member";
                        }
                    }

                    push(@args_list, "$type_name$arg_name");
1182

1183
                    if ($call->{ProcName} eq "SecretSetValue") {
1184
                        # SPECIAL: virSecretSetValue uses size_t instead of int
1185
                        push(@args_list, "size_t ${arg_name}len");
1186
                    } else {
1187
                        push(@args_list, "int ${arg_name}len");
1188 1189
                    }

1190 1191 1192
                    push(@setters_list, "args.$arg_name.${arg_name}_val = (char *)$arg_name;");
                    push(@setters_list, "args.$arg_name.${arg_name}_len = ${arg_name}len;");
                    push(@args_check_list, { name => "\"$arg_name\"", arg => "${arg_name}len", limit => $limit });
1193 1194 1195
                } elsif ($args_member =~ m/^(admin|remote)_string (\S+)<(\S+)>;/) {
                    my $arg_name = $2;
                    my $limit = $3;
1196 1197 1198

                    push(@args_list, "const char *$arg_name");
                    push(@args_list, "int ${arg_name}len");
1199 1200 1201
                    push(@setters_list, "args.$arg_name.${arg_name}_val = (char *)$arg_name;");
                    push(@setters_list, "args.$arg_name.${arg_name}_len = ${arg_name}len;");
                    push(@args_check_list, { name => "\"$arg_name\"", arg => "${arg_name}len", limit => $limit });
1202 1203 1204 1205 1206 1207
                } elsif ($args_member =~ m/^((?:unsigned )?int) (\S+)<(\S+)>;/) {
                    my $type_name = $1;
                    my $arg_name = $2;
                    my $limit = $3;

                    push(@args_list, "${type_name} *$arg_name");
1208
                    push(@args_list, "int ${arg_name}len");
1209 1210 1211
                    push(@setters_list, "args.$arg_name.${arg_name}_val = $arg_name;");
                    push(@setters_list, "args.$arg_name.${arg_name}_len = ${arg_name}len;");
                    push(@args_check_list, { name => "\"$arg_name\"", arg => "${arg_name}len", limit => $limit });
1212 1213 1214 1215 1216 1217 1218
                } elsif ($args_member =~ m/^remote_typed_param (\S+)<(\S+)>;/) {
                    push(@args_list, "virTypedParameterPtr $1");
                    push(@args_list, "int n$1");
                    push(@setters_list2, "if (remoteSerializeTypedParameters($1, n$1, &args.$1.$1_val, &args.$1.$1_len) < 0) {\n" .
                                         "        xdr_free((xdrproc_t)xdr_$call->{args}, (char *)&args);\n" .
                                         "        goto done;\n" .
                                         "    }");
1219
                    push(@free_list, "    remoteFreeTypedParameters(args.params.params_val, args.params.params_len);\n");
1220 1221
                } elsif ($args_member =~ m/^((?:unsigned )?int) (\S+);\s*\/\*\s*call-by-reference\s*\*\//) {
                    my $type_name = "$1 *";
1222 1223 1224 1225
                    my $arg_name = $2;

                    push(@args_list, "$type_name $arg_name");
                    push(@setters_list, "args.$arg_name = *$arg_name;");
1226 1227
                } elsif ($args_member =~ m/^((?:unsigned )?int) (\S+);/) {
                    my $type_name = $1;
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
                    my $arg_name = $2;

                    push(@args_list, "$type_name $arg_name");
                    push(@setters_list, "args.$arg_name = $arg_name;");
                } elsif ($args_member =~ m/^(unsigned )?hyper (\S+);/) {
                    my $type_name = $1;
                    my $arg_name = $2;

                    if (hyper_to_long($call->{ProcName}, "arg", $arg_name)) {
                        $type_name .= "long";
                    } else {
                        $type_name .= "long long";
1240 1241 1242 1243
                    }

                    push(@args_list, "$type_name $arg_name");
                    push(@setters_list, "args.$arg_name = $arg_name;");
1244
                } elsif ($args_member =~ m/^(\/)?\*/) {
1245 1246 1247 1248 1249 1250
                    # ignore comments
                } else {
                    die "unhandled type for argument value: $args_member";
                }

                if ($is_first_arg and $priv_src eq "conn") {
1251
                    unshift(@args_list, "$connect_ptr conn");
1252 1253 1254 1255 1256 1257
                }

                $is_first_arg = 0;
            }
        }

1258 1259
        if (!@args_list) {
            push(@args_list, "$connect_ptr conn");
1260 1261 1262 1263
        }

        # handle return values of the function
        my @ret_list = ();
1264
        my @ret_list2 = ();
1265 1266 1267
        my $call_ret = "&ret";
        my $single_ret_var = "int rv = -1";
        my $single_ret_type = "int";
1268 1269 1270 1271 1272
        my $single_ret_as_list = 0;
        my $single_ret_list_error_msg_type = "undefined";
        my $single_ret_list_name = "undefined";
        my $single_ret_list_max_var = "undefined";
        my $single_ret_list_max_define = "undefined";
1273
        my $single_ret_cleanup = 0;
1274 1275
        my $multi_ret = 0;

1276
        if ($rettype ne "void" and
1277 1278 1279 1280
            scalar(@{$call->{ret_members}}) > 1) {
            $multi_ret = 1;
        }

1281
        if ($rettype eq "void") {
1282
            $call_ret = "NULL";
1283
        } else {
1284
            push(@vars_list, "$rettype ret");
1285 1286

            foreach my $ret_member (@{$call->{ret_members}}) {
1287
                if ($multi_ret) {
1288
                    if ($ret_member =~ m/^(unsigned )?(char|short|int|hyper) (\S+)\[\S+\];/) {
1289 1290 1291 1292
                        if ($2 eq "hyper" and hyper_to_long($call->{ProcName}, "ret", $3)) {
                            die "legacy [u]long hyper arrays aren't supported";
                        }

1293
                        push(@ret_list, "memcpy(result->$3, ret.$3, sizeof(result->$3));");
1294 1295
                    } elsif ($ret_member =~ m/<\S+>;/ or $ret_member =~ m/\[\S+\];/) {
                        # just make all other array types fail
1296 1297
                        die "unhandled type for multi-return-value for " .
                            "procedure $call->{name}: $ret_member";
1298
                    } elsif ($ret_member =~ m/^(unsigned )?(char|short|int|hyper) (\S+);/) {
1299 1300 1301 1302 1303 1304 1305
                        if ($2 eq "hyper" and hyper_to_long($call->{ProcName}, "ret", $3)) {
                            my $sign = ""; $sign = "U" if ($1);

                            push(@ret_list, "HYPER_TO_${sign}LONG(result->$3, ret.$3);");
                        } else {
                            push(@ret_list, "result->$3 = ret.$3;");
                        }
1306
                    } else {
1307 1308
                        die "unhandled type for multi-return-value for " .
                            "procedure $call->{name}: $ret_member";
1309
                    }
1310 1311 1312
                } elsif ($ret_member =~ m/^(admin|remote)_nonnull_string (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
                    splice(@args_list, int($4), 0, ("char **const $2"));
                    push(@ret_list, "rv = ret.$2.$2_len;");
1313 1314
                    $single_ret_var = "int rv = -1";
                    $single_ret_type = "int";
1315
                    $single_ret_as_list = 1;
1316 1317 1318 1319
                    $single_ret_list_name = $2;
                    $single_ret_list_max_var = "max$2";
                    $single_ret_list_max_define = $3;
                } elsif ($ret_member =~ m/^(admin|remote)_nonnull_string (\S+)<\S+>;/) {
1320
                    # error out on unannotated arrays
1321 1322 1323
                    die "$1_nonnull_string array without insert@<offset> annotation: $ret_member";
                } elsif ($ret_member =~ m/^(admin|remote)_nonnull_string (\S+);/) {
                    push(@ret_list, "rv = ret.$2;");
1324 1325
                    $single_ret_var = "char *rv = NULL";
                    $single_ret_type = "char *";
1326 1327 1328
                } elsif ($ret_member =~ m/^(admin|remote)_string (\S+);/) {
                    push(@ret_list, "rv = ret.$2 ? *ret.$2 : NULL;");
                    push(@ret_list, "VIR_FREE(ret.$2);");
1329 1330
                    $single_ret_var = "char *rv = NULL";
                    $single_ret_type = "char *";
1331
                } elsif ($ret_member =~ m/^remote_nonnull_(domain|network|storage_pool|storage_vol|node_device|interface|secret|nwfilter|domain_snapshot) (\S+);/) {
1332 1333
                    my $name = $1;
                    my $arg_name = $2;
1334
                    my $type_name = name_to_TypeName($name);
1335

1336 1337 1338 1339 1340 1341 1342 1343
                    if ($call->{ProcName} eq "DomainCreateWithFlags") {
                        # SPECIAL: virDomainCreateWithFlags updates the given
                        #          domain object instead of returning a new one
                        push(@ret_list, "dom->id = ret.dom.id;");
                        push(@ret_list, "xdr_free((xdrproc_t)xdr_$call->{ret}, (char *)&ret);");
                        push(@ret_list, "rv = 0;");
                        $single_ret_var = "int rv = -1";
                        $single_ret_type = "int";
1344
                    } else {
1345
                        if ($name eq "domain_snapshot") {
1346 1347 1348
                            my $dom = "$priv_src";
                            $dom =~ s/->conn//;
                            push(@ret_list, "rv = get_nonnull_$name($dom, ret.$arg_name);");
1349 1350 1351
                        } else {
                            push(@ret_list, "rv = get_nonnull_$name($priv_src, ret.$arg_name);");
                        }
1352

1353
                        push(@ret_list, "xdr_free((xdrproc_t)xdr_$rettype, (char *)&ret);");
1354 1355 1356
                        $single_ret_var = "vir${type_name}Ptr rv = NULL";
                        $single_ret_type = "vir${type_name}Ptr";
                    }
1357 1358 1359 1360 1361
                } elsif ($ret_member =~ m/^remote_typed_param (\S+)<(\S+)>;\s*\/\*\s*insert@(\d+)\s*\*\//) {
                    splice(@args_list, int($3), 0, ("virTypedParameterPtr $1"));
                    push(@ret_list2, "if (remoteDeserializeTypedParameters(ret.$1.$1_val,\n" .
                                     "                                         ret.$1.$1_len,\n" .
                                     "                                         $2,\n" .
1362
                                     "                                         &$1,\n" .
1363 1364 1365 1366 1367 1368
                                     "                                         n$1) < 0)\n" .
                                     "        goto cleanup;\n");
                    $single_ret_cleanup = 1;
                } elsif ($ret_member =~ m/^remote_typed_param (\S+)<\S+>;/) {
                    # error out on unannotated arrays
                    die "remote_typed_param array without insert@<offset> annotation: $ret_member";
1369
                } elsif ($ret_member =~ m/^int (\S+);/) {
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
                    my $arg_name = $1;

                    if ($call->{ProcName} =~ m/GetAutostart$/) {
                        push(@args_list, "int *$arg_name");
                        push(@ret_list, "if ($arg_name) *$arg_name = ret.$arg_name;");
                        push(@ret_list, "rv = 0;");
                    } else {
                        push(@ret_list, "rv = ret.$arg_name;");
                    }

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
                    $single_ret_var = "int rv = -1";
                    $single_ret_type = "int";
                } elsif ($ret_member =~ m/^(unsigned )?hyper (\S+);\s*\/\*\s*insert@(\d+)\s*\*\//) {
                    my $type_name = $1;
                    my $sign = ""; $sign = "U" if ($1);
                    my $ret_name = $2;
                    my $insert = $3;

                    if (hyper_to_long($call->{ProcName}, "ret", $ret_name)) {
                        $type_name .= "long";
                        push(@ret_list, "if ($ret_name) HYPER_TO_${sign}LONG(*$ret_name, ret.$ret_name);");
                    } else {
                        $type_name .= "long long";
                        push(@ret_list, "if ($ret_name) *$ret_name = ret.$ret_name;");
                    }

                    splice(@args_list, int($insert), 0, ("$type_name *$ret_name"));
                    push(@ret_list, "rv = 0;");
1398 1399
                    $single_ret_var = "int rv = -1";
                    $single_ret_type = "int";
1400
                } elsif ($ret_member =~ m/^unsigned hyper (\S+);/) {
1401
                    my $ret_name = $1;
1402

1403
                    if ($call->{ProcName} =~ m/Get(Lib)?Version/) {
1404 1405 1406 1407 1408 1409 1410
                        if ($structprefix eq "admin") {
                            push(@args_list, "unsigned long long *$ret_name");
                            push(@ret_list, "*$ret_name = ret.$ret_name;");
                        } else {
                            push(@args_list, "unsigned long *$ret_name");
                            push(@ret_list, "if ($ret_name) HYPER_TO_ULONG(*$ret_name, ret.$ret_name);");
                        }
1411 1412 1413
                        push(@ret_list, "rv = 0;");
                        $single_ret_var = "int rv = -1";
                        $single_ret_type = "int";
1414 1415
                    } elsif (hyper_to_long($call->{ProcName}, "ret", $ret_name)) {
                        push(@ret_list, "HYPER_TO_ULONG(rv, ret.$ret_name);");
1416 1417
                        $single_ret_var = "unsigned long rv = 0";
                        $single_ret_type = "unsigned long";
1418 1419 1420 1421
                    } else {
                        push(@ret_list, "rv = ret.$ret_name;");
                        $single_ret_var = "unsigned long long rv = 0";
                        $single_ret_type = "unsigned long long";
1422
                    }
1423 1424
                } elsif ($ret_member =~ m/^(\/)?\*/) {
                    # ignore comments
1425
                } else {
1426 1427
                    die "unhandled type for return value for procedure " .
                        "$call->{name}: $ret_member";
1428 1429 1430 1431
                }
            }
        }

1432 1433
        # select struct type for multi-return-value functions
        if ($multi_ret) {
1434 1435
            if (!(defined $call->{ret_offset})) {
                die "multi-return-value without insert@<offset> annotation: $call->{ret}";
1436 1437
            }

1438 1439
            my $struct_name = $call->{ProcName};
            $struct_name =~ s/Get//;
1440

1441
            splice(@args_list, $call->{ret_offset}, 0, ("vir${struct_name}Ptr result"));
1442 1443
        }

1444 1445 1446 1447
        if ($call->{streamflag} ne "none") {
            splice(@args_list, $call->{streamoffset}, 0, ("virStreamPtr st"));
        }

1448 1449
        # print function
        print "\n";
1450
        print "static $single_ret_type\n";
1451 1452 1453 1454 1455 1456
        if ($structprefix eq "remote") {
            print "$structprefix$call->{ProcName}(";
        } else {
            my $proc = $call->{ProcName};
            my $extra = $structprefix;
            $extra =~ s/^(\w)/uc $1/e;
1457 1458 1459 1460 1461
            if ($structprefix eq "admin") {
                $proc = $extra . $proc;
            } else {
                $proc =~ s/^(Domain)(.*)/$1 . $extra . $2/e;
            }
1462 1463
            print "remote$proc(";
        }
1464 1465 1466 1467 1468

        print join(", ", @args_list);

        print ")\n";
        print "{\n";
1469
        print "    $single_ret_var;\n";
1470 1471 1472 1473 1474
        if ($structprefix eq "admin") {
            print "    remoteAdminPrivPtr priv = $priv_src->privateData;\n";
        } else {
            print "    struct private_data *priv = $priv_src->privateData;\n";
        }
1475 1476 1477 1478 1479

        foreach my $var (@vars_list) {
            print "    $var;\n";
        }

1480
        if ($single_ret_as_list) {
1481
            print "    size_t i;\n";
1482 1483
        }

1484
        if ($call->{streamflag} ne "none") {
1485
            print "    virNetClientStreamPtr netst = NULL;\n";
1486 1487
        }

1488
        print "\n";
1489 1490 1491 1492 1493
        if ($structprefix eq "admin") {
            print "    virObjectLock(priv);\n";
        } else {
            print "    remoteDriverLock(priv);\n";
        }
1494

1495 1496
        if ($call->{streamflag} ne "none") {
            print "\n";
1497
            print "    if (!(netst = virNetClientStreamNew(priv->remoteProgram, $call->{constname}, priv->counter)))\n";
1498
            print "        goto done;\n";
1499
            print "\n";
1500
            print "    if (virNetClientAddStream(priv->client, netst) < 0) {\n";
1501
            print "        virObjectUnref(netst);\n";
1502
            print "        goto done;\n";
1503 1504
            print "    }";
            print "\n";
1505
            print "    st->driver = &remoteStreamDrv;\n";
1506
            print "    st->privateData = netst;\n";
1507 1508
        }

1509 1510 1511 1512 1513 1514 1515 1516 1517
        if ($call->{ProcName} eq "SupportsFeature") {
            # SPECIAL: VIR_DRV_FEATURE_REMOTE feature is handled directly
            print "\n";
            print "    if (feature == VIR_DRV_FEATURE_REMOTE) {\n";
            print "        rv = 1;\n";
            print "        goto done;\n";
            print "    }\n";
        }

1518 1519 1520
        foreach my $args_check (@args_check_list) {
            print "\n";
            print "    if ($args_check->{arg} > $args_check->{limit}) {\n";
1521 1522 1523
            print "        virReportError(VIR_ERR_RPC,\n";
            print "                       _(\"%s length greater than maximum: %d > %d\"),\n";
            print "                       $args_check->{name}, (int)$args_check->{arg}, $args_check->{limit});\n";
1524 1525 1526 1527
            print "        goto done;\n";
            print "    }\n";
        }

1528 1529 1530
        if ($single_ret_as_list) {
            print "\n";
            print "    if ($single_ret_list_max_var > $single_ret_list_max_define) {\n";
1531 1532 1533
            print "        virReportError(VIR_ERR_RPC,\n";
            print "                       _(\"too many remote ${single_ret_list_error_msg_type}s: %d > %d\"),\n";
            print "                       $single_ret_list_max_var, $single_ret_list_max_define);\n";
1534 1535 1536 1537
            print "        goto done;\n";
            print "    }\n";
        }

1538
        if (@setters_list) {
1539
            print "\n";
1540 1541 1542 1543 1544 1545 1546 1547 1548
            print "    ";
        }

        print join("\n    ", @setters_list);

        if (@setters_list) {
            print "\n";
        }

1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
        if (@setters_list2) {
            print "\n";
            print "    ";
        }

        print join("\n    ", @setters_list2);

        if (@setters_list2) {
            print "\n";
        }

1560
        if ($rettype ne "void") {
1561
            print "\n";
1562
            print "    memset(&ret, 0, sizeof(ret));\n";
1563 1564
        }

1565 1566 1567 1568
        my $callflags = "0";
        if ($structprefix eq "qemu") {
            $callflags = "REMOTE_CALL_QEMU";
        }
1569 1570 1571
        if ($structprefix eq "lxc") {
            $callflags = "REMOTE_CALL_LXC";
        }
1572

1573 1574 1575 1576
        if ($structprefix ne "admin") {
            $priv_src = "$priv_src, priv";
        }

1577
        print "\n";
1578
        print "    if (call($priv_src, $callflags, $call->{constname},\n";
1579 1580
        print "             (xdrproc_t)xdr_$argtype, (char *)$call_args,\n";
        print "             (xdrproc_t)xdr_$rettype, (char *)$call_ret) == -1) {\n";
1581 1582

        if ($call->{streamflag} ne "none") {
1583
            print "        virNetClientRemoveStream(priv->client, netst);\n";
1584
            print "        virObjectUnref(netst);\n";
1585 1586
            print "        st->driver = NULL;\n";
            print "        st->privateData = NULL;\n";
1587 1588
        }

1589
        print "        goto done;\n";
1590
        print "    }\n";
1591
        print "\n";
1592

1593 1594
        if ($single_ret_as_list) {
            print "    if (ret.$single_ret_list_name.${single_ret_list_name}_len > $single_ret_list_max_var) {\n";
1595 1596 1597
            print "        virReportError(VIR_ERR_RPC,\n";
            print "                       _(\"too many remote ${single_ret_list_error_msg_type}s: %d > %d\"),\n";
            print "                       ret.$single_ret_list_name.${single_ret_list_name}_len, $single_ret_list_max_var);\n";
1598 1599 1600 1601 1602
            print "        goto cleanup;\n";
            print "    }\n";
            print "\n";
            print "    /* This call is caller-frees (although that isn't clear from\n";
            print "     * the documentation).  However xdr_free will free up both the\n";
1603
            print "     * names and the list of pointers, so we have to VIR_STRDUP the\n";
1604 1605
            print "     * names here. */\n";
            print "    for (i = 0; i < ret.$single_ret_list_name.${single_ret_list_name}_len; ++i) {\n";
1606 1607
            print "        if (VIR_STRDUP(${single_ret_list_name}[i],\n";
            print "                       ret.$single_ret_list_name.${single_ret_list_name}_val[i]) < 0) {\n";
1608 1609 1610
            print "            size_t j;\n";
            print "            for (j = 0; j < i; j++)\n";
            print "                VIR_FREE(${single_ret_list_name}[j]);\n";
1611 1612 1613 1614 1615 1616 1617
            print "\n";
            print "            goto cleanup;\n";
            print "        }\n";
            print "    }\n";
            print "\n";
        }

1618 1619 1620 1621 1622 1623
        if (@ret_list2) {
            print "    ";
            print join("\n    ", @ret_list2);
            print "\n";
        }

1624 1625 1626 1627
        if (@ret_list) {
            print "    ";
            print join("\n    ", @ret_list);
            print "\n";
1628 1629
        }

1630
        if ($call->{ProcName} eq "DomainDestroy" ||
1631 1632
            $call->{ProcName} eq "DomainSave" ||
            $call->{ProcName} eq "DomainManagedSave") {
1633
            # SPECIAL: virDomain{Destroy|Save|ManagedSave} need to reset
1634
            # the domain id explicitly on success
1635 1636 1637
            print "    dom->id = -1;\n";
        }

1638
        if ($multi_ret or !@ret_list) {
1639 1640 1641
            print "    rv = 0;\n";
        }

1642
        if ($single_ret_as_list or $single_ret_cleanup) {
1643 1644
            print "\n";
            print "cleanup:\n";
1645
            print "    xdr_free((xdrproc_t)xdr_$call->{ret}, (char *)&ret);\n";
1646 1647
        }

1648 1649
        print "\n";
        print "done:\n";
1650 1651 1652

        print join("\n", @free_list);

1653 1654 1655 1656 1657 1658
        if ($structprefix eq "admin") {
            print "    virObjectUnlock(priv);\n";
        } else {
            print "    remoteDriverUnlock(priv);\n";
        }

1659 1660 1661
        print "    return rv;\n";
        print "}\n";
    }
1662 1663
} elsif ($mode eq "aclheader" ||
         $mode eq "aclbody" ||
1664 1665
         $mode eq "aclsym" ||
         $mode eq "aclapi") {
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
    my %generate = map { $_ => 1 } @autogen;
    my @keys = keys %calls;

    if ($mode eq "aclsym") {
        @keys = sort { my $c = $a . "ensureacl";
                       my $d = $b . "ensureacl";
                       $c cmp $d } @keys;
    } else {
        @keys = sort { $a cmp $b } @keys;
    }

    if ($mode eq "aclheader") {
        my @headers = (
            "internal.h",
            "domain_conf.h",
            "network_conf.h",
            "secret_conf.h",
            "storage_conf.h",
            "nwfilter_conf.h",
            "node_device_conf.h",
            "interface_conf.h"
            );
        foreach my $hdr (@headers) {
            print "#include \"$hdr\"\n";
        }
1691
        print "\n";
1692 1693 1694 1695 1696 1697 1698 1699 1700
    } elsif ($mode eq "aclbody") {
        my $header = shift;
        print "#include <config.h>\n";
        print "#include \"$header\"\n";
        print "#include \"access/viraccessmanager.h\"\n";
        print "#include \"datatypes.h\"\n";
        print "#include \"virerror.h\"\n";
        print "\n";
        print "#define VIR_FROM_THIS VIR_FROM_ACCESS\n";
1701 1702 1703 1704 1705
        print "\n";
    } elsif ($mode eq "aclapi") {
        print "<aclinfo>\n";
    } else {
        print "\n";
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
    }

    foreach (@keys) {
        my $call = $calls{$_};

        die "missing 'acl' option for $call->{ProcName}"
            unless exists $call->{acl} &&
            $#{$call->{acl}} != -1;

        next if $call->{acl}->[0] eq "none";

        if ($mode eq "aclsym") {
1718
            my $apiname = $prefix . $call->{ProcName};
1719
            if ($structprefix eq "qemu") {
1720
                $apiname =~ s/(vir(Connect)?Domain)/${1}Qemu/;
1721 1722 1723 1724 1725 1726 1727
            } elsif ($structprefix eq "lxc") {
                $apiname =~ s/virDomain/virDomainLxc/;
            }
            if (defined $call->{aclfilter}) {
                print $apiname . "CheckACL;\n";
            }
            print $apiname . "EnsureACL;\n";
1728 1729
        } elsif ($mode eq "aclapi") {
            &generate_aclapi($call);
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
        } else {
            &generate_acl($call, $call->{acl}, "Ensure");
            if (defined $call->{aclfilter}) {
                &generate_acl($call, $call->{aclfilter}, "Check");
            }
        }

        sub generate_acl {
            my $call = shift;
            my $acl = shift;
            my $action = shift;

            my @acl;
            foreach (@{$acl}) {
                my @bits = split /:/;
                push @acl, { object => $bits[0], perm => $bits[1], flags => $bits[2] }
            }

            my $checkflags = 0;
            for (my $i = 1 ; $i <= $#acl ; $i++) {
                if ($acl[$i]->{object} ne $acl[0]->{object}) {
                    die "acl for '$call->{ProcName}' cannot check different objects";
                }
                if (defined $acl[$i]->{flags}) {
                    $checkflags = 1;
                }
            }

1758
            my $apiname = $prefix . $call->{ProcName};
1759
            if ($structprefix eq "qemu") {
1760
                $apiname =~ s/(vir(Connect)?Domain)/${1}Qemu/;
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
            } elsif ($structprefix eq "lxc") {
                $apiname =~ s/virDomain/virDomainLxc/;
            }

            my $object = $acl[0]->{object};
            my $arg = $acl[0]->{object};
            $arg =~ s/^.*_(\w+)$/$1/;
            $object =~ s/^(\w)/uc $1/e;
            $object =~ s/_(\w)/uc $1/e;
            $object =~ s/Nwfilter/NWFilter/;
1771
            my $objecttype = $prefix . $object . "DefPtr";
1772 1773 1774 1775 1776 1777 1778
            $apiname .= $action . "ACL";

            if ($arg eq "interface") {
                $arg = "iface";
            }

            my @argdecls;
1779
            push @argdecls, "$connect_ptr conn";
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
            if ($object ne "Connect") {
                if ($object eq "StorageVol") {
                    push @argdecls, "virStoragePoolDefPtr pool";
                }
                push @argdecls, "$objecttype $arg";
            }
            if ($checkflags) {
                push @argdecls, "unsigned int flags";
            }

1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
            my $ret;
            my $pass;
            my $fail;
            if ($action eq "Check") {
                $ret = "bool";
                $pass = "true";
                $fail = "false";
            } else {
                $ret = "int";
                $pass = "0";
                $fail = "-1";
            }

1803
            if ($mode eq "aclheader") {
1804
                print "extern $ret $apiname(" . join(", ", @argdecls) . ");\n";
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
            } else {
                my @argvars;
                push @argvars, "mgr";
                push @argvars, "conn->driver->name";
                if ($object ne "Connect") {
                    if ($object eq "StorageVol") {
                        push @argvars, "pool";
                    }
                    push @argvars, $arg;
                }

1816 1817
                print "/* Returns: $fail on error/denied, $pass on allowed */\n";
                print "$ret $apiname(" . join(", ", @argdecls) . ")\n";
1818 1819 1820 1821
                print "{\n";
                print "    virAccessManagerPtr mgr;\n";
                print "    int rv;\n";
                print "\n";
1822 1823 1824 1825 1826 1827
                print "    if (!(mgr = virAccessManagerGetDefault())) {\n";
                if ($action eq "Check") {
                    print "        virResetLastError();\n";
                }
                print "        return $fail;\n";
                print "    }\n";
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
                print "\n";

                foreach my $acl (@acl) {
                    my $perm = "vir_access_perm_" . $acl->{object} . "_" . $acl->{perm};
                    $perm =~ tr/a-z/A-Z/;

                    my $method = "virAccessManagerCheck" . $object;
                    my $space = ' ' x length($method);
                    print "    if (";
                    if (defined $acl->{flags}) {
                        my $flags = $acl->{flags};
                        if ($flags =~ /^\!/) {
                            $flags = substr $flags, 1;
                            print "((flags & ($flags)) == 0) &&\n";
                        } else {
                            print "((flags & ($flags)) == ($flags)) &&\n";
                        }
                        print "        ";
                    }
                    print "(rv = $method(" . join(", ", @argvars, $perm) . ")) <= 0) {\n";
                    print "        virObjectUnref(mgr);\n";
                    if ($action eq "Ensure") {
                        print "        if (rv == 0)\n";
                        print "            virReportError(VIR_ERR_ACCESS_DENIED, NULL);\n";
1852
                        print "        return $fail;\n";
1853
                    } else {
1854 1855
                        print "        virResetLastError();\n";
                        print "        return $fail;\n";
1856 1857 1858 1859 1860 1861
                    }
                    print "    }";
                    print "\n";
                }

                print "    virObjectUnref(mgr);\n";
1862
                print "    return $pass;\n";
1863 1864 1865
                print "}\n\n";
            }
        }
1866 1867 1868 1869

        sub generate_aclapi {
            my $call = shift;

1870
            my $apiname = $prefix . $call->{ProcName};
1871
            if ($structprefix eq "qemu") {
1872
                $apiname =~ s/(vir(Connect)?Domain)/${1}Qemu/;
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
            } elsif ($structprefix eq "lxc") {
                $apiname =~ s/virDomain/virDomainLxc/;
            }

            print "  <api name='$apiname'>\n";

            my $acl = $call->{acl};
            foreach (@{$acl}) {
                my @bits = split /:/;
                print "    <check object='$bits[0]' perm='$bits[1]'";
                if (defined $bits[2]) {
                    print " flags='$bits[2]'";
                }
                print "/>\n";
            }

            my $aclfilter = $call->{aclfilter};
            foreach (@{$aclfilter}) {
                my @bits = split /:/;
                print "    <filter object='$bits[0]' perm='$bits[1]'/>\n";
            }

            print "  </api>\n";
        }

    }

    if ($mode eq "aclapi") {
        print "</aclinfo>\n";
1902
    }
1903
}