A while back I asked this question.
I eventually hacked together a sort of solution:
int convertWindowsSIDToString(void *sidToConvert, int size, char* result) {
const char *sidStringPrefix = "S-";
int i;
int concatLength = 0;
/* For Linux I have SID defined in a seperate header */
SID *sid;
char revision[2], identifierAuthority[2];
if(sidToConvert == NULL) {
return 1;
}
sid = (SID *)sidToConvert;
snprintf(revision, 2, "%d", sid -> Revision);
snprintf(identifierAuthority, 2, "%d", sid -> IdentifierAuthority.Value[5]);
/* Push prefix in to result buffer */
strcpy (result,sidStringPrefix);
/* Add revision so now should be S-{revision} */
strcat(result, revision);
/* Append another - symbol */
strcat(result, "-");
/* Add the identifier authority */
strcat(result, identifierAuthority);
/* Sub Authorities are all stored as unsigned long so a little conversion is required */
for (i = 0; i < sid -> SubAuthorityCount; i++) {
if(concatLength > 0){
concatLength += snprintf(result + concatLength, size, "-%lu", sid -> SubAuthority[i]);
} else {
concatLength = snprintf(result, size, "%s-%lu", result, sid -> SubAuthority[i]);
}
}
return 0;
}
I'm a complete amateur at C. In the few test cases I have run, this works fine but I am worried about how I'm handling strings here.
Is there any better way to handle string concatenation in this type of scenario? Please note, I am kind of tied to C89 compatibility as I am trying to keep all code compiling on all platforms and am stuck with Visual Studio on Windows for now.
Also my apologies if this question is not the best format for Stack Overflow. I guess I'm asking more for a code review that a very specific question but not sure where else to go.
EDIT
Just wanted to add what I think is almost the final solution, based on suggestions here, before accepting an answer.
int convertWindowsSIDToString(SID *sidToConvert, int size, char* result) {
int i;
char* t;
if(sidToConvert == NULL) {
printf("Error: SID to convert is null.\n");
return 1;
}
if(size < 32) {
printf("Error: Buffer size must be at least 32.\n");
return 1;
}
t = result;
t+= snprintf(t, size, "S-%d-%d", sidToConvert->Revision, sidToConvert->IdentifierAuthority.Value[5]);
for (i = 0; i < sidToConvert -> SubAuthorityCount; i++) {
t += snprintf(t, size - strlen(result), "-%lu", sidToConvert -> SubAuthority[i]);
}
return 0;
}
I've got a lot of reading to do yet by the look of things. Got to admit, C is pretty fun though.