/*****************************************************************************
 *                                  _   _ ____  _     
 *  Project                     ___| | | |  _ \| |    
 *                             / __| | | | |_) | |    
 *                            | (__| |_| |  _ <| |___ 
 *                             \___|\___/|_| \_\_____|
 *
 * $Id: multithread.c,v 1.1 2001/05/04 09:35:43 bagder Exp $
 */

/* A multi-threaded example that uses pthreads extensively to fetch
 * X remote files at once */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <curl/curl.h>

/* silly list of test-URLs */
char *urls[]= {
  "https://www/","https://www/","https://www/","https://www/"};

void *pull_one_url(void *url)
{
  CURL *curl;
  int	response=-1;
  int status=-1;
  char	curl_error[ CURL_ERROR_SIZE ];
  FILE	*uit;

  uit= fopen( "nl:","w"); // Might be /dev/null on unix	

  curl = curl_easy_init();

  curl_easy_setopt(curl, CURLOPT_URL, url);
  curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_error );
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, uit);

/*
  curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");
  curl_easy_setopt(curl,CURLOPT_CAINFO, "ddd.pem");
 */

  /* not disconnect if we can't validate server's cert */
  curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER, (long) 0 );
  curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST, (long) 1 );


  status = curl_easy_perform(curl);

  curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &response);	

  if ( status ){
	  fprintf(stderr,"curl result = %d, HTTP response %d, error_buffer[%s]\n",status, response, curl_error );
  }else{
	  fprintf(stderr,"ok, %s\n",(char *)url);
  }

  curl_easy_cleanup(curl);

  fclose( uit );
  return NULL;
}


/* 
   int pthread_create(pthread_t *new_thread_ID,
   const pthread_attr_t *attr,
   void * (*start_func)(void *), void *arg);
*/

int main(int argc, char **argv)
{
  pthread_t tid[4];
  int i;
  int error;
  int sleep_time=0;

  if ( argc > 1 ) sleep_time=atoi( argv[1]);

  for(i=0; i< 4; i++) {

    /* if we put a sleep here, all goes ok, if not, we get a 27, SSL error cannot create context*/

    if( sleep_time )sleep( sleep_time );


    error = pthread_create(&tid[i],
                           NULL, /* default attributes please */
                           pull_one_url,
                           urls[i]);
    if(0 != error)
      fprintf(stderr, "Couldn't run thread number %d, errno %d\n", i, error);
    else 
      fprintf(stderr, "Thread %d, gets %s\n", i, urls[i]);
  }

  /* now wait for all threads to terminate */
  for(i=0; i< 4; i++) {
    error = pthread_join(tid[i], NULL);
    fprintf(stderr, "Thread %d terminated\n", i);
  }

  return 0;
}
