- gchar *r, *c = g_strndup(s, e-s);
- r = g_strdup_printf("%s%i", c, atoi(e)+1);
- g_free(c);
- return r;
- } else
- return g_strdup_printf("%s #2", s);
+ char *c, *m;
+ size_t l;
+ int n;
+
+ n = atoi(e)+1;
+ if (!(m = avahi_strdup_printf("%i", n)))
+ return NULL;
+
+ l = e-s-2;
+
+ if (l >= AVAHI_LABEL_MAX-1-strlen(m)-2)
+ l = AVAHI_LABEL_MAX-1-strlen(m)-2;
+
+ if (!(c = avahi_strndup(s, l))) {
+ avahi_free(m);
+ return NULL;
+ }
+
+ drop_incomplete_utf8(c);
+
+ r = avahi_strdup_printf("%s #%s", c, m);
+ avahi_free(c);
+ avahi_free(m);
+ } else {
+ char *c;
+
+ if (!(c = avahi_strndup(s, AVAHI_LABEL_MAX-1-3)))
+ return NULL;
+
+ drop_incomplete_utf8(c);
+
+ r = avahi_strdup_printf("%s #2", c);
+ avahi_free(c);
+ }
+
+ assert(avahi_is_valid_service_name(r));
+
+ return r;