/*
* File Name: common.c
* Author: Jade Cheng
* Date: March 29, 2009
* Course: ICS 451
* Assignment: Project 2
*/
#include "common.h"
/* ------------------------------------------------------------------------ */
extern void fprint_buffer(FILE * f, const void * input, size_t len)
{
int i;
const u_char * ptr;
ptr = input;
/* First print the buffer as hex values. */
fprintf(f, " { ");
for (i = 0; i < len; i++)
fprintf(f, "%02x ", ptr[i]);
fprintf(f, "}\n");
/* Next print the buffer as ASCII values, if possible. */
fprintf(f, " { ");
for (i = 0; i < len; i++)
fprintf(f, " %c ", ((ptr[i] >= 32 && ptr[i] <= 127) ? ptr[i] : '?'));
fprintf(f, "}\n");
}
/* ------------------------------------------------------------------------ */
extern void fprint_peer(FILE * f, const peer_t * peer) {
char ip[16];
inet_ntop(AF_INET, &peer->addr, ip, sizeof(ip));
fprintf(f, "%s:%hu", ip, peer->port);
}
/* ------------------------------------------------------------------------ */
extern int peer_cmp(const peer_t * peer1, const peer_t * peer2)
{
int result;
assert(peer1 != NULL);
assert(peer2 != NULL);
if (0 != (result = (peer1->addr - peer2->addr)))
return result;
return peer1->port - peer2->port;
}
/* ------------------------------------------------------------------------ */
#ifdef DEBUG
extern int return_failure(
const char * file,
const size_t line,
const char * function,
const int info)
{
assert(file != NULL);
assert(function != NULL);
fprintf(stderr, "%s(%d): %s failed.", file, line, function);
/* errno is not always set. Don't print information if it isn't. */
if (info != 0)
fprintf(stderr, " (%d) %s", info, strerror(info));
fprintf(stderr, "\n");
return EXIT_FAILURE;
}
#endif /* DEBUG */
/* ------------------------------------------------------------------------ */
extern int verify_name(const char * name)
{
size_t dots;
size_t i;
size_t len;
assert(name != NULL);
/* Check the length is valid. */
len = strlen(name);
RETURN_IF_FALSE(len <= MAX_NAME_LENGTH);
RETURN_IF_FALSE(len > 0);
/* Check each character is valid. */
dots = 0;
for (i = 0; i < len; i++) {
RETURN_IF_FALSE(
islower((int)name[i])
|| isdigit((int)name[i])
|| name[i] == '_'
|| name[i] == '.');
/* Do not allow more than one dot. */
if (name[i] == '.' && ++dots == 2)
RETURN_FAILURE();
}
return EXIT_SUCCESS;
}