+int sd_lldp_save(sd_lldp *lldp, const char *lldp_file) {
+ _cleanup_free_ char *temp_path = NULL;
+ _cleanup_fclose_ FILE *f = NULL;
+ uint8_t *mac, *port_id, type;
+ lldp_neighbour_port *p;
+ uint16_t data = 0, length = 0;
+ char buf[LINE_MAX];
+ lldp_chassis *c;
+ usec_t time;
+ Iterator i;
+ int r;
+
+ assert(lldp);
+ assert(lldp_file);
+
+ r = fopen_temporary(lldp_file, &f, &temp_path);
+ if (r < 0)
+ goto finish;
+
+ fchmod(fileno(f), 0644);
+
+ HASHMAP_FOREACH(c, lldp->neighbour_mib, i) {
+ LIST_FOREACH(port, p, c->ports) {
+ _cleanup_free_ char *s = NULL;
+ char *k, *t;
+
+ r = lldp_read_chassis_id(p->packet, &type, &length, &mac);
+ if (r < 0)
+ continue;
+
+ sprintf(buf, "'_Chassis=%02x:%02x:%02x:%02x:%02x:%02x' '_CType=%d' ",
+ mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], type);
+
+ s = strdup(buf);
+ if (!s)
+ return -ENOMEM;
+
+ r = lldp_read_port_id(p->packet, &type, &length, &port_id);
+ if (r < 0)
+ continue;
+
+ if (type != LLDP_PORT_SUBTYPE_MAC_ADDRESS) {
+ k = strndup((char *) port_id, length -1);
+ if (!k)
+ return -ENOMEM;
+
+ sprintf(buf, "'_Port=%s' '_PType=%d' ", k , type);
+ free(k);
+ } else {
+ mac = port_id;
+ sprintf(buf, "'_Port=%02x:%02x:%02x:%02x:%02x:%02x' '_PType=%d' ",
+ mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], type);
+ }
+
+ k = strappend(s, buf);
+ if (!k)
+ return -ENOMEM;
+
+ free(s);
+ s = k;
+
+ time = now(CLOCK_BOOTTIME);
+
+ /* Don't write expired packets */
+ if (time - p->until <= 0)
+ continue;
+
+ sprintf(buf, "'_TTL="USEC_FMT"' ", p->until);
+
+ k = strappend(s, buf);
+ if (!k)
+ return -ENOMEM;
+
+ free(s);
+ s = k;
+
+ r = lldp_read_system_name(p->packet, &length, &k);
+ if (r < 0)
+ k = strappend(s, "'_NAME=N/A' ");
+ else {
+ t = strndup(k, length);
+ if (!t)
+ return -ENOMEM;
+
+ k = strjoin(s, "'_NAME=", t, "' ", NULL);
+ free(t);
+ }
+
+ if (!k)
+ return -ENOMEM;
+
+ free(s);
+ s = k;
+
+ (void)lldp_read_system_capability(p->packet, &data);
+
+ sprintf(buf, "'_CAP=%x'", data);
+
+ k = strappend(s, buf);
+ if (!k)
+ return -ENOMEM;
+
+ free(s);
+ s = k;
+
+ fprintf(f, "%s\n", s);
+ }
+ }
+ r = 0;
+
+ fflush(f);
+
+ if (ferror(f) || rename(temp_path, lldp_file) < 0) {
+ r = -errno;
+ unlink(lldp_file);
+ unlink(temp_path);
+ }
+
+ finish:
+ if (r < 0)
+ log_error("Failed to save lldp data %s: %s", lldp_file, strerror(-r));
+
+ return r;
+}
+