New API: lvm-canonical-lv-name: make LV name canonical.
[libguestfs.git] / generator / generator_daemon.ml
1 (* libguestfs
2  * Copyright (C) 2009-2010 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  *)
18
19 (* Please read generator/README first. *)
20
21 open Printf
22
23 open Generator_types
24 open Generator_utils
25 open Generator_pr
26 open Generator_docstrings
27 open Generator_optgroups
28 open Generator_actions
29 open Generator_structs
30 open Generator_c
31
32 (* Generate daemon/actions.h. *)
33 let generate_daemon_actions_h () =
34   generate_header CStyle GPLv2plus;
35
36   pr "#include \"../src/guestfs_protocol.h\"\n";
37   pr "\n";
38
39   List.iter (
40     fun (name, style, _, _, _, _, _) ->
41       generate_prototype
42         ~single_line:true ~newline:true ~in_daemon:true ~prefix:"do_"
43         name style;
44   ) daemon_functions
45
46 (* Generate the server-side stubs. *)
47 and generate_daemon_actions () =
48   generate_header CStyle GPLv2plus;
49
50   pr "#include <config.h>\n";
51   pr "\n";
52   pr "#include <stdio.h>\n";
53   pr "#include <stdlib.h>\n";
54   pr "#include <string.h>\n";
55   pr "#include <inttypes.h>\n";
56   pr "#include <rpc/types.h>\n";
57   pr "#include <rpc/xdr.h>\n";
58   pr "\n";
59   pr "#include \"daemon.h\"\n";
60   pr "#include \"c-ctype.h\"\n";
61   pr "#include \"../src/guestfs_protocol.h\"\n";
62   pr "#include \"actions.h\"\n";
63   pr "\n";
64
65   List.iter (
66     fun (name, (ret, args, optargs), _, _, _, _, _) ->
67       if optargs <> [] then
68         failwithf "optional arguments not supported in the daemon yet";
69
70       (* Generate server-side stubs. *)
71       pr "static void %s_stub (XDR *xdr_in)\n" name;
72       pr "{\n";
73       let error_code =
74         match ret with
75         | RErr | RInt _ -> pr "  int r;\n"; "-1"
76         | RInt64 _ -> pr "  int64_t r;\n"; "-1"
77         | RBool _ -> pr "  int r;\n"; "-1"
78         | RConstString _ | RConstOptString _ ->
79             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
80         | RString _ -> pr "  char *r;\n"; "NULL"
81         | RStringList _ | RHashtable _ -> pr "  char **r;\n"; "NULL"
82         | RStruct (_, typ) -> pr "  guestfs_int_%s *r;\n" typ; "NULL"
83         | RStructList (_, typ) -> pr "  guestfs_int_%s_list *r;\n" typ; "NULL"
84         | RBufferOut _ ->
85             pr "  size_t size = 1;\n";
86             pr "  char *r;\n";
87             "NULL" in
88
89       (match args with
90        | [] -> ()
91        | args ->
92            pr "  struct guestfs_%s_args args;\n" name;
93            List.iter (
94              function
95              | Device n | Dev_or_Path n
96              | Pathname n
97              | String n
98              | Key n -> ()
99              | OptString n -> pr "  char *%s;\n" n
100              | StringList n | DeviceList n -> pr "  char **%s;\n" n
101              | Bool n -> pr "  int %s;\n" n
102              | Int n -> pr "  int %s;\n" n
103              | Int64 n -> pr "  int64_t %s;\n" n
104              | FileIn _ | FileOut _ -> ()
105              | BufferIn n ->
106                  pr "  const char *%s;\n" n;
107                  pr "  size_t %s_size;\n" n
108            ) args
109       );
110       pr "\n";
111
112       let is_filein =
113         List.exists (function FileIn _ -> true | _ -> false) args in
114
115       (match args with
116        | [] -> ()
117        | args ->
118            pr "  memset (&args, 0, sizeof args);\n";
119            pr "\n";
120            pr "  if (!xdr_guestfs_%s_args (xdr_in, &args)) {\n" name;
121            if is_filein then
122              pr "    if (cancel_receive () != -2)\n";
123            pr "      reply_with_error (\"daemon failed to decode procedure arguments\");\n";
124            pr "    goto done;\n";
125            pr "  }\n";
126            let pr_args n =
127              pr "  char *%s = args.%s;\n" n n
128            in
129            let pr_list_handling_code n =
130              pr "  %s = realloc (args.%s.%s_val,\n" n n n;
131              pr "                sizeof (char *) * (args.%s.%s_len+1));\n" n n;
132              pr "  if (%s == NULL) {\n" n;
133              if is_filein then
134                pr "    if (cancel_receive () != -2)\n";
135              pr "      reply_with_perror (\"realloc\");\n";
136              pr "    goto done;\n";
137              pr "  }\n";
138              pr "  %s[args.%s.%s_len] = NULL;\n" n n n;
139              pr "  args.%s.%s_val = %s;\n" n n n;
140            in
141            List.iter (
142              function
143              | Pathname n ->
144                  pr_args n;
145                  pr "  ABS_PATH (%s, %s, goto done);\n"
146                    n (if is_filein then "cancel_receive ()" else "0");
147              | Device n ->
148                  pr_args n;
149                  pr "  RESOLVE_DEVICE (%s, %s, goto done);\n"
150                    n (if is_filein then "cancel_receive ()" else "0");
151              | Dev_or_Path n ->
152                  pr_args n;
153                  pr "  REQUIRE_ROOT_OR_RESOLVE_DEVICE (%s, %s, goto done);\n"
154                    n (if is_filein then "cancel_receive ()" else "0");
155              | String n | Key n -> pr_args n
156              | OptString n -> pr "  %s = args.%s ? *args.%s : NULL;\n" n n n
157              | StringList n ->
158                  pr_list_handling_code n;
159              | DeviceList n ->
160                  pr_list_handling_code n;
161                  pr "  /* Ensure that each is a device,\n";
162                  pr "   * and perform device name translation.\n";
163                  pr "   */\n";
164                  pr "  {\n";
165                  pr "    size_t i;\n";
166                  pr "    for (i = 0; %s[i] != NULL; ++i)\n" n;
167                  pr "      RESOLVE_DEVICE (%s[i], %s, goto done);\n" n
168                    (if is_filein then "cancel_receive ()" else "0");
169                  pr "  }\n";
170              | Bool n -> pr "  %s = args.%s;\n" n n
171              | Int n -> pr "  %s = args.%s;\n" n n
172              | Int64 n -> pr "  %s = args.%s;\n" n n
173              | FileIn _ | FileOut _ -> ()
174              | BufferIn n ->
175                  pr "  %s = args.%s.%s_val;\n" n n n;
176                  pr "  %s_size = args.%s.%s_len;\n" n n n
177            ) args;
178            pr "\n"
179       );
180
181       (* this is used at least for do_equal *)
182       if List.exists (function Pathname _ -> true | _ -> false) args then (
183         (* Emit NEED_ROOT just once, even when there are two or
184            more Pathname args *)
185         pr "  NEED_ROOT (%s, goto done);\n"
186           (if is_filein then "cancel_receive ()" else "0");
187       );
188
189       (* Don't want to call the impl with any FileIn or FileOut
190        * parameters, since these go "outside" the RPC protocol.
191        *)
192       let args' =
193         List.filter (function FileIn _ | FileOut _ -> false | _ -> true) args in
194       pr "  r = do_%s " name;
195       generate_c_call_args (ret, args', optargs);
196       pr ";\n";
197
198       (match ret with
199        | RErr | RInt _ | RInt64 _ | RBool _
200        | RConstString _ | RConstOptString _
201        | RString _ | RStringList _ | RHashtable _
202        | RStruct (_, _) | RStructList (_, _) ->
203            pr "  if (r == %s)\n" error_code;
204            pr "    /* do_%s has already called reply_with_error */\n" name;
205            pr "    goto done;\n";
206            pr "\n"
207        | RBufferOut _ ->
208            pr "  /* size == 0 && r == NULL could be a non-error case (just\n";
209            pr "   * an ordinary zero-length buffer), so be careful ...\n";
210            pr "   */\n";
211            pr "  if (size == 1 && r == %s)\n" error_code;
212            pr "    /* do_%s has already called reply_with_error */\n" name;
213            pr "    goto done;\n";
214            pr "\n"
215       );
216
217       (* If there are any FileOut parameters, then the impl must
218        * send its own reply.
219        *)
220       let no_reply =
221         List.exists (function FileOut _ -> true | _ -> false) args in
222       if no_reply then
223         pr "  /* do_%s has already sent a reply */\n" name
224       else (
225         match ret with
226         | RErr -> pr "  reply (NULL, NULL);\n"
227         | RInt n | RInt64 n | RBool n ->
228             pr "  struct guestfs_%s_ret ret;\n" name;
229             pr "  ret.%s = r;\n" n;
230             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
231               name
232         | RConstString _ | RConstOptString _ ->
233             failwithf "RConstString|RConstOptString cannot be used by daemon functions"
234         | RString n ->
235             pr "  struct guestfs_%s_ret ret;\n" name;
236             pr "  ret.%s = r;\n" n;
237             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
238               name;
239             pr "  free (r);\n"
240         | RStringList n | RHashtable n ->
241             pr "  struct guestfs_%s_ret ret;\n" name;
242             pr "  ret.%s.%s_len = count_strings (r);\n" n n;
243             pr "  ret.%s.%s_val = r;\n" n n;
244             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
245               name;
246             pr "  free_strings (r);\n"
247         | RStruct (n, _) ->
248             pr "  struct guestfs_%s_ret ret;\n" name;
249             pr "  ret.%s = *r;\n" n;
250             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
251               name;
252             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
253               name
254         | RStructList (n, _) ->
255             pr "  struct guestfs_%s_ret ret;\n" name;
256             pr "  ret.%s = *r;\n" n;
257             pr "  reply ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
258               name;
259             pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_ret, (char *) &ret);\n"
260               name
261         | RBufferOut n ->
262             pr "  struct guestfs_%s_ret ret;\n" name;
263             pr "  ret.%s.%s_val = r;\n" n n;
264             pr "  ret.%s.%s_len = size;\n" n n;
265             pr "  reply ((xdrproc_t) &xdr_guestfs_%s_ret, (char *) &ret);\n"
266               name;
267             pr "  free (r);\n"
268       );
269
270       (* Free the args. *)
271       pr "done:\n";
272       (match args with
273        | [] -> ()
274        | _ ->
275            pr "  xdr_free ((xdrproc_t) xdr_guestfs_%s_args, (char *) &args);\n"
276              name
277       );
278       pr "  return;\n";
279       pr "}\n\n";
280   ) daemon_functions;
281
282   (* Dispatch function. *)
283   pr "void dispatch_incoming_message (XDR *xdr_in)\n";
284   pr "{\n";
285   pr "  switch (proc_nr) {\n";
286
287   List.iter (
288     fun (name, _, _, _, _, _, _) ->
289       pr "    case GUESTFS_PROC_%s:\n" (String.uppercase name);
290       pr "      %s_stub (xdr_in);\n" name;
291       pr "      break;\n"
292   ) daemon_functions;
293
294   pr "    default:\n";
295   pr "      reply_with_error (\"dispatch_incoming_message: unknown procedure number %%d, set LIBGUESTFS_PATH to point to the matching libguestfs appliance directory\", proc_nr);\n";
296   pr "  }\n";
297   pr "}\n";
298   pr "\n";
299
300   (* LVM columns and tokenization functions. *)
301   (* XXX This generates crap code.  We should rethink how we
302    * do this parsing.
303    *)
304   List.iter (
305     function
306     | typ, cols ->
307         pr "static const char *lvm_%s_cols = \"%s\";\n"
308           typ (String.concat "," (List.map fst cols));
309         pr "\n";
310
311         pr "static int lvm_tokenize_%s (char *str, guestfs_int_lvm_%s *r)\n" typ typ;
312         pr "{\n";
313         pr "  char *tok, *p, *next;\n";
314         pr "  size_t i, j;\n";
315         pr "\n";
316         (*
317           pr "  fprintf (stderr, \"%%s: <<%%s>>\\n\", __func__, str);\n";
318           pr "\n";
319         *)
320         pr "  if (!str) {\n";
321         pr "    fprintf (stderr, \"%%s: failed: passed a NULL string\\n\", __func__);\n";
322         pr "    return -1;\n";
323         pr "  }\n";
324         pr "  if (!*str || c_isspace (*str)) {\n";
325         pr "    fprintf (stderr, \"%%s: failed: passed a empty string or one beginning with whitespace\\n\", __func__);\n";
326         pr "    return -1;\n";
327         pr "  }\n";
328         pr "  tok = str;\n";
329         List.iter (
330           fun (name, coltype) ->
331             pr "  if (!tok) {\n";
332             pr "    fprintf (stderr, \"%%s: failed: string finished early, around token %%s\\n\", __func__, \"%s\");\n" name;
333             pr "    return -1;\n";
334             pr "  }\n";
335             pr "  p = strchrnul (tok, ',');\n";
336             pr "  if (*p) next = p+1; else next = NULL;\n";
337             pr "  *p = '\\0';\n";
338             (match coltype with
339              | FString ->
340                  pr "  r->%s = strdup (tok);\n" name;
341                  pr "  if (r->%s == NULL) {\n" name;
342                  pr "    perror (\"strdup\");\n";
343                  pr "    return -1;\n";
344                  pr "  }\n"
345              | FUUID ->
346                  pr "  for (i = j = 0; i < 32; ++j) {\n";
347                  pr "    if (tok[j] == '\\0') {\n";
348                  pr "      fprintf (stderr, \"%%s: failed to parse UUID from '%%s'\\n\", __func__, tok);\n";
349                  pr "      return -1;\n";
350                  pr "    } else if (tok[j] != '-')\n";
351                  pr "      r->%s[i++] = tok[j];\n" name;
352                  pr "  }\n";
353              | FBytes ->
354                  pr "  if (sscanf (tok, \"%%\"SCNu64, &r->%s) != 1) {\n" name;
355                  pr "    fprintf (stderr, \"%%s: failed to parse size '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
356                  pr "    return -1;\n";
357                  pr "  }\n";
358              | FInt64 ->
359                  pr "  if (sscanf (tok, \"%%\"SCNi64, &r->%s) != 1) {\n" name;
360                  pr "    fprintf (stderr, \"%%s: failed to parse int '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
361                  pr "    return -1;\n";
362                  pr "  }\n";
363              | FOptPercent ->
364                  pr "  if (tok[0] == '\\0')\n";
365                  pr "    r->%s = -1;\n" name;
366                  pr "  else if (sscanf (tok, \"%%f\", &r->%s) != 1) {\n" name;
367                  pr "    fprintf (stderr, \"%%s: failed to parse float '%%s' from token %%s\\n\", __func__, tok, \"%s\");\n" name;
368                  pr "    return -1;\n";
369                  pr "  }\n";
370              | FBuffer | FInt32 | FUInt32 | FUInt64 | FChar ->
371                  assert false (* can never be an LVM column *)
372             );
373             pr "  tok = next;\n";
374         ) cols;
375
376         pr "  if (tok != NULL) {\n";
377         pr "    fprintf (stderr, \"%%s: failed: extra tokens at end of string\\n\", __func__);\n";
378         pr "    return -1;\n";
379         pr "  }\n";
380         pr "  return 0;\n";
381         pr "}\n";
382         pr "\n";
383
384         pr "guestfs_int_lvm_%s_list *\n" typ;
385         pr "parse_command_line_%ss (void)\n" typ;
386         pr "{\n";
387         pr "  char *out, *err;\n";
388         pr "  char *p, *pend;\n";
389         pr "  int r, i;\n";
390         pr "  guestfs_int_lvm_%s_list *ret;\n" typ;
391         pr "  void *newp;\n";
392         pr "\n";
393         pr "  ret = malloc (sizeof *ret);\n";
394         pr "  if (!ret) {\n";
395         pr "    reply_with_perror (\"malloc\");\n";
396         pr "    return NULL;\n";
397         pr "  }\n";
398         pr "\n";
399         pr "  ret->guestfs_int_lvm_%s_list_len = 0;\n" typ;
400         pr "  ret->guestfs_int_lvm_%s_list_val = NULL;\n" typ;
401         pr "\n";
402         pr "  r = command (&out, &err,\n";
403         pr "           \"lvm\", \"%ss\",\n" typ;
404         pr "           \"-o\", lvm_%s_cols, \"--unbuffered\", \"--noheadings\",\n" typ;
405         pr "           \"--nosuffix\", \"--separator\", \",\", \"--units\", \"b\", NULL);\n";
406         pr "  if (r == -1) {\n";
407         pr "    reply_with_error (\"%%s\", err);\n";
408         pr "    free (out);\n";
409         pr "    free (err);\n";
410         pr "    free (ret);\n";
411         pr "    return NULL;\n";
412         pr "  }\n";
413         pr "\n";
414         pr "  free (err);\n";
415         pr "\n";
416         pr "  /* Tokenize each line of the output. */\n";
417         pr "  p = out;\n";
418         pr "  i = 0;\n";
419         pr "  while (p) {\n";
420         pr "    pend = strchr (p, '\\n');       /* Get the next line of output. */\n";
421         pr "    if (pend) {\n";
422         pr "      *pend = '\\0';\n";
423         pr "      pend++;\n";
424         pr "    }\n";
425         pr "\n";
426         pr "    while (*p && c_isspace (*p))    /* Skip any leading whitespace. */\n";
427         pr "      p++;\n";
428         pr "\n";
429         pr "    if (!*p) {                      /* Empty line?  Skip it. */\n";
430         pr "      p = pend;\n";
431         pr "      continue;\n";
432         pr "    }\n";
433         pr "\n";
434         pr "    /* Allocate some space to store this next entry. */\n";
435         pr "    newp = realloc (ret->guestfs_int_lvm_%s_list_val,\n" typ;
436         pr "                sizeof (guestfs_int_lvm_%s) * (i+1));\n" typ;
437         pr "    if (newp == NULL) {\n";
438         pr "      reply_with_perror (\"realloc\");\n";
439         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
440         pr "      free (ret);\n";
441         pr "      free (out);\n";
442         pr "      return NULL;\n";
443         pr "    }\n";
444         pr "    ret->guestfs_int_lvm_%s_list_val = newp;\n" typ;
445         pr "\n";
446         pr "    /* Tokenize the next entry. */\n";
447         pr "    r = lvm_tokenize_%s (p, &ret->guestfs_int_lvm_%s_list_val[i]);\n" typ typ;
448         pr "    if (r == -1) {\n";
449         pr "      reply_with_error (\"failed to parse output of '%ss' command\");\n" typ;
450         pr "      free (ret->guestfs_int_lvm_%s_list_val);\n" typ;
451         pr "      free (ret);\n";
452         pr "      free (out);\n";
453         pr "      return NULL;\n";
454         pr "    }\n";
455         pr "\n";
456         pr "    ++i;\n";
457         pr "    p = pend;\n";
458         pr "  }\n";
459         pr "\n";
460         pr "  ret->guestfs_int_lvm_%s_list_len = i;\n" typ;
461         pr "\n";
462         pr "  free (out);\n";
463         pr "  return ret;\n";
464         pr "}\n"
465
466   ) ["pv", lvm_pv_cols; "vg", lvm_vg_cols; "lv", lvm_lv_cols]
467
468 (* Generate a list of function names, for debugging in the daemon.. *)
469 and generate_daemon_names () =
470   generate_header CStyle GPLv2plus;
471
472   pr "#include <config.h>\n";
473   pr "\n";
474   pr "#include \"daemon.h\"\n";
475   pr "\n";
476
477   pr "/* This array is indexed by proc_nr.  See guestfs_protocol.x. */\n";
478   pr "const char *function_names[] = {\n";
479   List.iter (
480     fun (name, _, proc_nr, _, _, _, _) -> pr "  [%d] = \"%s\",\n" proc_nr name
481   ) daemon_functions;
482   pr "};\n";
483
484 (* Generate the optional groups for the daemon to implement
485  * guestfs_available.
486  *)
487 and generate_daemon_optgroups_c () =
488   generate_header CStyle GPLv2plus;
489
490   pr "#include <config.h>\n";
491   pr "\n";
492   pr "#include \"daemon.h\"\n";
493   pr "#include \"optgroups.h\"\n";
494   pr "\n";
495
496   pr "struct optgroup optgroups[] = {\n";
497   List.iter (
498     fun (group, _) ->
499       pr "  { \"%s\", optgroup_%s_available },\n" group group
500   ) optgroups;
501   pr "  { NULL, NULL }\n";
502   pr "};\n"
503
504 and generate_daemon_optgroups_h () =
505   generate_header CStyle GPLv2plus;
506
507   List.iter (
508     fun (group, _) ->
509       pr "extern int optgroup_%s_available (void);\n" group
510   ) optgroups