#include <stdio.h>
#include <curl/curl.h>
#include <sys/stat.h>
#include <fcntl.h>

size_t filecode;

/* Trailer header callback function */
struct curl_slist * trailerheader_callback(CURL *handle, void *userdata) {
  struct curl_slist *trailer_headers = NULL;
  int *code = (int *)userdata;
  
  if(!(*code))
    trailer_headers = curl_slist_append(trailer_headers, "mytrailer: EOF");
  else
    trailer_headers = curl_slist_append(trailer_headers, "mytrailer: error");

  return trailer_headers;
}

/* Read callback function */
size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream) {
  size_t retcode;
 
  retcode = fread(ptr, size, nmemb, stream);
  if(!retcode) {
    if(ferror(stream))
      filecode = 1;
    if(feof(stream))
      filecode = 0;
  }

  return retcode;
}

int main(void)
{
  CURL *curl;
  CURLcode res;
  FILE *fd;
  struct curl_slist *custom_http_hdrs = NULL;
 
  fd = fopen("video_0000", "rb");
  if(!fd)
    return 1;

  curl = curl_easy_init();
  if(curl) {

    curl_easy_setopt(curl, CURLOPT_URL, "http://10.8.6.65/myfile");

    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
    curl_easy_setopt(curl, CURLOPT_READDATA, fd);
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
 
    custom_http_hdrs = curl_slist_append(custom_http_hdrs, 
                                         "Transfer-Encoding: chunked");
    custom_http_hdrs = curl_slist_append(custom_http_hdrs, 
                                         "Trailer: mytrailer");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, custom_http_hdrs);

    curl_easy_setopt(curl, CURLOPT_TRAILERFUNCTION, trailerheader_callback);
    curl_easy_setopt(curl, CURLOPT_TRAILERDATA, &filecode);
 
    res = curl_easy_perform(curl);
    if(res != CURLE_OK) {
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
                                                   curl_easy_strerror(res));
    }

    curl_slist_free_all(custom_http_hdrs);
    curl_easy_cleanup(curl);
  }
  fclose(fd);

  return 0;
}
