[TIP] XCode Header Search Path

September 26, 2009 | Filed Under Tips, XCode | 1 Comment

For many of you, this sounds like a stupid thing. But for those that just use gcc -I from command line, can be a pain find how to do it.

So, the problem is. How can I specify my Include path in XCode (gcc -I./mypath).

XCode Search Header Path

Tap on your project target, and click “Get Info“, tap on “Build” tab and search “Path” as showed in the figure above. Then click on the “Header Search Paths” options and add your favorite include paths for selected target.

[TIP] Generic Key Comparer

August 10, 2009 | Filed Under Tips | No Comments

I’m back to code on my “Cloud” FileSystem, and distributed tools. And here is a little tip.

When you’re working on Data, probably you store it as a Key-Value Pair on a BTree or something similar, and maybe this key is an aggregation of information… Maybe you’ve one bit of flag, N bytes of ParentKey, and others…

Now, the problem is… How can a “foreign” server sort correctly my keys? The solution is to send to the server the information on how to sort.. or a method to do it… but today, I’m focusing on the first one.

Generic Key

The code below show an implementation in Python of the Generic Key Comparer. At the end of the source code you can find an usage example. The Full Source Code is available here. Generic Key Comparer Source Code.

def __indexOfOne(data, tokens, offset):
   for i in xrange(offset, len(data)):
   if data[i] in tokens:
      return i
   return -1

def rawComparer(data1, data2, comparer):
   typeIds = [ 's', 'u', 'c', 'i', 'f', 'x' ]
   pyBinMap = {
      ('u', 1): 'B', ('u', 2): 'H', ('u', 4):'L', ('u', 8):'Q',
      ('i', 1): 'b', ('i', 2): 'h', ('i', 4):'l', ('i', 8):'q',
      ('f', 4): 'f', ('f', 8): 'd'
   }

   p = i = 0
   while i < len(comparer):
      nextIdx = __indexOfOne(comparer, typeIds, i + 1)
      if (nextIdx < 0): nextIdx = len(comparer)

      format = None
      length = 1 if (i + 1) == nextIdx else int(comparer[i+1:nextIdx])
      if comparer[i] == 's':
         format = str(length) + 's'
      elif comparer[i] == 'c':
         format = 'c'
      elif (comparer[i], length) in pyBinMap:
         format = pyBinMap[(comparer[i], length)]         

      if format != None:
         d1 = struct.unpack(format, data1[p:p+length])[0]
         d2 = struct.unpack(format, data2[p:p+length])[0]

         if d1 < d2:
            return -1
         elif d1 > d2:
            return 1         

      p += length
      i = nextIdx
   return 0

# Usage Example
if __name__ == '__main__':
  data1 = struct.pack('4sLch', 'test', 10, 'A', -3)
  data2 = struct.pack('4sLch', 'test', 10, 'A', -3)
  print 'Equal (test 10 A -3)', rawComparer(data1, data2, 's4u4ci2')

  data1 = struct.pack('4sLch', 'test', 10, 'A', 1)
  data2 = struct.pack('4sLch', 'test', 10, 'A', 0)
  print '(test 10 A 1) > (test 10 A 0)', rawComparer(data1, data2, 's4u4ci2')

  data1 = struct.pack('4sLch', 'test', 10, 'A', 0)
  data2 = struct.pack('4sLch', 'test', 10, 'A', 1)
  print '(test 10 A 0) < (test 10 A 1)', rawComparer(data1, data2, 's4u4ci2')

[TIP] Non Blocking C Read

May 11, 2009 | Filed Under Tips | No Comments

This is Just a simple code that maybe all the Linux C Developer knows, but if someone is still learning, This is a function that wrap the standard read function adding the non blocking feature. It’s Really useful in relation with Sockets.

int nonblock_read (int fd, char *buffer, size_t bufsize, int timeout) {
  if (timeout > 0) {
    struct timeval tv;
    fd_set rfds;

    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);

    tv.tv_sec = 0;
    tv.tv_usec = timeout * 1000;

    if (select(1, &rfds, NULL, NULL, &tv) <= 0)
      return(-ETIME);
  }

  return(read(fd, buffer, bufsize));
}

[TIP] Words Tokenization

April 24, 2009 | Filed Under Tips | No Comments

Sometimes is useful to split the input text in a list of words to Indexing or Searching data.
Here is how to extract words from a sentence in C.

char str[] = "Hi, I'm a test. (This is just a test). "
             "Join The #qt IRC Channel!"
             "GNU/Linux - theo@gmail.com";
char delims[] = " !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~";

char *result = NULL;
result = strtok(str, delims);
while(result != NULL) {
    printf("%s\n", result);
    result = strtok(NULL, delims);
}


…and this is the Qt way.

QString str = "Hi, I'm a test. (This is just a test). "
        "Join The #qt IRC Channel! GNU/Linux - theo@gmail.com";
QString delim = QRegExp::escape(" !\"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~");
QRegExp regexp(QString("[%1]").arg(delim),Qt::CaseSensitive,QRegExp::RegExp2);
qDebug() << str.split(regexp, QString::SkipEmptyParts);

OpenSSL: License Key with RSA

November 26, 2008 | Filed Under Tips | No Comments

In the last days I’ve played a bit with C libraries like OpenSSL and SQLite. The first post after Site downtime is dedicated to OpenSSL.
how do can you create your own license system for your application? With OpenSSL and less than 10 lines of code, you can do it. Take a look at the code below.

...
unsigned char checkDigest[SHA_DIGEST_LENGTH];
unsigned char shaDigest[SHA_DIGEST_LENGTH];
const char *userKey = "Matteo License";
unsigned char *signature = NULL;
unsigned int signatureLength = 0;

/* Generate Your RSA Key Pair */
RSA *rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);

/* Generate SHA1 of User Key */
SHA1(userKey, strlen(userKey), shaDigest);

/* Create License Key for the User Key */
signature = OPENSSL_malloc(RSA_size(rsa));
signatureLength = RSA_private_encrypt(SHA_DIGEST_LENGTH, shaDigest,
                                 signature, rsa, RSA_PKCS1_PADDING);

/* Check if User Signature is a valid License Key */
if (RSA_public_decrypt(signatureLength, signature, checkDigest,
                                rsa, RSA_PKCS1_PADDING) != SHA_DIGEST_LENGTH)
{
      /* Valid License Key */
} else {
      /* Invalid License Key */
}

free(signature);
RSA_free(rsa);
...

You need to store the RSA Public Key in your app and then give to each user a generated signature, and it’s all.
Ok, this is a really base example (less than 10 lines of code) if you don’t want reinvent a License Key system, take a look at AquaticPrime Framework (http://www.aquaticmac.com/).

[TIP] Test TCP Port with PHP

September 26, 2008 | Filed Under Tips | No Comments

I need to test if specified TCP Port on specified Host is opened or Not, and i need to do it from a Web Service… This is my Solution a simple “ping” method written in PHP.

function qPing ($host, $port, $timeout = 5) {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) return(1);

    if (!socket_set_nonblock($socket))
        return(2);

    $time = time();
    while (!@socket_connect($socket, $host, $port)) {
        $err = socket_last_error($socket);
        if ($err == 115 || $err == 114) {
            if ((time() - $time) >= $timeout) {
                socket_close($socket);
                return(3);    # Connection timed out.
            }
            usleep(500);
            continue;
        }
        echo $err . ' ' . socket_strerror($err) . "\n";
        return(4);
    }

    socket_close($socket);
    return(0);
}