Small code refactoring to avoid too many condition branches.
Always check the return value of pkg_new().

pkg_new() can fail when malloc(3) fails (ENOMEM) and we should always
ensure that the call was successfull and act acordingly on error.
Fix a bad calloc(3) call (discovered by scan-build)
Codepath refactoring.

testing against -1 is more "intuitive" as most libc function will return
-1 on error. When possible we should avoid having error handling
codepath in the function body and prefer enclosing it in block like
this:

if (error) {
    /* error handling */
}