Debian Codegraph @

libfdisk/src/script.c

raw
1
2 #include "cctype.h"
3 #include "fdiskP.h"
4 #include "strutils.h"
5 #include "carefulputc.h"
6 #include "mangle.h"
7 #include "jsonwrt.h"
8 #include "fileutils.h"
9
10 #ifdef FUZZ_TARGET
11 #include "fuzz.h"
12 #endif
13
14 /**
15 * SECTION: script
16 * @title: Script
17 * @short_description: complex way to create and dump partition table
18 *
19 * This interface can be used to compose in-memory partition table with all details,
20 * write all partition table description to human readable text file, read it
21 * from the file, and apply the script to on-disk label.
22 *
23 * The libfdisk scripts are based on original sfdisk script (dumps). Each
24 * script has two parts: script headers and partition table entries
25 * (partitions). The script is possible to dump in JSON too (read JSON is not
26 * implemented yet).
27 *
28 * For more details about script format see sfdisk man page.
29 *
30 * There are four ways how to build the script:
31 *
32 * - read the current on-disk partition table by fdisk_script_read_context())
33 * - read it from text file by fdisk_script_read_file()
34 * - read it interactively from user by fdisk_script_read_line() and fdisk_script_set_fgets()
35 * - manually in code by fdisk_script_set_header() and fdisk_script_set_table()
36 *
37 * The read functions fdisk_script_read_context() and fdisk_script_read_file()
38 * creates always a new script partition table. The table (see
39 * fdisk_script_get_table()) is possible to modify by standard
40 * fdisk_table_...() functions and then apply by fdisk_apply_script().
41 *
42 * Note that script API is fully non-interactive and forces libfdisk to not use
43 * standard dialog driven partitioning as we have in fdisk(8).
44 */
45
46 /* script header (e.g. unit: sectors) */
47 struct fdisk_scriptheader {
48 struct list_head headers;
49 char *name;
50 char *data;
51 };
52
53 /* script control struct */
54 struct fdisk_script {
55 struct fdisk_table *table;
56 struct list_head headers;
57 struct fdisk_context *cxt;
58
59 int refcount;
60 char *(*fn_fgets)(struct fdisk_script *, char *, size_t, FILE *);
61 void *userdata;
62
63 /* parser's state */
64 size_t nlines;
65 struct fdisk_label *label;
66
67 unsigned long sector_size; /* as defined by script */
68
69 unsigned int json : 1, /* JSON output */
70 force_label : 1; /* label: <name> specified */
71 };
72
73 static void fdisk_script_free_header(struct fdisk_scriptheader *fi)
74 {
75 if (!fi)
76 return;
77
78 DBG(SCRIPT, ul_debugobj(fi, "free header %s", fi->name));
79 free(fi->name);
80 free(fi->data);
81 list_del(&fi->headers);
82 free(fi);
83 }
84
85 /**
86 * fdisk_new_script:
87 * @cxt: context
88 *
89 * The script hold fdisk_table and additional information to read/write
90 * script to the file.
91 *
92 * Returns: newly allocated script struct.
93 */
94 struct fdisk_script *fdisk_new_script(struct fdisk_context *cxt)
95 {
96 struct fdisk_script *dp = NULL;
97
98 dp = calloc(1, sizeof(*dp));
99 if (!dp)
100 return NULL;
101
102 DBG(SCRIPT, ul_debugobj(dp, "alloc"));
103 dp->refcount = 1;
104 dp->cxt = cxt;
105 fdisk_ref_context(cxt);
106
107 INIT_LIST_HEAD(&dp->headers);
108 return dp;
109 }
110
111 /**
112 * fdisk_new_script_from_file:
113 * @cxt: context
114 * @filename: path to the script file
115 *
116 * Allocates a new script and reads script from @filename.
117 *
118 * Returns: new script instance or NULL in case of error (check errno for more details).
119 */
120 struct fdisk_script *fdisk_new_script_from_file(struct fdisk_context *cxt,
121 const char *filename)
122 {
123 int rc;
124 FILE *f;
125 struct fdisk_script *dp, *res = NULL;
126
127 assert(cxt);
128 assert(filename);
129
130 DBG(SCRIPT, ul_debug("opening %s", filename));
131 f = fopen(filename, "r");
132 if (!f)
133 return NULL;
134
135 dp = fdisk_new_script(cxt);
136 if (!dp)
137 goto done;
138
139 rc = fdisk_script_read_file(dp, f);
140 if (rc) {
141 errno = -rc;
142 goto done;
143 }
144
145 res = dp;
146 done:
147 fclose(f);
148 if (!res)
149 fdisk_unref_script(dp);
150 else
151 errno = 0;
152
153 return res;
154 }
155
156 /**
157 * fdisk_ref_script:
158 * @dp: script pointer
159 *
160 * Increments reference counter.
161 */
162 void fdisk_ref_script(struct fdisk_script *dp)
163 {
164 if (dp)
165 dp->refcount++;
166 }
167
168 static void fdisk_reset_script(struct fdisk_script *dp)
169 {
170 assert(dp);
171
172 DBG(SCRIPT, ul_debugobj(dp, "reset"));
173
174 if (dp->table)
175 fdisk_reset_table(dp->table);
176
177 while (!list_empty(&dp->headers)) {
178 struct fdisk_scriptheader *fi = list_entry(dp->headers.next,
179 struct fdisk_scriptheader, headers);
180 fdisk_script_free_header(fi);
181 }
182 INIT_LIST_HEAD(&dp->headers);
183 }
184
185 /**
186 * fdisk_unref_script:
187 * @dp: script pointer
188 *
189 * Decrements reference counter, on zero the @dp is automatically
190 * deallocated.
191 */
192 void fdisk_unref_script(struct fdisk_script *dp)
193 {
194 if (!dp)
195 return;
196
197 dp->refcount--;
198 if (dp->refcount <= 0) {
199 fdisk_reset_script(dp);
200 fdisk_unref_context(dp->cxt);
201 fdisk_unref_table(dp->table);
202 DBG(SCRIPT, ul_debugobj(dp, "free script"));
203 free(dp);
204 }
205 }
206
207 /**
208 * fdisk_script_set_userdata
209 * @dp: script
210 * @data: your data
211 *
212 * Sets data usable for example in callbacks (e.g fdisk_script_set_fgets()).
213 *
214 * Returns: 0 on success, <0 on error.
215 */
216 int fdisk_script_set_userdata(struct fdisk_script *dp, void *data)
217 {
218 assert(dp);
219 dp->userdata = data;
220 return 0;
221 }
222
223 /**
224 * fdisk_script_get_userdata
225 * @dp: script
226 *
227 * Returns: user data or NULL.
228 */
229 void *fdisk_script_get_userdata(struct fdisk_script *dp)
230 {
231 assert(dp);
232 return dp->userdata;
233 }
234
235 static struct fdisk_scriptheader *script_get_header(struct fdisk_script *dp,
236 const char *name)
237 {
238 struct list_head *p;
239
240 list_for_each(p, &dp->headers) {
241 struct fdisk_scriptheader *fi = list_entry(p, struct fdisk_scriptheader, headers);
242
243 if (c_strcasecmp(fi->name, name) == 0)
244 return fi;
245 }
246
247 return NULL;
248 }
249
250 /**
251 * fdisk_script_get_header:
252 * @dp: script instance
253 * @name: header name
254 *
255 * Returns: pointer to header data or NULL.
256 */
257 const char *fdisk_script_get_header(struct fdisk_script *dp, const char *name)
258 {
259 struct fdisk_scriptheader *fi;
260
261 assert(dp);
262 assert(name);
263
264 fi = script_get_header(dp, name);
265 return fi ? fi->data : NULL;
266 }
267
268 /**
269 * fdisk_script_set_header:
270 * @dp: script instance
271 * @name: header name
272 * @data: header data (or NULL)
273 *
274 * The headers are used as global options for whole partition
275 * table, always one header per line.
276 *
277 * If no @data is specified then the header is removed. If header does not exist
278 * and @data is specified then a new header is added.
279 *
280 * Note that libfdisk can be used to specify arbitrary custom header, the default
281 * built-in headers are "unit" and "label", and some label specific headers
282 * (for example "uuid" and "name" for GPT).
283 *
284 * Returns: 0 on success, <0 on error
285 */
286 int fdisk_script_set_header(struct fdisk_script *dp,
287 const char *name,
288 const char *data)
289 {
290 struct fdisk_scriptheader *fi;
291
292 if (!dp || !name)
293 return -EINVAL;
294
295 fi = script_get_header(dp, name);
296 if (!fi && !data)
297 return 0; /* want to remove header that does not exist, success */
298
299 if (!data) {
300 DBG(SCRIPT, ul_debugobj(dp, "freeing header %s", name));
301
302 /* no data, remove the header */
303 fdisk_script_free_header(fi);
304 return 0;
305 }
306
307 if (!fi) {
308 int rc;
309
310 DBG(SCRIPT, ul_debugobj(dp, "setting new header %s='%s'", name, data));
311
312 /* new header */
313 fi = calloc(1, sizeof(*fi));
314 if (!fi)
315 return -ENOMEM;
316 INIT_LIST_HEAD(&fi->headers);
317
318 rc = strdup_to_struct_member(fi, name, name);
319 if (!rc)
320 rc = strdup_to_struct_member(fi, data, data);
321 if (rc) {
322 fdisk_script_free_header(fi);
323 return rc;
324 }
325 list_add_tail(&fi->headers, &dp->headers);
326 } else {
327 /* update existing */
328 char *x = strdup(data);
329
330 DBG(SCRIPT, ul_debugobj(dp, "update '%s' header '%s' -> '%s'", name, fi->data, data));
331
332 if (!x)
333 return -ENOMEM;
334 free(fi->data);
335 fi->data = x;
336 }
337
338 if (strcmp(name, "label") == 0)
339 dp->label = NULL;
340
341 return 0;
342 }
343
344 /**
345 * fdisk_script_get_table:
346 * @dp: script
347 *
348 * The table represents partitions holded by the script. The table is possible to
349 * fill by fdisk_script_read_context() or fdisk_script_read_file(). All the "read"
350 * functions remove old partitions from the table. See also fdisk_script_set_table().
351 *
352 * Returns: NULL or script table.
353 */
354 struct fdisk_table *fdisk_script_get_table(struct fdisk_script *dp)
355 {
356 assert(dp);
357
358 if (!dp->table)
359 /*
360 * Make sure user has access to the same table as script. If
361 * there is no table then create a new one and reuse it later.
362 */
363 dp->table = fdisk_new_table();
364
365 return dp->table;
366 }
367
368 /**
369 * fdisk_script_set_table:
370 * @dp: script
371 * @tb: table
372 *
373 * Replaces table used by script and creates a new reference to @tb. This
374 * function can be used to generate a new script table independently on the current
375 * context and without any file reading.
376 *
377 * This is useful for example to create partition table with the same basic
378 * settings (e.g. label-id, ...) but with different partitions -- just call
379 * fdisk_script_read_context() to get current settings and then
380 * fdisk_script_set_table() to set a different layout.
381 *
382 * If @tb is NULL then the current script table is unreferenced.
383 *
384 * Note that script read_ functions (e.g. fdisk_script_read_context()) create
385 * always a new script table.
386 *
387 * Returns: 0 on success, <0 on error
388 *
389 * Since: 2.35
390 */
391 int fdisk_script_set_table(struct fdisk_script *dp, struct fdisk_table *tb)
392 {
393 if (!dp)
394 return -EINVAL;
395
396 fdisk_ref_table(tb);
397 fdisk_unref_table(dp->table);
398 dp->table = tb;
399
400 DBG(SCRIPT, ul_debugobj(dp, "table replaced"));
401 return 0;
402 }
403
404 static struct fdisk_label *script_get_label(struct fdisk_script *dp)
405 {
406 assert(dp);
407 assert(dp->cxt);
408
409 if (!dp->label) {
410 dp->label = fdisk_get_label(dp->cxt,
411 fdisk_script_get_header(dp, "label"));
412 DBG(SCRIPT, ul_debugobj(dp, "label '%s'", dp->label ? dp->label->name : ""));
413 }
414 return dp->label;
415 }
416
417 /**
418 * fdisk_script_get_nlines:
419 * @dp: script
420 *
421 * Returns: number of parsed lines or <0 on error.
422 */
423 int fdisk_script_get_nlines(struct fdisk_script *dp)
424 {
425 assert(dp);
426 return dp->nlines;
427 }
428
429 /**
430 * fdisk_script_has_force_label:
431 * @dp: script
432 *
433 * Label has been explicitly specified in the script.
434 *
435 * Since: 2.30
436 *
437 * Returns: true if "label: name" has been parsed.
438 */
439 int fdisk_script_has_force_label(struct fdisk_script *dp)
440 {
441 assert(dp);
442 return dp->force_label;
443 }
444
445
446 /**
447 * fdisk_script_read_context:
448 * @dp: script
449 * @cxt: context
450 *
451 * Reads data from the @cxt context (on disk partition table) into the script.
452 * If the context is not specified then defaults to context used for fdisk_new_script().
453 *
454 * Return: 0 on success, <0 on error.
455 */
456 int fdisk_script_read_context(struct fdisk_script *dp, struct fdisk_context *cxt)
457 {
458 struct fdisk_label *lb;
459 int rc;
460 char *p = NULL;
461 char buf[64];
462
463 if (!dp || (!cxt && !dp->cxt))
464 return -EINVAL;
465
466 if (!cxt)
467 cxt = dp->cxt;
468
469 DBG(SCRIPT, ul_debugobj(dp, "reading context into script"));
470 fdisk_reset_script(dp);
471
472 lb = fdisk_get_label(cxt, NULL);
473 if (!lb)
474 return -EINVAL;
475
476 /* allocate (if not yet) and fill table */
477 rc = fdisk_get_partitions(cxt, &dp->table);
478 if (rc)
479 return rc;
480
481 /* generate headers */
482 rc = fdisk_script_set_header(dp, "label", fdisk_label_get_name(lb));
483
484 if (!rc && fdisk_get_disklabel_id(cxt, &p) == 0 && p) {
485 rc = fdisk_script_set_header(dp, "label-id", p);
486 free(p);
487 }
488 if (!rc && cxt->dev_path)
489 rc = fdisk_script_set_header(dp, "device", cxt->dev_path);
490 if (!rc)
491 rc = fdisk_script_set_header(dp, "unit", "sectors");
492
493 if (!rc && fdisk_is_label(cxt, GPT)) {
494 struct fdisk_labelitem item = FDISK_LABELITEM_INIT;
495
496 /* first-lba */
497 rc = fdisk_get_disklabel_item(cxt, GPT_LABELITEM_FIRSTLBA, &item);
498 if (!rc) {
499 snprintf(buf, sizeof(buf), "%"PRIu64, item.data.num64);
500 rc = fdisk_script_set_header(dp, "first-lba", buf);
501 }
502
503 /* last-lba */
504 if (!rc)
505 rc = fdisk_get_disklabel_item(cxt, GPT_LABELITEM_LASTLBA, &item);
506 if (!rc) {
507 snprintf(buf, sizeof(buf), "%"PRIu64, item.data.num64);
508 rc = fdisk_script_set_header(dp, "last-lba", buf);
509 }
510
511 /* table-length */
512 if (!rc) {
513 size_t n = fdisk_get_npartitions(cxt);
514 if (n != FDISK_GPT_NPARTITIONS_DEFAULT) {
515 snprintf(buf, sizeof(buf), "%zu", n);
516 rc = fdisk_script_set_header(dp, "table-length", buf);
517 }
518 }
519 }
520
521 if (!rc && fdisk_get_grain_size(cxt) != 2048 * 512) {
522 snprintf(buf, sizeof(buf), "%lu", fdisk_get_grain_size(cxt));
523 rc = fdisk_script_set_header(dp, "grain", buf);
524 }
525
526 if (!rc) {
527 snprintf(buf, sizeof(buf), "%lu", fdisk_get_sector_size(cxt));
528 rc = fdisk_script_set_header(dp, "sector-size", buf);
529 }
530
531 DBG(SCRIPT, ul_debugobj(dp, "read context done [rc=%d]", rc));
532 return rc;
533 }
534
535 /**
536 * fdisk_script_enable_json:
537 * @dp: script
538 * @json: 0 or 1
539 *
540 * Disable/Enable JSON output format.
541 *
542 * Returns: 0 on success, <0 on error.
543 */
544 int fdisk_script_enable_json(struct fdisk_script *dp, int json)
545 {
546 assert(dp);
547
548 dp->json = json;
549 return 0;
550 }
551
552 static int write_file_json(struct fdisk_script *dp, FILE *f)
553 {
554 struct list_head *h;
555 struct fdisk_partition *pa;
556 struct fdisk_iter itr;
557 const char *devname = NULL;
558 struct ul_jsonwrt json;
559
560 assert(dp);
561 assert(f);
562
563 DBG(SCRIPT, ul_debugobj(dp, "writing json dump to file"));
564
565 ul_jsonwrt_init(&json, f, 0, UL_JSON_PRETTY);
566 ul_jsonwrt_root_open(&json);
567
568 ul_jsonwrt_object_open(&json, "partitiontable");
569
570 /* script headers */
571 list_for_each(h, &dp->headers) {
572 struct fdisk_scriptheader *fi = list_entry(h, struct fdisk_scriptheader, headers);
573 const char *name = fi->name;
574 int num = 0;
575
576 if (strcmp(name, "first-lba") == 0) {
577 name = "firstlba";
578 num = 1;
579 } else if (strcmp(name, "last-lba") == 0) {
580 name = "lastlba";
581 num = 1;
582 } else if (strcmp(name, "sector-size") == 0) {
583 name = "sectorsize";
584 num = 1;
585 } else if (strcmp(name, "label-id") == 0)
586 name = "id";
587
588 if (num)
589 ul_jsonwrt_value_raw(&json, name, fi->data);
590 else
591 ul_jsonwrt_value_s(&json, name, fi->data);
592
593 if (strcmp(name, "device") == 0)
594 devname = fi->data;
595 }
596
597
598 if (!dp->table || fdisk_table_is_empty(dp->table)) {
599 DBG(SCRIPT, ul_debugobj(dp, "script table empty"));
600 goto done;
601 }
602
603 DBG(SCRIPT, ul_debugobj(dp, "%zu entries", fdisk_table_get_nents(dp->table)));
604
605 ul_jsonwrt_array_open(&json, "partitions");
606
607 fdisk_reset_iter(&itr, FDISK_ITER_FORWARD);
608 while (fdisk_table_next_partition(dp->table, &itr, &pa) == 0) {
609 char *p = NULL;
610
611 ul_jsonwrt_object_open(&json, NULL);
612 if (devname)
613 p = fdisk_partname(devname, pa->partno + 1);
614 if (p) {
615 DBG(SCRIPT, ul_debugobj(dp, "write %s entry", p));
616 ul_jsonwrt_value_s(&json, "node", p);
617 free(p);
618 }
619
620 if (fdisk_partition_has_start(pa))
621 ul_jsonwrt_value_u64(&json, "start", (uintmax_t)pa->start);
622
623 if (fdisk_partition_has_size(pa))
624 ul_jsonwrt_value_u64(&json, "size", (uintmax_t)pa->size);
625
626 if (pa->type && fdisk_parttype_get_string(pa->type))
627 ul_jsonwrt_value_s(&json, "type", fdisk_parttype_get_string(pa->type));
628
629 else if (pa->type) {
630 ul_jsonwrt_value_open(&json, "type");
631 fprintf(f, "\"%x\"", fdisk_parttype_get_code(pa->type));
632 ul_jsonwrt_value_close(&json);
633 }
634
635 if (pa->uuid)
636 ul_jsonwrt_value_s(&json, "uuid", pa->uuid);
637 if (pa->name && *pa->name)
638 ul_jsonwrt_value_s(&json, "name", pa->name);
639
640 /* for MBR attr=80 means bootable */
641 if (pa->attrs) {
642 struct fdisk_label *lb = script_get_label(dp);
643
644 if (!lb || fdisk_label_get_type(lb) != FDISK_DISKLABEL_DOS)
645 ul_jsonwrt_value_s(&json, "attrs", pa->attrs);
646 }
647
648 if (fdisk_partition_is_bootable(pa))
649 ul_jsonwrt_value_boolean(&json, "bootable", 1);
650 ul_jsonwrt_object_close(&json);
651 }
652
653 ul_jsonwrt_array_close(&json);
654 done:
655 ul_jsonwrt_object_close(&json);
656 ul_jsonwrt_root_close(&json);
657
658 DBG(SCRIPT, ul_debugobj(dp, "write script done"));
659 return 0;
660 }
661
662 static int write_file_sfdisk(struct fdisk_script *dp, FILE *f)
663 {
664 struct list_head *h;
665 struct fdisk_partition *pa;
666 struct fdisk_iter itr;
667 const char *devname = NULL;
668
669 assert(dp);
670 assert(f);
671
672 DBG(SCRIPT, ul_debugobj(dp, "writing sfdisk-like script to file"));
673
674 /* script headers */
675 list_for_each(h, &dp->headers) {
676 struct fdisk_scriptheader *fi = list_entry(h, struct fdisk_scriptheader, headers);
677 fprintf(f, "%s: %s\n", fi->name, fi->data);
678 if (strcmp(fi->name, "device") == 0)
679 devname = fi->data;
680 }
681
682 if (!dp->table || fdisk_table_is_empty(dp->table)) {
683 DBG(SCRIPT, ul_debugobj(dp, "script table empty"));
684 return 0;
685 }
686
687 DBG(SCRIPT, ul_debugobj(dp, "%zu entries", fdisk_table_get_nents(dp->table)));
688
689 fputc('\n', f);
690
691 fdisk_reset_iter(&itr, FDISK_ITER_FORWARD);
692 while (fdisk_table_next_partition(dp->table, &itr, &pa) == 0) {
693 char *p = NULL;
694 int sep = 0;
695
696 if (devname)
697 p = fdisk_partname(devname, pa->partno + 1);
698 if (p) {
699 DBG(SCRIPT, ul_debugobj(dp, "write %s entry", p));
700 fprintf(f, "%s : ", p);
701 free(p);
702 } else
703 fprintf(f, "%zu : ", pa->partno + 1);
704
705 if (fdisk_partition_has_start(pa))
706 sep = fprintf(f, "start=%12ju", (uintmax_t)pa->start);
707 if (fdisk_partition_has_size(pa))
708 sep = fprintf(f, "%ssize=%12ju",
709 sep ? ", " : " ", (uintmax_t)pa->size);
710
711 if (pa->type && fdisk_parttype_get_string(pa->type))
712 sep = fprintf(f, "%stype=%s",
713 sep ? ", " : " ",
714 fdisk_parttype_get_string(pa->type));
715 else if (pa->type)
716 sep = fprintf(f, "%stype=%x",
717 sep ? ", " : " ",
718 fdisk_parttype_get_code(pa->type));
719
720 if (pa->uuid)
721 sep = fprintf(f, "%suuid=%s", sep ? ", " : " ", pa->uuid);
722 if (pa->name && *pa->name) {
723 sep = fprintf(f, "%sname=", sep ? ", " : " ");
724 fputs_quoted(pa->name, f);
725 }
726
727 /* for MBR attr=80 means bootable */
728 if (pa->attrs) {
729 struct fdisk_label *lb = script_get_label(dp);
730
731 if (!lb || fdisk_label_get_type(lb) != FDISK_DISKLABEL_DOS)
732 sep = fprintf(f, "%sattrs=\"%s\"",
733 sep ? ", " : " ",
734 pa->attrs);
735 }
736 if (fdisk_partition_is_bootable(pa))
737 sep = fprintf(f, "%sbootable", sep ? ", " : " ");
738 fputc('\n', f);
739 }
740
741 DBG(SCRIPT, ul_debugobj(dp, "write script done"));
742 return 0;
743 }
744
745 /**
746 * fdisk_script_write_file:
747 * @dp: script
748 * @f: output file
749 *
750 * Writes script @dp to the file @f.
751 *
752 * Returns: 0 on success, <0 on error.
753 */
754 int fdisk_script_write_file(struct fdisk_script *dp, FILE *f)
755 {
756 assert(dp);
757
758 if (dp->json)
759 return write_file_json(dp, f);
760
761 return write_file_sfdisk(dp, f);
762 }
763
764 static inline int is_header_line(const char *s)
765 {
766 const char *p = strchr(s, ':');
767
768 if (!p || p == s || !*(p + 1) || strchr(s, '='))
769 return 0;
770
771 return 1;
772 }
773
774 /* parses "<name>: value", note modifies @s*/
775 static int parse_line_header(struct fdisk_script *dp, char *s)
776 {
777 size_t i;
778 char *name, *value;
779 static const char *const supported[] = {
780 "label", "unit", "label-id", "device", "grain",
781 "first-lba", "last-lba", "table-length", "sector-size"
782 };
783
784 DBG(SCRIPT, ul_debugobj(dp, " parse header '%s'", s));
785
786 if (!s || !*s)
787 return -EINVAL;
788
789 name = s;
790 value = strchr(s, ':');
791 if (!value)
792 return -EINVAL;
793 *value = '\0';
794 value++;
795
796 ltrim_whitespace((unsigned char *) name);
797 rtrim_whitespace((unsigned char *) name);
798 ltrim_whitespace((unsigned char *) value);
799 rtrim_whitespace((unsigned char *) value);
800
801 if (!*name || !*value)
802 return -EINVAL;
803
804 /* check header name */
805 for (i = 0; i < ARRAY_SIZE(supported); i++) {
806 if (strcmp(name, supported[i]) == 0)
807 break;
808 }
809 if (i == ARRAY_SIZE(supported))
810 return -ENOTSUP;
811
812 /* header specific actions */
813 if (strcmp(name, "label") == 0) {
814 if (dp->cxt && !fdisk_get_label(dp->cxt, value))
815 return -EINVAL; /* unknown label name */
816 dp->force_label = 1;
817
818 } else if (strcmp(name, "sector-size") == 0) {
819 uint64_t x = 0;
820
821 if (ul_strtou64(value, &x, 10) != 0)
822 return -EINVAL;
823 if (x > ULONG_MAX || x % 512)
824 return -ERANGE;
825 dp->sector_size = (unsigned long) x;
826
827 if (dp->cxt && dp->sector_size && dp->cxt->sector_size
828 && dp->sector_size != dp->cxt->sector_size)
829 fdisk_warnx(dp->cxt, _("The script and device sector size differ; the sizes will be recalculated to match the device."));
830
831 } else if (strcmp(name, "unit") == 0) {
832 if (strcmp(value, "sectors") != 0)
833 return -EINVAL; /* only "sectors" supported */
834
835 }
836
837 return fdisk_script_set_header(dp, name, value);
838 }
839
840 static int partno_from_devname(char *s)
841 {
842 intmax_t num;
843 size_t sz;
844 char *end, *p;
845
846 if (!s || !*s)
847 return -1;
848
849 sz = rtrim_whitespace((unsigned char *)s);
850 end = p = s + sz;
851
852 while (p > s && isdigit(*(p - 1)))
853 p--;
854 if (p == end)
855 return -1;
856 end = NULL;
857 errno = 0;
858 num = strtol(p, &end, 10);
859 if (errno || !end || p == end)
860 return -1;
861
862 if (num < INT32_MIN || num > INT32_MAX) {
863 errno = ERANGE;
864 return -1;
865 }
866 return num - 1;
867 }
868
869
870 /* returns zero terminated string with next token and @str is updated */
871 static char *next_token(char **str)
872 {
873 char *tk_begin = NULL,
874 *tk_end = NULL,
875 *end = NULL,
876 *p;
877 int open_quote = 0, terminated = 0;
878
879 for (p = *str; p && *p; p++) {
880 if (!tk_begin) {
881 if (isblank(*p))
882 continue;
883 tk_begin = *p == '"' ? p + 1 : p;
884 }
885 if (*p == '"')
886 open_quote ^= 1;
887 if (open_quote)
888 continue;
889 if (isblank(*p) || *p == ',' || *p == ';' || *p == '"' )
890 tk_end = p;
891 else if (*(p + 1) == '\0')
892 tk_end = p + 1;
893 if (tk_begin && tk_end)
894 break;
895 }
896
897 if (!tk_end)
898 return NULL;
899
900 end = tk_end;
901
902 /* skip closing quotes */
903 if (*end == '"')
904 end++;
905
906 /* token is terminated by blank (or blank is before "," or ";") */
907 if (isblank(*end)) {
908 end = (char *) skip_blank(end);
909 terminated++;
910 }
911
912 /* token is terminated by "," or ";" */
913 if (*end == ',' || *end == ';') {
914 end++;
915 terminated++;
916
917 /* token is terminated by \0 */
918 } else if (!*end)
919 terminated++;
920
921 if (!terminated) {
922 DBG(SCRIPT, ul_debug("unterminated token '%s'", end));
923 return NULL;
924 }
925
926 /* skip extra space after terminator */
927 end = (char *) skip_blank(end);
928
929 *tk_end = '\0';
930 *str = end;
931 return tk_begin;
932 }
933
934 /*
935 * "[-]<,;>"
936 * "[ ]<,;>"
937 * "- <value>"
938 */
939 static int is_default_value(char **str)
940 {
941 char *p = (char *) skip_blank(*str);
942 int blank = 0;
943
944 if (*p == '-') {
945 char *x = ++p;
946 p = (char *) skip_blank(x);
947 blank = x < p; /* "- " */
948 }
949
950 if (*p == ';' || *p == ',') {
951 *str = ++p;
952 return 1;
953 }
954 if (*p == '\0' || blank) {
955 *str = p;
956 return 1;
957 }
958
959 return 0;
960 }
961
962 static int next_string(char **s, char **str)
963 {
964 char *tk, *p = NULL;
965 int rc = -EINVAL;
966
967 assert(s);
968 assert(str);
969
970 tk = next_token(s);
971 if (tk) {
972 p = strdup(tk);
973 rc = p ? 0 : -ENOMEM;
974 }
975
976 *str = p;
977 return rc;
978 }
979
980 static int skip_optional_sign(char **str)
981 {
982 char *p = (char *) skip_blank(*str);
983
984 if (*p == '-' || *p == '+') {
985 *str = p+1;
986 return *p;
987 }
988 return 0;
989 }
990
991 static int recount_script2device_sectors(struct fdisk_script *dp, uint64_t *num)
992 {
993 if (!dp->cxt ||
994 !dp->sector_size ||
995 !dp->cxt->sector_size)
996 return 0;
997
998 if (dp->sector_size > dp->cxt->sector_size)
999 *num *= (dp->sector_size / dp->cxt->sector_size);
1000
1001 else if (dp->sector_size < dp->cxt->sector_size) {
1002 uint64_t x = dp->cxt->sector_size / dp->sector_size;
1003
1004 if (*num % x)
1005 return -EINVAL;
1006 *num /= x;
1007 }
1008
1009 return 0;
1010 }
1011
1012 static int parse_start_value(struct fdisk_script *dp, struct fdisk_partition *pa, char **str)
1013 {
1014 char *tk;
1015 int rc = 0;
1016
1017 assert(str);
1018
1019 if (is_default_value(str)) {
1020 fdisk_partition_start_follow_default(pa, 1);
1021 return 0;
1022 }
1023
1024 tk = next_token(str);
1025 if (!tk)
1026 return -EINVAL;
1027
1028 if (strcmp(tk, "+") == 0) {
1029 fdisk_partition_start_follow_default(pa, 1);
1030 pa->movestart = FDISK_MOVE_DOWN;
1031 } else {
1032 int pow = 0, sign = skip_optional_sign(&tk);
1033 uint64_t num;
1034
1035 rc = ul_parse_size(tk, (uintmax_t *) &num, &pow);
1036 if (!rc) {
1037 if (pow) { /* specified as <num><suffix> */
1038 if (!dp->cxt->sector_size) {
1039 rc = -EINVAL;
1040 goto done;
1041 }
1042 num /= dp->cxt->sector_size;
1043 } else {
1044 rc = recount_script2device_sectors(dp, &num);
1045 if (rc) {
1046 fdisk_warnx(dp->cxt, _("Can't recalculate partition start to the device sectors"));
1047 goto done;
1048 }
1049 }
1050
1051 fdisk_partition_set_start(pa, num);
1052
1053 pa->movestart = sign == '-' ? FDISK_MOVE_DOWN :
1054 sign == '+' ? FDISK_MOVE_UP :
1055 FDISK_MOVE_NONE;
1056 }
1057 fdisk_partition_start_follow_default(pa, 0);
1058 }
1059
1060 done:
1061 DBG(SCRIPT, ul_debugobj(dp, " start parse result: rc=%d, move=%s, start=%ju, default=%s",
1062 rc, pa->movestart == FDISK_MOVE_DOWN ? "down" :
1063 pa->movestart == FDISK_MOVE_UP ? "up" : "none",
1064 pa->start,
1065 pa->start_follow_default ? "on" : "off"));
1066 return rc;
1067 }
1068
1069 static int parse_size_value(struct fdisk_script *dp, struct fdisk_partition *pa, char **str)
1070 {
1071 char *tk;
1072 int rc = 0;
1073
1074 if (is_default_value(str)) {
1075 fdisk_partition_end_follow_default(pa, 1);
1076 return 0;
1077 }
1078
1079 tk = next_token(str);
1080 if (!tk)
1081 return -EINVAL;
1082
1083 if (strcmp(tk, "+") == 0) {
1084 fdisk_partition_end_follow_default(pa, 1);
1085 pa->resize = FDISK_RESIZE_ENLARGE;
1086 } else {
1087 /* '[+-]<number>[<suffix] */
1088 int pow = 0, sign = skip_optional_sign(&tk);
1089 uint64_t num;
1090
1091 rc = ul_parse_size(tk, (uintmax_t *) &num, &pow);
1092 if (!rc) {
1093 if (pow) { /* specified as <size><suffix> */
1094 if (!dp->cxt->sector_size) {
1095 rc = -EINVAL;
1096 goto done;
1097 }
1098 num /= dp->cxt->sector_size;
1099 } else {
1100 /* specified as number of sectors */
1101 fdisk_partition_size_explicit(pa, 1);
1102 rc = recount_script2device_sectors(dp, &num);
1103 if (rc) {
1104 fdisk_warnx(dp->cxt, _("Can't recalculate partition size to the device sectors"));
1105 goto done;
1106 }
1107 }
1108
1109 fdisk_partition_set_size(pa, num);
1110 pa->resize = sign == '-' ? FDISK_RESIZE_REDUCE :
1111 sign == '+' ? FDISK_RESIZE_ENLARGE :
1112 FDISK_RESIZE_NONE;
1113 }
1114 fdisk_partition_end_follow_default(pa, 0);
1115 }
1116
1117 done:
1118 DBG(SCRIPT, ul_debugobj(dp, " size parse result: rc=%d, move=%s, size=%ju, default=%s",
1119 rc, pa->resize == FDISK_RESIZE_REDUCE ? "reduce" :
1120 pa->resize == FDISK_RESIZE_ENLARGE ? "enlarge" : "none",
1121 pa->size,
1122 pa->end_follow_default ? "on" : "off"));
1123 return rc;
1124 }
1125
1126
1127 #define FDISK_SCRIPT_PARTTYPE_PARSE_FLAGS \
1128 (FDISK_PARTTYPE_PARSE_DATA | FDISK_PARTTYPE_PARSE_DATALAST | \
1129 FDISK_PARTTYPE_PARSE_SHORTCUT | FDISK_PARTTYPE_PARSE_ALIAS | \
1130 FDISK_PARTTYPE_PARSE_NAME | \
1131 FDISK_PARTTYPE_PARSE_DEPRECATED)
1132
1133 /* dump format
1134 * <device>: start=<num>, size=<num>, type=<string>, ...
1135 */
1136 static int parse_line_nameval(struct fdisk_script *dp, char *s)
1137 {
1138 char *p, *x;
1139 struct fdisk_partition *pa;
1140 int rc = 0;
1141 int pno;
1142
1143 assert(dp);
1144 assert(s);
1145 assert(dp->table);
1146
1147 DBG(SCRIPT, ul_debugobj(dp, " parse script line: '%s'", s));
1148
1149 pa = fdisk_new_partition();
1150 if (!pa)
1151 return -ENOMEM;
1152
1153 fdisk_partition_start_follow_default(pa, 1);
1154 fdisk_partition_end_follow_default(pa, 1);
1155 fdisk_partition_partno_follow_default(pa, 1);
1156
1157 /* set partno */
1158 p = strstr(s, " : "); /* device : start= */
1159 if (!p)
1160 p = strstr(s, " :"); /* device :start= */
1161 if (!p)
1162 p = strstr(s, ": "); /* device: start= */
1163 if (!p)
1164 p = strchr(s, ':');
1165
1166 x = strchr(s, '=');
1167 if (p && (!x || p < x)) {
1168 *p = '\0';
1169 p++;
1170
1171 pno = partno_from_devname(s);
1172 if (pno >= 0) {
1173 fdisk_partition_partno_follow_default(pa, 0);
1174 fdisk_partition_set_partno(pa, pno);
1175 }
1176 if (*p == ':')
1177 p++;
1178 } else
1179 p = s;
1180
1181 while (rc == 0 && p && *p) {
1182
1183 DBG(SCRIPT, ul_debugobj(dp, " parsing '%s'", p));
1184 p = (char *) skip_blank(p);
1185
1186 if (!c_strncasecmp(p, "start=", 6)) {
1187 p += 6;
1188 rc = parse_start_value(dp, pa, &p);
1189
1190 } else if (!c_strncasecmp(p, "size=", 5)) {
1191 p += 5;
1192 rc = parse_size_value(dp, pa, &p);
1193
1194 } else if (!c_strncasecmp(p, "bootable", 8)) {
1195 /* we use next_token() to skip possible extra space */
1196 char *tk = next_token(&p);
1197 if (tk && c_strcasecmp(tk, "bootable") == 0)
1198 pa->boot = 1;
1199 else
1200 rc = -EINVAL;
1201
1202 } else if (!c_strncasecmp(p, "attrs=", 6)) {
1203 p += 6;
1204 free(pa->attrs);
1205 rc = next_string(&p, &pa->attrs);
1206
1207 } else if (!c_strncasecmp(p, "uuid=", 5)) {
1208 p += 5;
1209 free(pa->uuid);
1210 rc = next_string(&p, &pa->uuid);
1211
1212 } else if (!c_strncasecmp(p, "name=", 5)) {
1213 p += 5;
1214 free(pa->name);
1215 rc = next_string(&p, &pa->name);
1216 if (!rc)
1217 unhexmangle_string(pa->name);
1218
1219 } else if (!c_strncasecmp(p, "type=", 5) ||
1220 !c_strncasecmp(p, "Id=", 3)) { /* backward compatibility */
1221 char *type = NULL;
1222
1223 fdisk_unref_parttype(pa->type);
1224 pa->type = NULL;
1225
1226 p += ((*p == 'I' || *p == 'i') ? 3 : 5); /* "Id=", "type=" */
1227
1228 rc = next_string(&p, &type);
1229 if (rc == 0) {
1230 pa->type = fdisk_label_advparse_parttype(script_get_label(dp),
1231 type, FDISK_SCRIPT_PARTTYPE_PARSE_FLAGS);
1232 if (!pa->type)
1233 rc = -EINVAL;
1234 }
1235 free(type);
1236 } else {
1237 DBG(SCRIPT, ul_debugobj(dp, "script parse error: unknown field '%s'", p));
1238 rc = -EINVAL;
1239 break;
1240 }
1241 }
1242
1243 if (!rc)
1244 rc = fdisk_table_add_partition(dp->table, pa);
1245 if (rc)
1246 DBG(SCRIPT, ul_debugobj(dp, "script parse error: [rc=%d]", rc));
1247
1248 fdisk_unref_partition(pa);
1249 return rc;
1250 }
1251
1252 /* simple format:
1253 * <start>, <size>, <type>, <bootable>, ...
1254 */
1255 static int parse_line_valcommas(struct fdisk_script *dp, char *s)
1256 {
1257 int rc = 0;
1258 char *p = s;
1259 struct fdisk_partition *pa;
1260 enum { ITEM_START, ITEM_SIZE, ITEM_TYPE, ITEM_BOOTABLE };
1261 int item = -1;
1262
1263 assert(dp);
1264 assert(s);
1265 assert(dp->table);
1266
1267 pa = fdisk_new_partition();
1268 if (!pa)
1269 return -ENOMEM;
1270
1271 fdisk_partition_start_follow_default(pa, 1);
1272 fdisk_partition_end_follow_default(pa, 1);
1273 fdisk_partition_partno_follow_default(pa, 1);
1274
1275 while (rc == 0 && p && *p) {
1276 char *begin;
1277
1278 p = (char *) skip_blank(p);
1279 item++;
1280
1281 DBG(SCRIPT, ul_debugobj(dp, " parsing item %d ('%s')", item, p));
1282 begin = p;
1283
1284 switch (item) {
1285 case ITEM_START:
1286 rc = parse_start_value(dp, pa, &p);
1287 break;
1288 case ITEM_SIZE:
1289 rc = parse_size_value(dp, pa, &p);
1290 break;
1291 case ITEM_TYPE:
1292 {
1293 char *str = NULL;
1294
1295 fdisk_unref_parttype(pa->type);
1296 pa->type = NULL;
1297
1298 if (*p == ',' || *p == ';' || is_default_value(&p))
1299 break; /* use default type */
1300
1301 rc = next_string(&p, &str);
1302 if (rc)
1303 break;
1304
1305 pa->type = fdisk_label_advparse_parttype(script_get_label(dp),
1306 str, FDISK_SCRIPT_PARTTYPE_PARSE_FLAGS);
1307 free(str);
1308 if (!pa->type)
1309 rc = -EINVAL;
1310 break;
1311 }
1312 case ITEM_BOOTABLE:
1313 if (*p == ',' || *p == ';')
1314 break;
1315 else {
1316 char *tk = next_token(&p);
1317 if (tk && *tk == '*' && *(tk + 1) == '\0')
1318 pa->boot = 1;
1319 else if (tk && *tk == '-' && *(tk + 1) == '\0')
1320 pa->boot = 0;
1321 else if (tk && *tk == '+' && *(tk + 1) == '\0')
1322 pa->boot = 1;
1323 else
1324 rc = -EINVAL;
1325 }
1326 break;
1327 default:
1328 break;
1329 }
1330
1331 if (begin == p)
1332 p++;
1333 }
1334
1335 if (!rc)
1336 rc = fdisk_table_add_partition(dp->table, pa);
1337 if (rc)
1338 DBG(SCRIPT, ul_debugobj(dp, "script parse error: [rc=%d]", rc));
1339
1340 fdisk_unref_partition(pa);
1341 return rc;
1342 }
1343
1344 /* modifies @s ! */
1345 static int fdisk_script_read_buffer(struct fdisk_script *dp, char *s)
1346 {
1347 int rc = 0;
1348
1349 assert(dp);
1350 assert(s);
1351
1352 DBG(SCRIPT, ul_debugobj(dp, " parsing buffer"));
1353
1354 s = (char *) skip_blank(s);
1355 if (!s || !*s)
1356 return 0; /* nothing baby, ignore */
1357
1358 if (!dp->table && fdisk_script_get_table(dp) == NULL)
1359 return -ENOMEM;
1360
1361 /* parse header lines only if no partition specified yet */
1362 if (fdisk_table_is_empty(dp->table) && is_header_line(s))
1363 rc = parse_line_header(dp, s);
1364
1365 /* parse script format */
1366 else if (strchr(s, '='))
1367 rc = parse_line_nameval(dp, s);
1368
1369 /* parse simple <value>, ... format */
1370 else
1371 rc = parse_line_valcommas(dp, s);
1372
1373 if (rc)
1374 DBG(SCRIPT, ul_debugobj(dp, "%zu: parse error [rc=%d]",
1375 dp->nlines, rc));
1376 return rc;
1377 }
1378
1379 /**
1380 * fdisk_script_set_fgets:
1381 * @dp: script
1382 * @fn_fgets: callback function
1383 *
1384 * The library uses fgets() function to read the next line from the script.
1385 * This default maybe overridden by another function. Note that the function has
1386 * to return the line terminated by \n (for example readline(3) removes \n).
1387 *
1388 * Return: 0 on success, <0 on error
1389 */
1390 int fdisk_script_set_fgets(struct fdisk_script *dp,
1391 char *(*fn_fgets)(struct fdisk_script *, char *, size_t, FILE *))
1392 {
1393 assert(dp);
1394
1395 dp->fn_fgets = fn_fgets;
1396 return 0;
1397 }
1398
1399 /**
1400 * fdisk_script_read_line:
1401 * @dp: script
1402 * @f: file
1403 * @buf: buffer to store one line of the file
1404 * @bufsz: buffer size
1405 *
1406 * Reads next line into dump.
1407 *
1408 * Returns: 0 on success, <0 on error, 1 when nothing to read. For unknown headers
1409 * returns -ENOTSUP, it's usually safe to ignore this error.
1410 */
1411 int fdisk_script_read_line(struct fdisk_script *dp, FILE *f, char *buf, size_t bufsz)
1412 {
1413 char *s;
1414
1415 assert(dp);
1416 assert(f);
1417 assert(bufsz);
1418
1419 DBG(SCRIPT, ul_debugobj(dp, " parsing line %zu", dp->nlines));
1420
1421 /* read the next non-blank non-comment line */
1422 do {
1423 buf[0] = '\0';
1424 if (dp->fn_fgets) {
1425 if (dp->fn_fgets(dp, buf, bufsz, f) == NULL)
1426 return 1;
1427 } else if (fgets(buf, bufsz, f) == NULL)
1428 return 1;
1429
1430 dp->nlines++;
1431 s = strchr(buf, '\n');
1432 if (!s) {
1433 /* Missing final newline? Otherwise an extremely */
1434 /* long line - assume file was corrupted */
1435 if (feof(f)) {
1436 DBG(SCRIPT, ul_debugobj(dp, "no final newline"));
1437 s = strchr(buf, '\0');
1438 } else {
1439 DBG(SCRIPT, ul_debugobj(dp,
1440 "%zu: missing newline at line", dp->nlines));
1441 return -EINVAL;
1442 }
1443 }
1444
1445 *s = '\0';
1446 if (--s >= buf && *s == '\r')
1447 *s = '\0';
1448 s = (char *) skip_blank(buf);
1449 } while (*s == '\0' || *s == '#');
1450
1451 return fdisk_script_read_buffer(dp, s);
1452 }
1453
1454
1455 /**
1456 * fdisk_script_read_file:
1457 * @dp: script
1458 * @f: input file
1459 *
1460 * Reads file @f into script @dp.
1461 *
1462 * Returns: 0 on success, <0 on error.
1463 */
1464 int fdisk_script_read_file(struct fdisk_script *dp, FILE *f)
1465 {
1466 char buf[BUFSIZ] = { '\0' };
1467 int rc = 1;
1468
1469 assert(dp);
1470 assert(f);
1471
1472 DBG(SCRIPT, ul_debugobj(dp, "parsing file"));
1473
1474 while (!feof(f)) {
1475 rc = fdisk_script_read_line(dp, f, buf, sizeof(buf));
1476 if (rc && rc != -ENOTSUP)
1477 break;
1478 }
1479
1480 if (rc == 1)
1481 rc = 0; /* end of file */
1482
1483 DBG(SCRIPT, ul_debugobj(dp, "parsing file done [rc=%d]", rc));
1484 return rc;
1485 }
1486
1487 /**
1488 * fdisk_set_script:
1489 * @cxt: context
1490 * @dp: script (or NULL to remove previous reference)
1491 *
1492 * Sets reference to the @dp script and remove reference to the previously used
1493 * script.
1494 *
1495 * The script headers might be used by label drivers to overwrite
1496 * built-in defaults (for example disk label Id) and label driver might
1497 * optimize the default semantic to be more usable for scripts (for example to
1498 * not ask for primary/logical/extended partition type).
1499 *
1500 * Note that script also contains reference to the fdisk context (see
1501 * fdisk_new_script()). This context may be completely independent on
1502 * context used for fdisk_set_script().
1503 *
1504 * Don't forget to call fdisk_set_script(cxt, NULL); to remove this reference
1505 * if no more necessary!
1506 *
1507 * Returns: <0 on error, 0 on success.
1508 */
1509 int fdisk_set_script(struct fdisk_context *cxt, struct fdisk_script *dp)
1510 {
1511 assert(cxt);
1512
1513 /* unref old */
1514 if (cxt->script)
1515 fdisk_unref_script(cxt->script);
1516
1517 /* ref new */
1518 cxt->script = dp;
1519 if (cxt->script) {
1520 DBG(CXT, ul_debugobj(cxt, "setting reference to script %p", cxt->script));
1521 fdisk_ref_script(cxt->script);
1522 }
1523
1524 return 0;
1525 }
1526
1527 /**
1528 * fdisk_get_script:
1529 * @cxt: context
1530 *
1531 * Returns: the current script or NULL.
1532 */
1533 struct fdisk_script *fdisk_get_script(struct fdisk_context *cxt)
1534 {
1535 assert(cxt);
1536 return cxt->script;
1537 }
1538
1539 /**
1540 * fdisk_apply_script_headers:
1541 * @cxt: context
1542 * @dp: script
1543 *
1544 * Associate context @cxt with script @dp and creates a new empty disklabel.
1545 * The script may be later unreference by fdisk_set_script() with NULL as script.
1546 *
1547 * Returns: 0 on success, <0 on error.
1548 */
1549 int fdisk_apply_script_headers(struct fdisk_context *cxt, struct fdisk_script *dp)
1550 {
1551 const char *name;
1552 const char *str;
1553 int rc;
1554
1555 assert(cxt);
1556 assert(dp);
1557
1558 DBG(SCRIPT, ul_debugobj(dp, "applying script headers"));
1559 fdisk_set_script(cxt, dp);
1560
1561 if (dp->sector_size && dp->cxt->sector_size != dp->sector_size) {
1562 /*
1563 * Ignore last and first LBA if device sector size mismatch
1564 * with sector size in script. It would be possible to
1565 * recalculate it, but for GPT it will not work in some cases
1566 * as these offsets are calculated by relative number of
1567 * sectors. It's better to use library defaults than try
1568 * to be smart ...
1569 */
1570 if (fdisk_script_get_header(dp, "first-lba")) {
1571 fdisk_script_set_header(dp, "first-lba", NULL);
1572 fdisk_info(dp->cxt, _("Ignore \"first-lba\" header due to sector size mismatch."));
1573 }
1574 if (fdisk_script_get_header(dp, "last-lba")) {
1575 fdisk_script_set_header(dp, "last-lba", NULL);
1576 fdisk_info(dp->cxt, _("Ignore \"last-lba\" header due to sector size mismatch."));
1577 }
1578 }
1579
1580 str = fdisk_script_get_header(dp, "grain");
1581 if (str) {
1582 uintmax_t sz;
1583
1584 rc = ul_parse_size(str, &sz, NULL);
1585 if (rc == 0)
1586 rc = fdisk_save_user_grain(cxt, sz);
1587 if (rc)
1588 return rc;
1589 }
1590
1591 if (fdisk_has_user_device_properties(cxt)) {
1592 rc = fdisk_apply_user_device_properties(cxt);
1593 if (rc)
1594 return rc;
1595 }
1596
1597
1598 /* create empty label */
1599 name = fdisk_script_get_header(dp, "label");
1600 if (!name)
1601 return -EINVAL;
1602
1603 rc = fdisk_create_disklabel(cxt, name);
1604 if (rc)
1605 return rc;
1606
1607 str = fdisk_script_get_header(dp, "table-length");
1608 if (str) {
1609 uintmax_t sz;
1610
1611 rc = ul_parse_size(str, &sz, NULL);
1612 if (rc == 0)
1613 rc = fdisk_gpt_set_npartitions(cxt, sz);
1614 }
1615
1616 return rc;
1617 }
1618
1619 /**
1620 * fdisk_apply_script:
1621 * @cxt: context
1622 * @dp: script
1623 *
1624 * This function creates a new disklabel and partition within context @cxt. You
1625 * have to call fdisk_write_disklabel() to apply changes to the device.
1626 *
1627 * Returns: 0 on error, <0 on error.
1628 */
1629 int fdisk_apply_script(struct fdisk_context *cxt, struct fdisk_script *dp)
1630 {
1631 int rc;
1632 struct fdisk_script *old;
1633
1634 assert(dp);
1635 assert(cxt);
1636
1637 DBG(CXT, ul_debugobj(cxt, "applying script %p", dp));
1638
1639 old = fdisk_get_script(cxt);
1640 fdisk_ref_script(old);
1641
1642 /* create empty disk label */
1643 rc = fdisk_apply_script_headers(cxt, dp);
1644
1645 /* create partitions */
1646 if (!rc && dp->table)
1647 rc = fdisk_apply_table(cxt, dp->table);
1648
1649 fdisk_set_script(cxt, old);
1650 fdisk_unref_script(old);
1651
1652 DBG(CXT, ul_debugobj(cxt, "script done [rc=%d]", rc));
1653 return rc;
1654 }
1655
1656 #ifdef FUZZ_TARGET
1657 # include "all-io.h"
1658
1659 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
1660 {
1661 char name[] = "/tmp/test-script-fuzz.XXXXXX";
1662 int fd;
1663 struct fdisk_script *dp;
1664 struct fdisk_context *cxt;
1665 FILE *f;
1666
1667 fd = mkstemp_cloexec(name);
1668 if (fd < 0)
1669 err(EXIT_FAILURE, "mkstemp() failed");
1670 if (write_all(fd, data, size) != 0)
1671 err(EXIT_FAILURE, "write() failed");
1672 f = fopen(name, "r");
1673 if (!f)
1674 err(EXIT_FAILURE, "cannot open %s", name);
1675
1676 cxt = fdisk_new_context();
1677 dp = fdisk_new_script(cxt);
1678
1679 fdisk_script_read_file(dp, f);
1680 fclose(f);
1681
1682 fdisk_script_write_file(dp, stdout);
1683 fdisk_unref_script(dp);
1684 fdisk_unref_context(cxt);
1685
1686 close(fd);
1687 unlink(name);
1688
1689 return 0;
1690 }
1691 #endif
1692
1693 #ifdef TEST_PROGRAM
1694 static int test_dump(struct fdisk_test *ts __attribute__((unused)),
1695 int argc, char *argv[])
1696 {
1697 if (argc != 2)
1698 return -1;
1699
1700 char *devname = argv[1];
1701 struct fdisk_context *cxt;
1702 struct fdisk_script *dp;
1703
1704 cxt = fdisk_new_context();
1705 fdisk_assign_device(cxt, devname, 1);
1706
1707 dp = fdisk_new_script(cxt);
1708 fdisk_script_read_context(dp, NULL);
1709
1710 fdisk_script_write_file(dp, stdout);
1711 fdisk_unref_script(dp);
1712 fdisk_unref_context(cxt);
1713
1714 return 0;
1715 }
1716
1717 static int test_read(struct fdisk_test *ts __attribute__((unused)),
1718 int argc, char *argv[])
1719 {
1720 if (argc != 2)
1721 return -1;
1722
1723 char *filename = argv[1];
1724 struct fdisk_script *dp;
1725 struct fdisk_context *cxt;
1726 FILE *f;
1727
1728 if (!(f = fopen(filename, "r")))
1729 err(EXIT_FAILURE, "%s: cannot open", filename);
1730
1731 cxt = fdisk_new_context();
1732 dp = fdisk_new_script(cxt);
1733
1734 fdisk_script_read_file(dp, f);
1735 fclose(f);
1736
1737 fdisk_script_write_file(dp, stdout);
1738 fdisk_unref_script(dp);
1739 fdisk_unref_context(cxt);
1740
1741 return 0;
1742 }
1743
1744 static int test_stdin(struct fdisk_test *ts __attribute__((unused)),
1745 int argc, char *argv[] __attribute__((unused)))
1746 {
1747 if (argc != 1)
1748 return -1;
1749
1750 char buf[BUFSIZ] = { '\0' };
1751 struct fdisk_script *dp;
1752 struct fdisk_context *cxt;
1753 int rc = 0;
1754
1755 cxt = fdisk_new_context();
1756 dp = fdisk_new_script(cxt);
1757 fdisk_script_set_header(dp, "label", "dos");
1758
1759 printf("<start>, <size>, <type>, <bootable: *|->\n");
1760 do {
1761 struct fdisk_partition *pa;
1762 size_t n = dp->table ? fdisk_table_get_nents(dp->table) : 0;
1763
1764 printf(" #%zu :\n", n + 1);
1765 rc = fdisk_script_read_line(dp, stdin, buf, sizeof(buf));
1766
1767 if (rc == 0) {
1768 pa = fdisk_table_get_partition(dp->table, n);
1769 printf(" #%zu %12ju %12ju\n", n + 1,
1770 (uintmax_t)fdisk_partition_get_start(pa),
1771 (uintmax_t)fdisk_partition_get_size(pa));
1772 }
1773 } while (rc == 0);
1774
1775 if (!rc)
1776 fdisk_script_write_file(dp, stdout);
1777 fdisk_unref_script(dp);
1778 fdisk_unref_context(cxt);
1779
1780 return rc;
1781 }
1782
1783 static int test_apply(struct fdisk_test *ts __attribute__((unused)),
1784 int argc, char *argv[])
1785 {
1786 if (argc != 3)
1787 return -1;
1788
1789 char *devname = argv[1], *scriptname = argv[2];
1790 struct fdisk_context *cxt;
1791 struct fdisk_script *dp;
1792 struct fdisk_table *tb = NULL;
1793 struct fdisk_iter *itr = NULL;
1794 struct fdisk_partition *pa = NULL;
1795 int rc;
1796
1797 cxt = fdisk_new_context();
1798 fdisk_assign_device(cxt, devname, 0);
1799
1800 dp = fdisk_new_script_from_file(cxt, scriptname);
1801 if (!dp)
1802 return -errno;
1803
1804 rc = fdisk_apply_script(cxt, dp);
1805 if (rc)
1806 goto done;
1807 fdisk_unref_script(dp);
1808
1809 /* list result */
1810 fdisk_list_disklabel(cxt);
1811 fdisk_get_partitions(cxt, &tb);
1812
1813 itr = fdisk_new_iter(FDISK_ITER_FORWARD);
1814 while (fdisk_table_next_partition(tb, itr, &pa) == 0) {
1815 printf(" #%zu %12ju %12ju\n", fdisk_partition_get_partno(pa),
1816 (uintmax_t)fdisk_partition_get_start(pa),
1817 (uintmax_t)fdisk_partition_get_size(pa));
1818 }
1819
1820 done:
1821 fdisk_free_iter(itr);
1822 fdisk_unref_table(tb);
1823
1824 /*fdisk_write_disklabel(cxt);*/
1825 fdisk_unref_context(cxt);
1826 return 0;
1827 }
1828
1829 static int test_tokens(struct fdisk_test *ts __attribute__((unused)),
1830 int argc, char *argv[])
1831 {
1832 if (argc != 2)
1833 return -1;
1834
1835 char *p, *str = argc == 2 ? strdup(argv[1]) : NULL;
1836 int i;
1837
1838 for (i = 1, p = str; p && *p; i++) {
1839 char *tk = next_token(&p);
1840
1841 if (!tk)
1842 break;
1843
1844 printf("#%d: '%s'\n", i, tk);
1845 }
1846
1847 free(str);
1848 return 0;
1849 }
1850
1851 int main(int argc, char *argv[])
1852 {
1853 struct fdisk_test tss[] = {
1854 { "--dump", test_dump, "<device> dump PT as script" },
1855 { "--read", test_read, "<file> read PT script from file" },
1856 { "--apply", test_apply, "<device> <file> try apply script from file to device" },
1857 { "--stdin", test_stdin, " read input like sfdisk" },
1858 { "--tokens", test_tokens, "<string> parse string" },
1859 { NULL }
1860 };
1861
1862 return fdisk_run_test(tss, argc, argv);
1863 }
1864
1865 #endif