Example #1
1
static void
init_prng (void)
{
  char namebuf[256];
  const char *random_file;

  if (RAND_status ())
    /* The PRNG has been seeded; no further action is necessary. */
    return;

  /* Seed from a file specified by the user.  This will be the file
     specified with --random-file, $RANDFILE, if set, or ~/.rnd, if it
     exists.  */
  if (opt.random_file)
    random_file = opt.random_file;
  else
    {
      /* Get the random file name using RAND_file_name. */
      namebuf[0] = '\0';
      random_file = RAND_file_name (namebuf, sizeof (namebuf));
    }

  if (random_file && *random_file)
    /* Seed at most 16k (apparently arbitrary value borrowed from
       curl) from random file. */
    RAND_load_file (random_file, 16384);

  if (RAND_status ())
    return;

  /* Get random data from EGD if opt.egd_file was used.  */
  if (opt.egd_file && *opt.egd_file)
    RAND_egd (opt.egd_file);

  if (RAND_status ())
    return;

#ifdef WINDOWS
  /* Under Windows, we can try to seed the PRNG using screen content.
     This may or may not work, depending on whether we'll calling Wget
     interactively.  */

  RAND_screen ();
  if (RAND_status ())
    return;
#endif

#if 0 /* don't do this by default */
  {
    int maxrand = 500;

    /* Still not random enough, presumably because neither /dev/random
       nor EGD were available.  Try to seed OpenSSL's PRNG with libc
       PRNG.  This is cryptographically weak and defeats the purpose
       of using OpenSSL, which is why it is highly discouraged.  */

    logprintf (LOG_NOTQUIET, _("WARNING: using a weak random seed.\n"));

    while (RAND_status () == 0 && maxrand-- > 0)
      {
        unsigned char rnd = random_number (256);
        RAND_seed (&rnd, sizeof (rnd));
      }
  }
#endif
}
Example #2
0
static int run(struct rules_t *obj, struct JsonNode *arguments, char **ret, enum origin_t origin) {
	struct JsonNode *childs = json_first_child(arguments);
	struct devices_t *dev = NULL;
	struct devices_settings_t *opt = NULL;
	struct protocols_t *protocol = NULL;
	struct tm tm;
	char *p = *ret, *datetime = NULL, *interval = NULL, **array = NULL;
	int nrunits = (sizeof(units)/sizeof(units[0])), values[nrunits], error = 0;
	int l = 0, i = 0, type = -1, match = 0;

	memset(&values, 0, nrunits);

	if(childs == NULL) {
		logprintf(LOG_ERR, "DATE_ADD two parameters e.g. DATE_ADD(datetime, 1 DAY)");
		error = -1;
		goto close;
	}

	if(devices_get(childs->string_, &dev) == 0) {
		if(origin == RULE) {
			event_cache_device(obj, childs->string_);
		}
		protocol = dev->protocols;
		if(protocol->listener->devtype == DATETIME) {
			opt = dev->settings;
			while(opt) {
				if(strcmp(opt->name, "year") == 0) {
					tm.tm_year = opt->values->number_-1900;
				}
				if(strcmp(opt->name, "month") == 0) {
					tm.tm_mon = opt->values->number_-1;
				}
				if(strcmp(opt->name, "day") == 0) {
					tm.tm_mday = opt->values->number_;
				}
				if(strcmp(opt->name, "hour") == 0) {
					tm.tm_hour = opt->values->number_;
				}
				if(strcmp(opt->name, "minute") == 0) {
					tm.tm_min = opt->values->number_;
				}
				if(strcmp(opt->name, "second") == 0) {
					tm.tm_sec = opt->values->number_;
				}
				if(strcmp(opt->name, "weekday") == 0) {
					tm.tm_wday = opt->values->number_-1;
				}
				if(strcmp(opt->name, "dst") == 0) {
					tm.tm_isdst = opt->values->number_;
				}
				opt = opt->next;
			}
		} else {
			logprintf(LOG_ERR, "device \"%s\" is not a datetime protocol", childs->string_);
			error = -1;
			goto close;
		}
	} else {
		datetime = childs->string_;
	}

	childs = childs->next;
	if(childs == NULL) {
		logprintf(LOG_ERR, "DATE_ADD requires two parameters e.g. DATE_ADD(datetime, 1 DAY)");
		error = -1;
		goto close;
	}
	interval = childs->string_;

	if(childs->next != NULL) {
		if(dev == NULL) {
			logprintf(LOG_ERR, "DATE_ADD requires two parameters e.g. DATE_ADD(2000-01-01 12:00:00, 1 DAY)");
		} else {
			logprintf(LOG_ERR, "DATE_ADD requires two parameters e.g. DATE_ADD(datetime, 1 DAY)");
		}
		error = -1;
		goto close;
	}

	l = explode(interval, " ", &array);
	if(l == 2) {
		if(isNumeric(array[0]) == 0) {
			for(i=0;i<nrunits;i++) {
				if(strcmp(array[1], units[i].name) == 0) {
					values[i] = atoi(array[0]);
					type = units[i].id;
					match = 1;
					break;
				}
			}
		} else {
			logprintf(LOG_ERR, "The DATE_ADD unit parameter requires a number and a unit e.g. \"1 DAY\" instead of \"%%Y-%%m-%%d %%H:%%M:%%S\"");
			error = -1;
			goto close;
		}
	} else {
		logprintf(LOG_ERR, "The DATE_ADD unit parameter is formatted as e.g. \"1 DAY\" instead of \"%%Y-%%m-%%d %%H:%%M:%%S\"");
		error = -1;
		goto close;
	}
	if(match == 0) {
		logprintf(LOG_ERR, "DATE_ADD does not accept \"%s\" as a unit", array[1]);
		error = -1;
		goto close;
	}
	if(dev == NULL) {
		if(strptime(datetime, "%Y-%m-%d %H:%M:%S", &tm) == NULL) {
			logprintf(LOG_ERR, "DATE_ADD requires the datetime parameter to be formatted as \"%%Y-%%m-%%d %%H:%%M:%%S\"");
			error = -1;
			goto close;
		}
	}
	add(&tm, values, type);

	int year = tm.tm_year+1900;
	int month = tm.tm_mon+1;
	int day = tm.tm_mday;
	int hour = tm.tm_hour;
	int minute = tm.tm_min;
	int second = tm.tm_sec;

	datefix(&year, &month, &day, &hour, &minute, &second);

	snprintf(p, BUFFER_SIZE, "\"%04d-%02d-%02d %02d:%02d:%02d\"", year, month, day, hour, minute, second);

close:
	array_free(&array, l);
	return error;
}
Example #3
0
static void
write_backup_file (const char *file, downloaded_file_t downloaded_file_return)
{
  /* Rather than just writing over the original .html file with the
     converted version, save the former to *.orig.  Note we only do
     this for files we've _successfully_ downloaded, so we don't
     clobber .orig files sitting around from previous invocations.
     On VMS, use "_orig" instead of ".orig".  See "wget.h". */

  /* Construct the backup filename as the original name plus ".orig". */
  size_t         filename_len = strlen (file);
  char*          filename_plus_orig_suffix;

  /* TODO: hack this to work with css files */
  if (downloaded_file_return == FILE_DOWNLOADED_AND_HTML_EXTENSION_ADDED)
    {
      /* Just write "orig" over "html".  We need to do it this way
         because when we're checking to see if we've downloaded the
         file before (to see if we can skip downloading it), we don't
         know if it's a text/html file.  Therefore we don't know yet
         at that stage that -E is going to cause us to tack on
         ".html", so we need to compare vs. the original URL plus
         ".orig", not the original URL plus ".html.orig". */
      filename_plus_orig_suffix = alloca (filename_len + 1);
      strcpy (filename_plus_orig_suffix, file);
      strcpy ((filename_plus_orig_suffix + filename_len) - 4, "orig");
    }
  else /* downloaded_file_return == FILE_DOWNLOADED_NORMALLY */
    {
      /* Append ".orig" to the name. */
      filename_plus_orig_suffix = alloca (filename_len + sizeof (ORIG_SFX));
      strcpy (filename_plus_orig_suffix, file);
      strcpy (filename_plus_orig_suffix + filename_len, ORIG_SFX);
    }

  if (!converted_files)
    converted_files = make_string_hash_table (0);

  /* We can get called twice on the same URL thanks to the
     convert_all_links() call in main().  If we write the .orig file
     each time in such a case, it'll end up containing the first-pass
     conversion, not the original file.  So, see if we've already been
     called on this file. */
  if (!string_set_contains (converted_files, file))
    {
      /* Rename <file> to <file>.orig before former gets written over. */
      if (rename (file, filename_plus_orig_suffix) != 0)
        logprintf (LOG_NOTQUIET, _("Cannot back up %s as %s: %s\n"),
                   file, filename_plus_orig_suffix, strerror (errno));

      /* Remember that we've already written a .orig backup for this file.
         Note that we never free this memory since we need it till the
         convert_all_links() call, which is one of the last things the
         program does before terminating.  BTW, I'm not sure if it would be
         safe to just set 'converted_file_ptr->string' to 'file' below,
         rather than making a copy of the string...  Another note is that I
         thought I could just add a field to the urlpos structure saying
         that we'd written a .orig file for this URL, but that didn't work,
         so I had to make this separate list.
         -- Dan Harkless <*****@*****.**>

         This [adding a field to the urlpos structure] didn't work
         because convert_file() is called from convert_all_links at
         the end of the retrieval with a freshly built new urlpos
         list.
         -- Hrvoje Niksic <*****@*****.**>
      */
      string_set_add (converted_files, file);
    }
}
Example #4
0
void CRcon::Packet_DisconnectionNotification(Packet* pPacket)
{
	in_addr in;
	in.s_addr = pPacket->playerId.binaryAddress;
	logprintf("[RCON] Admin [%s] has disconnected.", inet_ntoa(in));
}
Example #5
0
void *socket_wait(void *param) {
	struct socket_callback_t *socket_callback = (struct socket_callback_t *)param;

	int activity;
	int i, n, sd;
    int max_sd;
    struct sockaddr_in address;
	int addrlen = sizeof(address);
	fd_set readfds;
	readBuff = malloc(BIG_BUFFER_SIZE);

	while(socket_loop) {
		do {
			//clear the socket set
			FD_ZERO(&readfds);

			//add master socket to set
			FD_SET((long unsigned int)serverSocket, &readfds);
			max_sd = serverSocket;

			//add child sockets to set
			for(i=0;i<MAX_CLIENTS;i++) {
				//socket descriptor
				sd = socket_clients[i];

				//if valid socket descriptor then add to read list
				if(sd > 0)
					FD_SET((long unsigned int)sd, &readfds);

				//highest file descriptor number, need it for the select function
				if(sd > max_sd)
					max_sd = sd;
			}
			//wait for an activity on one of the sockets, timeout is NULL, so wait indefinitely
			activity = select(max_sd + 1, &readfds, NULL, NULL, NULL);
		} while(activity == -1 && errno == EINTR && socket_loop);

        //If something happened on the master socket, then its an incoming connection
        if(FD_ISSET((long unsigned int)serverSocket, &readfds)) {
            if((clientSocket = accept(serverSocket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
                logprintf(LOG_ERR, "failed to accept client");
                exit(EXIT_FAILURE);
            }
			//inform user of socket number - used in send and receive commands
			logprintf(LOG_INFO, "new client, ip: %s, port: %d", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
			logprintf(LOG_DEBUG, "client fd: %d", clientSocket);
			//send new connection accept message
			//socket_write(clientSocket, "{\"message\":\"accept connection\"}");

			//add new socket to array of sockets
			for(i=0;i<MAX_CLIENTS;i++) {
				//if position is empty
				if(socket_clients[i] == 0) {
					socket_clients[i] = clientSocket;
					if(socket_callback->client_connected_callback)
						socket_callback->client_connected_callback(i);
					logprintf(LOG_DEBUG, "client id: %d", i);
					break;
				}
			}
        }

        //else its some IO operation on some other socket :)
        for(i=0;i<MAX_CLIENTS;i++) {
			sd = socket_clients[i];

            if(FD_ISSET((long unsigned int)sd , &readfds)) {
                //Check if it was for closing, and also read the incoming message
				memset(readBuff, '\0', BUFFER_SIZE);

                if((n = (int)read(sd, readBuff, BUFFER_SIZE-1)) == 0) {
                    //Somebody disconnected, get his details and print
                    getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
					logprintf(LOG_INFO, "client disconnected, ip %s, port %d", inet_ntoa(address.sin_addr), ntohs(address.sin_port));
					if(socket_callback->client_disconnected_callback)
						socket_callback->client_disconnected_callback(i);
					//Close the socket and mark as 0 in list for reuse
					close(sd);
					socket_clients[i] = 0;
                } else {
                    //set the string terminating NULL byte on the end of the data read
                    //readBuff[n] = '\0';

					if(n > -1 && socket_callback->client_data_callback) {
						char *pch = strtok(readBuff, "\n");
						while(pch) {
							socket_callback->client_data_callback(i, pch);
							pch = strtok(NULL, "\n");
						}
						sfree((void *)&pch);
					}
                }
            }
        }
    }
	return NULL;
}
Example #6
0
char *config_get_file(void) {
    logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

    return configfile;
}
Example #7
0
uerr_t
retrieve_from_file (const char *file, bool html, int *count)
{
  uerr_t status;
  struct urlpos *url_list, *cur_url;
  struct iri *iri = iri_new();

  char *input_file, *url_file = NULL;
  const char *url = file;

  status = RETROK;             /* Suppose everything is OK.  */
  *count = 0;                  /* Reset the URL count.  */

  /* sXXXav : Assume filename and links in the file are in the locale */
  set_uri_encoding (iri, opt.locale, true);
  set_content_encoding (iri, opt.locale);

  if (url_valid_scheme (url))
    {
      int dt,url_err;
      uerr_t status;
      struct url *url_parsed = url_parse (url, &url_err, iri, true);
      if (!url_parsed)
        {
          char *error = url_error (url, url_err);
          logprintf (LOG_NOTQUIET, "%s: %s.\n", url, error);
          xfree (error);
          return URLERROR;
        }

      if (!opt.base_href)
        opt.base_href = xstrdup (url);

      status = retrieve_url (url_parsed, url, &url_file, NULL, NULL, &dt,
                             false, iri, true);
      url_free (url_parsed);

      if (!url_file || (status != RETROK))
        return status;

      if (dt & TEXTHTML)
        html = true;

      /* If we have a found a content encoding, use it.
       * ( == is okay, because we're checking for identical object) */
      if (iri->content_encoding != opt.locale)
	  set_uri_encoding (iri, iri->content_encoding, false);

      /* Reset UTF-8 encode status */
      iri->utf8_encode = opt.enable_iri;
      xfree_null (iri->orig_url);
      iri->orig_url = NULL;

      input_file = url_file;
    }
  else
    input_file = (char *) file;

  url_list = (html ? get_urls_html (input_file, NULL, NULL, iri)
              : get_urls_file (input_file));

  xfree_null (url_file);

  for (cur_url = url_list; cur_url; cur_url = cur_url->next, ++*count)
    {
      char *filename = NULL, *new_file = NULL;
      int dt;
      struct iri *tmpiri = iri_dup (iri);
      struct url *parsed_url = NULL;

      if (cur_url->ignore_when_downloading)
        continue;

      if (opt.quota && total_downloaded_bytes > opt.quota)
        {
          status = QUOTEXC;
          break;
        }

      parsed_url = url_parse (cur_url->url->url, NULL, tmpiri, true);

      if ((opt.recursive || opt.page_requisites)
          && (cur_url->url->scheme != SCHEME_FTP || getproxy (cur_url->url)))
        {
          int old_follow_ftp = opt.follow_ftp;

          /* Turn opt.follow_ftp on in case of recursive FTP retrieval */
          if (cur_url->url->scheme == SCHEME_FTP)
            opt.follow_ftp = 1;

          status = retrieve_tree (parsed_url ? parsed_url : cur_url->url,
                                  tmpiri);

          opt.follow_ftp = old_follow_ftp;
        }
      else
        status = retrieve_url (parsed_url ? parsed_url : cur_url->url,
                               cur_url->url->url, &filename,
                               &new_file, NULL, &dt, opt.recursive, tmpiri,
                               true);

      if (parsed_url)
          url_free (parsed_url);

      if (filename && opt.delete_after && file_exists_p (filename))
        {
          DEBUGP (("\
Removing file due to --delete-after in retrieve_from_file():\n"));
          logprintf (LOG_VERBOSE, _("Removing %s.\n"), filename);
          if (unlink (filename))
            logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
          dt &= ~RETROKF;
        }

      xfree_null (new_file);
      xfree_null (filename);
      iri_free (tmpiri);
    }
/*------------------------------------------------------------------*/
void relation_batch_init(msieve_obj *obj, relation_batch_t *rb,
			uint32 min_prime, uint32 max_prime,
			uint32 lp_cutoff_r, uint32 lp_cutoff_a, 
			savefile_t *savefile,
			print_relation_t print_relation) {

	prime_sieve_t sieve;
	uint32 num_primes, p;

	/* count the number of primes to multiply. Knowing this
	   in advance makes the recursion a lot easier, at the cost
	   of a small penalty in runtime */

	init_prime_sieve(&sieve, min_prime + 1, max_prime);
	p = min_prime;
	num_primes = 0;
	while (p < max_prime) {
		p = get_next_prime(&sieve);
		num_primes++;
	}
	free_prime_sieve(&sieve);

	/* compute the product of primes */

	logprintf(obj, "multiplying %u primes from %u to %u\n",
			num_primes, min_prime, max_prime);

	init_prime_sieve(&sieve, min_prime, max_prime);
	mpz_init(rb->prime_product);
	multiply_primes(0, num_primes - 2, &sieve, rb->prime_product);
	logprintf(obj, "multiply complete, product has %u bits\n", 
				(uint32)mpz_sizeinbase(rb->prime_product, 2));
					
	rb->savefile = savefile;
	rb->print_relation = print_relation;

	/* compute the cutoffs used by the recursion base-case. Large
	   primes have a maximum size specified as input arguments, 
	   but numbers that can be passed to the SQUFOF routine are
	   limited to size 2^62 */

	rb->lp_cutoff_r = lp_cutoff_r;
	lp_cutoff_r = MIN(lp_cutoff_r, 0x7fffffff);
	mp_clear(&rb->lp_cutoff_r2);
	rb->lp_cutoff_r2.nwords = 1;
	rb->lp_cutoff_r2.val[0] = lp_cutoff_r;
	mp_mul_1(&rb->lp_cutoff_r2, lp_cutoff_r, &rb->lp_cutoff_r2);

	rb->lp_cutoff_a = lp_cutoff_a;
	lp_cutoff_a = MIN(lp_cutoff_a, 0x7fffffff);
	mp_clear(&rb->lp_cutoff_a2);
	rb->lp_cutoff_a2.nwords = 1;
	rb->lp_cutoff_a2.val[0] = lp_cutoff_a;
	mp_mul_1(&rb->lp_cutoff_a2, lp_cutoff_a, &rb->lp_cutoff_a2);

	mp_clear(&rb->max_prime2);
	rb->max_prime2.nwords = 1;
	rb->max_prime2.val[0] = max_prime;
	mp_mul_1(&rb->max_prime2, max_prime, &rb->max_prime2);

	/* allocate lists for relations and their factors */

	rb->target_relations = 500000;
	rb->num_relations = 0;
	rb->num_relations_alloc = 1000;
	rb->relations = (cofactor_t *)xmalloc(rb->num_relations_alloc *
						sizeof(cofactor_t));

	rb->num_factors = 0;
	rb->num_factors_alloc = 10000;
	rb->factors = (uint32 *)xmalloc(rb->num_factors_alloc *
						sizeof(uint32));
}
Example #9
0
int main(int argc, char **argv) {
  axutil_env_t * env = NULL;
  axis2_char_t * client_home = NULL;
  axis2_char_t endpoint_uri[256], *tmpstr;
  axis2_stub_t * stub = NULL;
  int rc, i, port, use_wssec;
  char *euca_home, configFile[1024], policyFile[1024];
  
  if (MODE == 0) {
    if (argc != 2 || strcmp(argv[1], "-9")) {
      printf("only runnable from inside euca\n");
      exit(1);
    }
  } else {
    if (argc < 3) {
      printf("USAGE: CCclient <host:port> <command> <opts>\n");
      exit(1);
    }
  }
  
  euca_home = getenv("EUCALYPTUS");
  if (!euca_home) {
    snprintf(configFile, 1024, "/etc/eucalyptus/eucalyptus.conf");
    snprintf(policyFile, 1024, "/var/lib/eucalyptus/keys/cc-client-policy.xml");
  } else {
    snprintf(configFile, 1024, "%s/etc/eucalyptus/eucalyptus.conf", euca_home);
    snprintf(policyFile, 1024, "%s/var/lib/eucalyptus/keys/cc-client-policy.xml", euca_home);
  }

  rc = get_conf_var(configFile, "CC_PORT", &tmpstr);
  if (rc != 1) {
    // error
    logprintf("ERROR: parsing config file (%s) for CC_PORT\n",configFile);
    exit(1);
  } else {
    port = atoi(tmpstr);
  }

  rc = get_conf_var(configFile, "ENABLE_WS_SECURITY", &tmpstr);
  if (rc != 1) {
    // error
    logprintf("ERROR: parsing config file (%s) for ENABLE_WS_SECURITY\n",configFile);
    exit(1);
  } else {
    if (!strcmp(tmpstr, "Y")) {
      use_wssec = 1;
    } else {
      use_wssec = 0;
    }
  }
  
  if (MODE == 0) {
    snprintf(endpoint_uri, 256," http://localhost:%d/axis2/services/EucalyptusCC", port);
  } else {
    snprintf(endpoint_uri, 256," http://%s/axis2/services/EucalyptusCC", argv[1]);
  }
  //env =  axutil_env_create_all(NULL, 0);
  env =  axutil_env_create_all("/tmp/fofo", AXIS2_LOG_LEVEL_TRACE);
  
  client_home = AXIS2_GETENV("AXIS2C_HOME");
  if (!client_home) {
    printf("must have AXIS2C_HOME set\n");
    exit(1);
  }
  stub = axis2_stub_create_EucalyptusCC(env, client_home, endpoint_uri);
  
  if (use_wssec) {
    rc = InitWSSEC(env, stub, policyFile);
    if (rc) {
      printf("cannot initialize WS-SEC policy (%s)\n",policyFile);
      exit(1);
    } 
  }
  
  if (MODE == 0) {
    rc = cc_killallInstances(env, stub);
    if (rc != 0) {
      printf("cc_killallInstances() failed\n");
      exit(1);
    }
  } else {
    /*
    if (!strcmp(argv[2], "registerImage")) {
      rc = cc_registerImage(argv[3], env, stub);
      if (rc != 0) {
	printf("cc_registerImage() failed: in:%s out:%d\n", argv[3], rc);
	exit(1);
      }
    */
    if (!strcmp(argv[2], "runInstances")) {
      char *amiId=NULL, *amiURL=NULL, *kernelId=NULL, *kernelURL=NULL, *ramdiskId=NULL, *ramdiskURL=NULL;
      if (argv[3]) amiId = argv[3];
      if (argv[4]) amiURL = argv[4];
      if (argv[5]) kernelId = argv[5];
      if (argv[6]) kernelURL = argv[6];
      if (argv[10]) ramdiskId = argv[10];
      if (argv[11]) ramdiskURL = argv[11];

      virtualMachine params = { 64, 1, 64, "m1.small", 
				{ { "sda1", "root", 100, "none" }, 
				  { "sda2", "ephemeral1", 1000, "ext3" },
				  { "sda3", "swap", 50, "swap" } } };

      rc = cc_runInstances(amiId, amiURL, kernelId, kernelURL, ramdiskId, ramdiskURL, atoi(argv[7]), atoi(argv[8]), argv[9], &params, env, stub);
      if (rc != 0) {
	printf("cc_runInstances() failed: in:%s out:%d\n", argv[4], rc);
	exit(1);
      }
    } else if (!strcmp(argv[2], "describeInstances")) {
      rc = cc_describeInstances(NULL, 0, env, stub);
      if (rc != 0) {
	printf("cc_describeInstances() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "getConsoleOutput")) {
      rc = cc_getConsoleOutput(argv[3], env, stub);
      if (rc != 0) {
	printf("cc_getConsoleOutput() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "rebootInstances")) {
      char *instIds[256];
      if (argv[3] != NULL) {
	instIds[0] = strdup(argv[3]);
      }
      rc = cc_rebootInstances(instIds, 1, env, stub);
      if (rc != 0) {
	printf("cc_rebootInstances() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "terminateInstances")) {
      char *instIds[256];
      i=3;
      while (argv[i] != NULL) {
	instIds[i-3] = strdup(argv[i]);
	i++;
      }
      if ( (i-3) > 0) {
	rc = cc_terminateInstances(instIds, i-3, env, stub);
	if (rc != 0) {
	  printf("cc_terminateInstances() failed\n");
	  exit(1);
	}
      }
    } else if (!strcmp(argv[2], "describeResources")) {
      rc = cc_describeResources(env, stub);
      if (rc != 0) {
	printf("cc_describeResources() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "startNetwork")) {
      char **ccs;
      int ccsLen=0, i;
      ccs = malloc(sizeof(char *) * 32);
      for (i=0; i<32; i++) {
	if (argv[i+5]) {
	  ccs[i] = strdup(argv[i+5]);
	  ccsLen++;
	} else {
	  i=33;
	}
      }
      rc = cc_startNetwork(atoi(argv[3]), argv[4], ccs, ccsLen, env, stub);
      if (rc != 0) {
	printf("cc_startNetwork() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "describeNetworks")) {
      char **ccs, *nameserver;
      int ccsLen=0, i;
      ccs = malloc(sizeof(char *) * 32);
      for (i=0; i<32; i++) {
	if (argv[i+3]) {
	  ccs[i] = strdup(argv[i+3]);
	  ccsLen++;
	} else {
	  i=33;
	}
      }
      nameserver = strdup("1.2.3.4");

      rc = cc_describeNetworks(nameserver, ccs, ccsLen, env, stub);
      if (rc != 0) {
	printf("cc_describeNetworks() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "configureNetwork")) {
      rc = cc_configureNetwork(argv[3], argv[4], argv[5], atoi(argv[6]), atoi(argv[7]), argv[8], env, stub);
      if (rc != 0) {
	printf("cc_configureNetwork() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "stopNetwork")) {
      rc = cc_stopNetwork(atoi(argv[3]), argv[4], env, stub);
      if (rc != 0) {
	printf("cc_stopNetwork() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "assignAddress")) {
      rc = cc_assignAddress(argv[3], argv[4], env, stub);
      if (rc != 0) {
	printf("cc_assignNetwork() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "unassignAddress")) {
      rc = cc_unassignAddress(argv[3], argv[4], env, stub);
      if (rc != 0) {
	printf("cc_unassignNetwork() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "attachVolume")) {
      rc = cc_attachVolume(argv[3], argv[4], argv[5], argv[6], env, stub);
      if (rc != 0) {
	printf("cc_attachVolume() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "detachVolume")) {
      rc = cc_detachVolume(argv[3], argv[4], argv[5], argv[6], atoi(argv[7]), env, stub);
      if (rc != 0) {
	printf("cc_unassignNetwork() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "describePublicAddresses")) {
      rc = cc_describePublicAddresses(env, stub);
      if (rc != 0) {
	printf("cc_describePublicAddresses() failed\n");
	exit(1);
      }
    } else if (!strcmp(argv[2], "killallInstances")) {
      rc = cc_killallInstances(env, stub);
      if (rc != 0) {
	printf("cc_killallInstances() failed\n");
	exit(1);
      }
    }
  }
  
  exit(0);
}
Example #10
0
uerr_t
retrieve_url (struct url * orig_parsed, const char *origurl, char **file,
              char **newloc, const char *refurl, int *dt, bool recursive,
              struct iri *iri, bool register_status)
{
  uerr_t result;
  char *url;
  bool location_changed;
  bool iri_fallbacked = 0;
  int dummy;
  char *mynewloc, *proxy;
  struct url *u = orig_parsed, *proxy_url;
  int up_error_code;            /* url parse error code */
  char *local_file;
  int redirection_count = 0;

  bool post_data_suspended = false;
  char *saved_post_data = NULL;
  char *saved_post_file_name = NULL;

  /* If dt is NULL, use local storage.  */
  if (!dt)
    {
      dt = &dummy;
      dummy = 0;
    }
  url = xstrdup (origurl);
  if (newloc)
    *newloc = NULL;
  if (file)
    *file = NULL;

  if (!refurl)
    refurl = opt.referer;

 redirected:
  /* (also for IRI fallbacking) */

  result = NOCONERROR;
  mynewloc = NULL;
  local_file = NULL;
  proxy_url = NULL;

  proxy = getproxy (u);
  if (proxy)
    {
      struct iri *pi = iri_new ();
      set_uri_encoding (pi, opt.locale, true);
      pi->utf8_encode = false;

      /* Parse the proxy URL.  */
      proxy_url = url_parse (proxy, &up_error_code, NULL, true);
      if (!proxy_url)
        {
          char *error = url_error (proxy, up_error_code);
          logprintf (LOG_NOTQUIET, _("Error parsing proxy URL %s: %s.\n"),
                     proxy, error);
          xfree (url);
          xfree (error);
          RESTORE_POST_DATA;
          result = PROXERR;
          goto bail;
        }
      if (proxy_url->scheme != SCHEME_HTTP && proxy_url->scheme != u->scheme)
        {
          logprintf (LOG_NOTQUIET, _("Error in proxy URL %s: Must be HTTP.\n"), proxy);
          url_free (proxy_url);
          xfree (url);
          RESTORE_POST_DATA;
          result = PROXERR;
          goto bail;
        }
    }

  if (u->scheme == SCHEME_HTTP
#ifdef HAVE_SSL
      || u->scheme == SCHEME_HTTPS
#endif
      || (proxy_url && proxy_url->scheme == SCHEME_HTTP))
    {
      result = http_loop (u, orig_parsed, &mynewloc, &local_file, refurl, dt,
                          proxy_url, iri);
    }
  else if (u->scheme == SCHEME_FTP)
    {
      /* If this is a redirection, temporarily turn off opt.ftp_glob
         and opt.recursive, both being undesirable when following
         redirects.  */
      bool oldrec = recursive, glob = opt.ftp_glob;
      if (redirection_count)
        oldrec = glob = false;

      result = ftp_loop (u, &local_file, dt, proxy_url, recursive, glob);
      recursive = oldrec;

      /* There is a possibility of having HTTP being redirected to
         FTP.  In these cases we must decide whether the text is HTML
         according to the suffix.  The HTML suffixes are `.html',
         `.htm' and a few others, case-insensitive.  */
      if (redirection_count && local_file && u->scheme == SCHEME_FTP)
        {
          if (has_html_suffix_p (local_file))
            *dt |= TEXTHTML;
        }
    }

  if (proxy_url)
    {
      url_free (proxy_url);
      proxy_url = NULL;
    }

  location_changed = (result == NEWLOCATION || result == NEWLOCATION_KEEP_POST);
  if (location_changed)
    {
      char *construced_newloc;
      struct url *newloc_parsed;

      assert (mynewloc != NULL);

      if (local_file)
        xfree (local_file);

      /* The HTTP specs only allow absolute URLs to appear in
         redirects, but a ton of boneheaded webservers and CGIs out
         there break the rules and use relative URLs, and popular
         browsers are lenient about this, so wget should be too. */
      construced_newloc = uri_merge (url, mynewloc);
      xfree (mynewloc);
      mynewloc = construced_newloc;

      /* Reset UTF-8 encoding state, keep the URI encoding and reset
         the content encoding. */
      iri->utf8_encode = opt.enable_iri;
      set_content_encoding (iri, NULL);
      xfree_null (iri->orig_url);

      /* Now, see if this new location makes sense. */
      newloc_parsed = url_parse (mynewloc, &up_error_code, iri, true);
      if (!newloc_parsed)
        {
          char *error = url_error (mynewloc, up_error_code);
          logprintf (LOG_NOTQUIET, "%s: %s.\n", escnonprint_uri (mynewloc),
                     error);
          if (orig_parsed != u)
            {
              url_free (u);
            }
          xfree (url);
          xfree (mynewloc);
          xfree (error);
          RESTORE_POST_DATA;
          goto bail;
        }

      /* Now mynewloc will become newloc_parsed->url, because if the
         Location contained relative paths like .././something, we
         don't want that propagating as url.  */
      xfree (mynewloc);
      mynewloc = xstrdup (newloc_parsed->url);

      /* Check for max. number of redirections.  */
      if (++redirection_count > opt.max_redirect)
        {
          logprintf (LOG_NOTQUIET, _("%d redirections exceeded.\n"),
                     opt.max_redirect);
          url_free (newloc_parsed);
          if (orig_parsed != u)
            {
              url_free (u);
            }
          xfree (url);
          xfree (mynewloc);
          RESTORE_POST_DATA;
          result = WRONGCODE;
          goto bail;
        }

      xfree (url);
      url = mynewloc;
      if (orig_parsed != u)
        {
          url_free (u);
        }
      u = newloc_parsed;

      /* If we're being redirected from POST, and we received a
         redirect code different than 307, we don't want to POST
         again.  Many requests answer POST with a redirection to an
         index page; that redirection is clearly a GET.  We "suspend"
         POST data for the duration of the redirections, and restore
         it when we're done.
	 
	 RFC2616 HTTP/1.1 introduces code 307 Temporary Redirect
	 specifically to preserve the method of the request.
	 */
      if (result != NEWLOCATION_KEEP_POST && !post_data_suspended)
        SUSPEND_POST_DATA;

      goto redirected;
    }

  /* Try to not encode in UTF-8 if fetching failed */
  if (!(*dt & RETROKF) && iri->utf8_encode)
    {
      iri->utf8_encode = false;
      if (orig_parsed != u)
        {
          url_free (u);
        }
      u = url_parse (origurl, NULL, iri, true);
      if (u)
        {
          DEBUGP (("[IRI fallbacking to non-utf8 for %s\n", quote (url)));
          url = xstrdup (u->url);
          iri_fallbacked = 1;
          goto redirected;
        }
      else
          DEBUGP (("[Couldn't fallback to non-utf8 for %s\n", quote (url)));
    }

  if (local_file && u && *dt & RETROKF)
    {
      register_download (u->url, local_file);

      if (!opt.spider && redirection_count && 0 != strcmp (origurl, u->url))
        register_redirection (origurl, u->url);

      if (*dt & TEXTHTML)
        register_html (u->url, local_file);

      if (*dt & TEXTCSS)
        register_css (u->url, local_file);
    }

  if (file)
    *file = local_file ? local_file : NULL;
  else
    xfree_null (local_file);

  if (orig_parsed != u)
    {
      url_free (u);
    }

  if (redirection_count || iri_fallbacked)
    {
      if (newloc)
        *newloc = url;
      else
        xfree (url);
    }
  else
    {
      if (newloc)
        *newloc = NULL;
      xfree (url);
    }

  RESTORE_POST_DATA;

bail:
  if (register_status)
    inform_exit_status (result);
  return result;
}
Example #11
0
/*
 * Log an SSH packet.
 * If n_blanks != 0, blank or omit some parts.
 * Set of blanking areas must be in increasing order.
 */
void log_packet(void *handle, int direction, int type,
		char *texttype, const void *data, int len,
		int n_blanks, const struct logblank_t *blanks,
		const unsigned long *seq,
                unsigned downstream_id, const char *additional_log_text)
{
    struct LogContext *ctx = (struct LogContext *)handle;
    char dumpdata[80], smalldata[5];
    int p = 0, b = 0, omitted = 0;
    int output_pos = 0; /* NZ if pending output in dumpdata */

    if (!(ctx->logtype == LGTYP_SSHRAW ||
          (ctx->logtype == LGTYP_PACKETS && texttype)))
	return;

    /* Packet header. */
    if (texttype) {
        logprintf(ctx, "%s packet ",
                  direction == PKT_INCOMING ? "Incoming" : "Outgoing");

	if (seq)
	    logprintf(ctx, "#0x%lx, ", *seq);

        logprintf(ctx, "type %d / 0x%02x (%s)", type, type, texttype);

        if (downstream_id) {
	    logprintf(ctx, " on behalf of downstream #%u", downstream_id);
            if (additional_log_text)
                logprintf(ctx, " (%s)", additional_log_text);
        }

        logprintf(ctx, "\r\n");
    } else {
        /*
         * Raw data is logged with a timestamp, so that it's possible
         * to determine whether a mysterious delay occurred at the
         * client or server end. (Timestamping the raw data avoids
         * cluttering the normal case of only logging decrypted SSH
         * messages, and also adds conceptual rigour in the case where
         * an SSH message arrives in several pieces.)
         */
        char buf[256];
        struct tm tm;
	tm = ltime();
	strftime(buf, 24, "%Y-%m-%d %H:%M:%S", &tm);
        logprintf(ctx, "%s raw data at %s\r\n",
                  direction == PKT_INCOMING ? "Incoming" : "Outgoing",
                  buf);
    }

    /*
     * Output a hex/ASCII dump of the packet body, blanking/omitting
     * parts as specified.
     */
    while (p < len) {
	int blktype;

	/* Move to a current entry in the blanking array. */
	while ((b < n_blanks) &&
	       (p >= blanks[b].offset + blanks[b].len))
	    b++;
	/* Work out what type of blanking to apply to
	 * this byte. */
	blktype = PKTLOG_EMIT; /* default */
	if ((b < n_blanks) &&
	    (p >= blanks[b].offset) &&
	    (p < blanks[b].offset + blanks[b].len))
	    blktype = blanks[b].type;

	/* If we're about to stop omitting, it's time to say how
	 * much we omitted. */
	if ((blktype != PKTLOG_OMIT) && omitted) {
	    logprintf(ctx, "  (%d byte%s omitted)\r\n",
		      omitted, (omitted==1?"":"s"));
	    omitted = 0;
	}

	/* (Re-)initialise dumpdata as necessary
	 * (start of row, or if we've just stopped omitting) */
	if (!output_pos && !omitted)
	    sprintf(dumpdata, "  %08x%*s\r\n", p-(p%16), 1+3*16+2+16, "");

	/* Deal with the current byte. */
	if (blktype == PKTLOG_OMIT) {
	    omitted++;
	} else {
	    int c;
	    if (blktype == PKTLOG_BLANK) {
		c = 'X';
		sprintf(smalldata, "XX");
	    } else {  /* PKTLOG_EMIT */
		c = ((unsigned char *)data)[p];
		sprintf(smalldata, "%02x", c);
	    }
	    dumpdata[10+2+3*(p%16)] = smalldata[0];
	    dumpdata[10+2+3*(p%16)+1] = smalldata[1];
	    dumpdata[10+1+3*16+2+(p%16)] = (isprint(c) ? c : '.');
	    output_pos = (p%16) + 1;
	}

	p++;

	/* Flush row if necessary */
	if (((p % 16) == 0) || (p == len) || omitted) {
	    if (output_pos) {
		strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n");
		logwrite(ctx, dumpdata, strlen(dumpdata));
		output_pos = 0;
	    }
	}

    }

    /* Tidy up */
    if (omitted)
	logprintf(ctx, "  (%d byte%s omitted)\r\n",
		  omitted, (omitted==1?"":"s"));
    logflush(ctx);
}
Example #12
0
/* Merge two options structs */
void options_merge(struct options_t **a, struct options_t **b) {
    struct options_t *temp = NULL;
    temp = *b;
    while(temp) {
        struct options_t *optnode = malloc(sizeof(struct options_t));
        if(!optnode) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        optnode->id = temp->id;
        if(temp->name) {
            optnode->name = malloc(strlen(temp->name)+1);
            if(!optnode->name) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(optnode->name, '\0', strlen(temp->name)+1);
            strcpy(optnode->name, temp->name);
        } else {
            optnode->name = malloc(4);
            if(!optnode->name) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(optnode->name, '\0', 4);
        }
        if(temp->value) {
            optnode->value = malloc(strlen(temp->value)+1);
            if(!optnode->value) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            strcpy(optnode->value, temp->value);
        } else {
            optnode->value = malloc(4);
            if(!optnode->value) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(optnode->value, '\0', 4);
        }
        if(temp->mask) {
            optnode->mask = malloc(strlen(temp->mask)*2);
            if(!optnode->mask) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            strcpy(optnode->mask, temp->mask);
        } else {
            optnode->mask = malloc(4);
            if(!optnode->mask) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(optnode->mask, '\0', 4);
        }
        optnode->argtype = temp->argtype;
        optnode->conftype = temp->conftype;
        optnode->next = *a;
        *a = optnode;
        temp = temp->next;
    }
}
Example #13
0
/* Add a new option to the options struct */
void options_add(struct options_t **opt, int id, const char *name, int argtype, int conftype, const char *mask) {
    char *ctmp = NULL;
    char *nname = malloc(strlen(name)+1);
    if(!nname) {
        logprintf(LOG_ERR, "out of memory");
        exit(EXIT_FAILURE);
    }
    strcpy(nname, name);
    int itmp;
    if(!(argtype >= 0 && argtype <= 3)) {
        logprintf(LOG_ERR, "tying to add an invalid option type");
        sfree((void *)&nname);
        exit(EXIT_FAILURE);
    } else if(!(conftype >= 0 && conftype <= 5)) {
        logprintf(LOG_ERR, "trying to add an option with an invalid config type");
        sfree((void *)&nname);
        exit(EXIT_FAILURE);
    } else if(!name) {
        logprintf(LOG_ERR, "trying to add an option without name");
        sfree((void *)&nname);
        exit(EXIT_FAILURE);
    } else if(options_get_name(opt, id, &ctmp) == 0) {
        logprintf(LOG_ERR, "duplicate option id: %c", id);
        sfree((void *)&nname);
        exit(EXIT_FAILURE);
    } else if(options_get_id(opt, nname, &itmp) == 0) {
        logprintf(LOG_ERR, "duplicate option name: %s", name);
        sfree((void *)&nname);
        exit(EXIT_FAILURE);
    } else {
        struct options_t *optnode = malloc(sizeof(struct options_t));
        if(!optnode) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        optnode->id = id;
        optnode->name = malloc(strlen(name)+1);
        if(!optnode->name) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        strcpy(optnode->name, name);
        optnode->argtype = argtype;
        optnode->conftype = conftype;
        optnode->value = malloc(4);
        if(!optnode->value) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        memset(optnode->value, '\0', 4);
        if(mask) {
            optnode->mask = malloc(strlen(mask)+1);
            if(!optnode->mask) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            strcpy(optnode->mask, mask);
        } else {
            optnode->mask = malloc(4);
            if(!optnode->mask) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(optnode->mask, '\0', 4);
        }
        optnode->next = *opt;
        *opt = optnode;
        sfree((void *)&nname);
    }
}
Example #14
0
/* Parse all CLI arguments */
int options_parse(struct options_t **opt, int argc, char **argv, int error_check, char **optarg) {
    int c = 0;
    int itmp = 0;
#ifndef __FreeBSD__
    char *mask;
    regex_t regex;
    int reti;
#endif

    char *ctmp = NULL;

    /* If have read all arguments, exit and reset */
    if(getOptPos>=(argc-1)) {
        getOptPos=0;
        if(*optarg) {
            sfree((void *)&*optarg);
            *optarg = NULL;
        }
        return -1;
    } else {
        getOptPos++;
        /* Reserve enough memory to store all variables */
        longarg = realloc(longarg, 4);
        shortarg = realloc(shortarg, 2);
        *optarg = realloc(*optarg, 4);

        if(!longarg) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        if(!shortarg) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        if(!*optarg) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }

        /* The memory to null */
        memset(*optarg, '\0', 4);
        memset(shortarg, '\0', 2);
        memset(longarg, '\0', 4);

        /* Check if the CLI character contains an equals to (=) sign.
           If it does, we have probably encountered a long argument */
        if(strchr(argv[getOptPos],'=')) {
            /* Copy all characters until the equals to sign.
               This will probably be the name of the argument */
            longarg = realloc(longarg, strcspn(argv[getOptPos],"=")+1);
            if(!longarg) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(longarg, '\0', strcspn(argv[getOptPos],"=")+1);
            memcpy(longarg, &argv[getOptPos][0], strcspn(argv[getOptPos],"="));

            /* Then copy everything after the equals sign.
               This will probably be the value of the argument */
            size_t i = strlen(&argv[getOptPos][strcspn(argv[getOptPos],"=")+1]);
            *optarg = realloc(*optarg, i+1);
            if(!*optarg) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            memset(*optarg, '\0', i+1);
            memcpy(*optarg, &argv[getOptPos][strcspn(argv[getOptPos],"=")+1], i);
        } else {
            /* If the argument does not contain a equals sign.
               Store the argument to check later if it's a long argument */
            longarg = realloc(longarg, strlen(argv[getOptPos])+1);
            if(!longarg) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            strcpy(longarg, argv[getOptPos]);
        }

        /* A short argument only contains of two characters.
           So only store the first two characters */
        shortarg = realloc(shortarg, strlen(argv[getOptPos])+1);
        if(!shortarg) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        memset(shortarg, '\0', 3);
        strncpy(shortarg, argv[getOptPos], 2);

        /* Check if the short argument and the long argument are equal,
           then we probably encountered a short argument. Only store the
           identifier character. If there are more CLI characters
           after the current one, store it as the CLI value. However, only
           do this if the first character of the argument doesn't contain*/
        if(strcmp(longarg, shortarg) == 0 && (getOptPos+1)<argc && argv[getOptPos+1][0] != '-') {
            *optarg = realloc(*optarg, strlen(argv[getOptPos+1])+1);
            if(!*optarg) {
                logprintf(LOG_ERR, "out of memory");
                exit(EXIT_FAILURE);
            }
            strcpy(*optarg, argv[getOptPos+1]);
            c = shortarg[1];
            getOptPos++;
        } else {
            /* If the short argument and the long argument are not equal,
                then we probably encountered a long argument. */
            if(longarg[0] == '-' && longarg[1] == '-') {
                gctmp = realloc(gctmp, strlen(&longarg[2])+1);
                if(!gctmp) {
                    logprintf(LOG_ERR, "out of memory");
                    exit(EXIT_FAILURE);
                }
                strcpy(gctmp, &longarg[2]);

                /* Retrieve the short identifier for the long argument */
                if(options_get_id(opt, gctmp, &itmp) == 0) {
                    c = itmp;
                } else if(argv[getOptPos][0] == '-') {
                    c = shortarg[1];
                }
            } else if(argv[getOptPos][0] == '-' && strstr(shortarg, longarg) != 0) {
                c = shortarg[1];
            }
        }

        /* Check if the argument was expected */
        if(options_get_name(opt, c, &ctmp) != 0 && c > 0) {
            if(error_check == 1) {
                if(strcmp(longarg,shortarg) == 0) {
                    if(shortarg[0] == '-') {
                        logprintf(LOG_ERR, "invalid option -- '-%c'", c);
                    } else {
                        logprintf(LOG_ERR, "invalid option -- '%s'", longarg);
                    }
                } else {
                    logprintf(LOG_ERR, "invalid option -- '%s'", longarg);
                }
                goto gc;
            } else {
                return 0;
            }
            /* Check if an argument cannot have an argument that was set */
        } else if(strlen(*optarg) != 0 && options_get_argtype(opt, c, &itmp) == 0 && itmp == 1) {
            if(error_check == 1) {
                if(strcmp(longarg,shortarg) == 0) {
                    logprintf(LOG_ERR, "option '-%c' doesn't take an argument", c);
                } else {
                    logprintf(LOG_ERR, "option '%s' doesn't take an argument", longarg);
                }
                goto gc;
            } else {
                return 0;
            }
            /* Check if an argument required a value that wasn't set */
        } else if(strlen(*optarg) == 0 && options_get_argtype(opt, c, &itmp) == 0 && itmp == 2) {
            if(error_check == 1) {
                if(strcmp(longarg, shortarg) == 0) {
                    logprintf(LOG_ERR, "option '-%c' requires an argument", c);
                } else {
                    logprintf(LOG_ERR, "option '%s' requires an argument", longarg);
                }
                goto gc;
            } else {
                return 0;
            }
            /* Check if we have a valid argument */
        } else if(c == 0) {
            if(error_check == 1) {
                if(shortarg[0] == '-' && strstr(shortarg, longarg) != 0) {
                    logprintf(LOG_ERR, "invalid option -- '-%c'", c);
                } else {
                    logprintf(LOG_ERR, "invalid option -- '%s'", longarg);
                }
                goto gc;
            } else {
                return 0;
            }
        } else {
            /* If the argument didn't have a value, set it to 1 */
            if(strlen(*optarg) == 0) {
                options_set_value(opt, c, "1");
            } else {
#ifndef __FreeBSD__
                if(error_check != 2) {
                    /* If the argument has a regex mask, check if it passes */
                    if(options_get_mask(opt, c, &mask) == 0) {
                        reti = regcomp(&regex, mask, REG_EXTENDED);
                        if(reti) {
                            logprintf(LOG_ERR, "could not compile regex");
                            goto gc;
                        }
                        reti = regexec(&regex, *optarg, 0, NULL, 0);
                        if(reti == REG_NOMATCH || reti != 0) {
                            if(error_check == 1) {
                                if(shortarg[0] == '-') {
                                    logprintf(LOG_ERR, "invalid format -- '-%c'", c);
                                } else {
                                    logprintf(LOG_ERR, "invalid format -- '%s'", longarg);
                                }
                                logprintf(LOG_ERR, "requires %s", mask);
                            }
                            regfree(&regex);
                            goto gc;
                        }
                        regfree(&regex);
                    }
                }
#endif
                options_set_value(opt, c, *optarg);
            }
            return c;
        }
    }

gc:
    getOptPos=0;
    sfree((void *)&*optarg);

    return -2;
}
Example #15
0
int main(int argc, char *argv[])
{
  const char *s;
  const char *p;
  /*
  char *q;
  */
  logopen("l_pmx3.log","w");
 
  s = pmxsearch("a|b","xa");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}
  
  s = pmxsearch("a|b","xb");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}
 
  s = pmxsearch("x(|a|b)<l>","xcd");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}
  
  s = pmxsearch("x(|a|b)<l>","xad");
  if (logcheck(!s)) {logprintf("NOMATCH: %d",pmxlen(1));}

  s = pmxsearch("x(|a|b)<l>","xbd");
  if (logcheck(!s)) {logprintf("NOMATCH: %d",pmxlen(1));}
  
  s = pmxsearch("<d>(|in|cm)<2l>","--4px--");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}
  
  s = pmxsearch("<d>(|in|cm)<2l>","--4in--");
  if (logcheck(!s)) {logprintf("NOMATCH: %d",pmxlen(1));}
 
  s = pmxsearch("<d>(|in|cm)<2l>","--4cm--");
  if (logcheck(!s)) {logprintf("NOMATCH: %d",pmxlen(1));}
 
  s = pmxsearch("<d><!>(in|cm)<2l>","--4px--");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}
  
  s = pmxsearch("<d><!>(in|cm)<2l>","--4in--");
  if (logcheck(!s)) {logprintf("NOMATCH: %d",pmxlen(1));}
 
  s = pmxsearch("<d><!>(in|cm)<2l>","--4cm--");
  if (logcheck(!s)) {logprintf("NOMATCH: %d",pmxlen(1));}
 
  s = pmxsearch("<d>(|)<2l>","--4cm--");
  if (logcheck(!s)) {logprintf("NOMATCH: %d",pmxlen(1));}
 
  s = pmxsearch("<d>()<2l>","--4cm--");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}

  s = pmxsearch("<d>)<2l>","--4cm--");
  logcheck(s);
  
  logprintf("*************************");
  
  s= pmxsearch("<2>(a)","abcaad");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}
  
  s= pmxsearch("<d><?>(cm|in)<l>","a3p");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}

  s= pmxsearch("<d><?>(cm|in)<l>","a3cmp");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}
  
  s= pmxsearch("<d><?>(cm|in)<l>","a3inp");
  if (logcheck(s)) {logprintf("MATCH: %.*s",pmxlen(0),pmxstart(0));}
  
  s= pmxsearch("<d><?>(cm|in|<2l>)<l>","a3pxp");
  if (logcheck(s)) {logprintf("MATCH: %.*s (%.*s)",pmxlen(0),pmxstart(0),pmxlen(1),pmxstart(1));}
  
  s= pmxsearch("<utf>«<*>(\\»|<!=»>)»","a«ABC»x");
  if (logcheck(s)) {logprintf("MATCH: %.*s (%.*s)",pmxlen(0),pmxstart(0),pmxlen(1),pmxstart(1));}
  
  s= pmxsearch("<utf>«<*>(\\»|<!=»>)»","a«A\\»BC»x");
  if (logcheck(s)) {logprintf("MATCH: %.*s (%.*s)",pmxlen(0),pmxstart(0),pmxlen(1),pmxstart(1));}
  
  s= pmxsearch("<utf>«<*>(\\»|<!=»>)»","a«»x");
  if (logcheck(s)) {logprintf("MATCH: %.*s (%.*s)",pmxlen(0),pmxstart(0),pmxlen(1),pmxstart(1));}
  
  s= pmxsearch("(<l>)x<^1>","axa");
  if (logcheck(s)) {logprintf("MATCH: %.*s (%.*s)",pmxlen(0),pmxstart(0),pmxlen(1),pmxstart(1));}
  
  s= pmxsearch("(<l>)x<^1>","axb");
  logcheck(!s);

  s= pmxsearch("(<l><d>)x<2^1>","a3xa3a3");
  if (logcheck(s)) {logprintf("MATCH: %.*s (%.*s)",pmxlen(0),pmxstart(0),pmxlen(1),pmxstart(1));}

  s= pmxsearch("(<l><d>)x<2^1>","a3xa3");
  logcheck(!s);

  s= pmxsearch("(<l><d>)x<2^1>","a3xa3b3xb3b3");
  if (logcheck(s)) {logprintf("MATCH: %.*s (%.*s)",pmxlen(0),pmxstart(0),pmxlen(1),pmxstart(1));}

  s= pmxsearch("(<l>)x<^2>","a3xa3");
  logcheck(!s);

  p = "a<!>(bc|de)<2l>";
  s = pmxsearch(p,"abcbc");
  logcheck(!s);

  s = pmxsearch(p,"axybc");
  if (logcheck(s)) {logprintf("MATCH: %.*s (%.*s)",pmxlen(0),pmxstart(0),pmxlen(1),pmxstart(1));}
  
  logclose();
  exit(0);
}
Example #16
0
/*
 * Reads the fuses three times, checking that all readings are the
 * same. This will ensure that the before values aren't in error!
 */
int safemode_readfuses (unsigned char * lfuse, unsigned char * hfuse,
                        unsigned char * efuse, unsigned char * fuse,
                        PROGRAMMER * pgm, AVRPART * p)
{

  unsigned char value;
  unsigned char fusegood = 0;
  unsigned char allowfuseread = 1;
  unsigned char safemode_lfuse;
  unsigned char safemode_hfuse;
  unsigned char safemode_efuse;
  unsigned char safemode_fuse;
  AVRMEM * m = NULL;

  safemode_lfuse = *lfuse;
  safemode_hfuse = *hfuse;
  safemode_efuse = *efuse;
  safemode_fuse  = *fuse;


  /* Read fuse three times */
  // fusegood = 2; /* If AVR device doesn't support this fuse, don't want
                   // to generate a verify error */
  // m = avr_locate_mem(p, "fuse");
  // if (m != NULL) {
    // fusegood = 0; /* By default fuse is a failure */
    // if(pgm->read_byte(pgm, p, m, 0, &safemode_fuse) != 0)
        // {
        // allowfuseread = 0;
        // }
    // if(pgm->read_byte(pgm, p, m, 0, &value) != 0)
        // {
        // allowfuseread = 0;
        // }
    // if (value == safemode_fuse) {
        // if (pgm->read_byte(pgm, p, m, 0, &value) != 0)
            // {
            // allowfuseread = 0;
            // }
        // if (value == safemode_fuse)
            // {
            // fusegood = 1; /* Fuse read OK three times */
            // }
    // }
  // }

	// //Programmer does not allow fuse reading.... no point trying anymore
    // if (allowfuseread == 0)
		// {
		// return -5;
		// }

    // if (fusegood == 0)	 {
        // logprintf(LOG_ERR, "AVR verify error, unable to read fuse properly.");
		// logprintf(LOG_ERR, "Programmer may not be reliable.");
        // return -1;
    // }
    // else if ((fusegood == 1)) {
		// logprintf(LOG_INFO, "AVR fuse reads as %X", safemode_lfuse);
    // }


  /* Read lfuse three times */
  fusegood = 2; /* If AVR device doesn't support this fuse, don't want
                   to generate a verify error */
  m = p->lfusemem;
  if (m != NULL) {
    fusegood = 0; /* By default fuse is a failure */
    if (pgm->read_byte(pgm, p, m, 0, &safemode_lfuse) != 0) {
        allowfuseread = 0;
	}
    if (pgm->read_byte(pgm, p, m, 0, &value) != 0) {
        allowfuseread = 0;
	}
    if (value == safemode_lfuse) {
        if (pgm->read_byte(pgm, p, m, 0, &value) != 0) {
            allowfuseread = 0;
		}
        if (value == safemode_lfuse) {
        fusegood = 1; /* Fuse read OK three times */
        }
    }
  }

	//Programmer does not allow fuse reading.... no point trying anymore
    if (allowfuseread == 0) {
		return -5;
	}


    if (fusegood == 0)	 {
        logprintf(LOG_ERR, "AVR verify error, unable to read lfuse properly.");
		logprintf(LOG_ERR, "Programmer may not be reliable.");
        return -1;
    }
    else if (fusegood == 1) {
		logprintf(LOG_INFO, "AVR lfuse reads as %X", safemode_lfuse);
    }

  /* Read hfuse three times */
  fusegood = 2; /* If AVR device doesn't support this fuse, don't want
                   to generate a verify error */
  m = p->hfusemem;
  if (m != NULL) {
    fusegood = 0; /* By default fuse is a failure */
    if (pgm->read_byte(pgm, p, m, 0, &safemode_hfuse) != 0) {
        allowfuseread = 0;
	}
    if (pgm->read_byte(pgm, p, m, 0, &value) != 0) {
        allowfuseread = 0;
	}
    if (value == safemode_hfuse) {
        if (pgm->read_byte(pgm, p, m, 0, &value) != 0) {
            allowfuseread = 0;
		}
        if (value == safemode_hfuse) {
             fusegood = 1; /* Fuse read OK three times */
        }
    }
  }

	//Programmer does not allow fuse reading.... no point trying anymore
    if (allowfuseread == 0) {
		return -5;
	}

    if (fusegood == 0)	 {
        logprintf(LOG_ERR, "AVR verify error, unable to read hfuse properly.");
		logprintf(LOG_ERR, "Programmer may not be reliable.");
        return -1;
    }
    else if (fusegood == 1) {
		logprintf(LOG_INFO, "AVR hfuse reads as %X", safemode_lfuse);
    }

  /* Read efuse three times */
  fusegood = 2; /* If AVR device doesn't support this fuse, don't want
                   to generate a verify error */
  // m = avr_locate_mem(p, "efuse");
  // if (m != NULL) {
    // fusegood = 0; /* By default fuse is a failure */
    // if (pgm->read_byte(pgm, p, m, 0, &safemode_efuse) != 0)
        // {
        // allowfuseread = 0;
        // }
    // if (pgm->read_byte(pgm, p, m, 0, &value) != 0)
        // {
        // allowfuseread = 0;
        // }
    // if (value == safemode_efuse) {
        // if (pgm->read_byte(pgm, p, m, 0, &value) != 0)
            // {
            // allowfuseread = 0;
            // }
        // if (value == safemode_efuse){
             // fusegood = 1; /* Fuse read OK three times */
        // }
    // }
  // }

	// //Programmer does not allow fuse reading.... no point trying anymore
    // if (allowfuseread == 0)
		// {
		// return -5;
		// }

    // if (fusegood == 0)	 {
        // logprintf(LOG_ERR, "AVR verify error, unable to read efuse properly.");
		// logprintf(LOG_ERR, "Programmer may not be reliable.");
        // return -1;
    // }
    // else if ((fusegood == 1)) {
		// logprintf(LOG_INFO, "AVR efuse reads as %X", safemode_lfuse);
    // }

  *lfuse = safemode_lfuse;
  *hfuse = safemode_hfuse;
  *efuse = safemode_efuse;
  *fuse  = safemode_fuse;

  return 0;
}
Example #17
0
Socket::Socket(const Address &bindAddress, U32 sendBufferSize, U32 recvBufferSize, bool acceptsBroadcast, bool nonblockingIO)
{
   //TNL_JOURNAL_READ_BLOCK(Socket::Socket,
   //      TNL_JOURNAL_READ( (&mPlatformSocket) );
   //   return;
   //)
   init();
   mPlatformSocket = INVALID_SOCKET;
   mTransportProtocol = bindAddress.transport;

   const char *socketType;

   if(bindAddress.transport == IPProtocol)
   {
      socketType = "UDP";
      mPlatformSocket = socket(AF_INET, SOCK_DGRAM, 0);
   }
   else if(bindAddress.transport == TCPProtocol)
   {
      socketType = "TCP";
      mPlatformSocket = socket(AF_INET, SOCK_STREAM, 0);
   }
#if !defined(NO_IPX_SUPPORT)
   else if(bindAddress.transport == IPXProtocol)
   {
      socketType = "IPX";
      mPlatformSocket = socket(AF_IPX, SOCK_DGRAM, NSPROTO_IPX);
   }
#endif
   else
   {
      logprintf(LogConsumer::LogError, "Attempted to create a socket bound to an invalid transport.");
      return;
   }
   if(mPlatformSocket != INVALID_SOCKET)
   {
      S32 error = 0;
      SOCKADDR address;
      socklen_t addressSize = sizeof(address);

      TNLToSocketAddress(bindAddress, &address, &addressSize);
      error = bind(mPlatformSocket, &address, addressSize);

      Address boundAddress;
      addressSize = sizeof(address);

      getsockname(mPlatformSocket, (PSOCKADDR) &address, &addressSize);
      SocketToTNLAddress(&address, &boundAddress);

      logprintf(LogConsumer::LogUDP, "%s socket created - bound to address: %s", socketType, boundAddress.toString());

      // set the send and receive buffer sizes
      error = setsockopt(mPlatformSocket, SOL_SOCKET, SO_RCVBUF, (char *) &recvBufferSize, sizeof(recvBufferSize));
      if(!error)
      {
         logprintf(LogConsumer::LogUDP, "%s socket receive buffer size set to %d.", socketType, recvBufferSize);
         error = setsockopt(mPlatformSocket, SOL_SOCKET, SO_SNDBUF, (char *) &sendBufferSize, sizeof(sendBufferSize));
      }
      else
         logprintf(LogConsumer::LogError, "%s socket error: unable to set the receive buffer size on socket.", socketType);

      if(!error)
      {
         logprintf(LogConsumer::LogUDP, "%s socket send buffer size set to %d.", socketType, recvBufferSize);

         if(mTransportProtocol != TCPProtocol)
         {
            // set the broadcast allowed flag
            S32 bc = acceptsBroadcast;
            error = setsockopt(mPlatformSocket, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc));
         }
      }
      else
         logprintf(LogConsumer::LogError, "%s socket error: unable to set the send buffer size on socket.", socketType);


      // set the nonblocking IO flag
      if(!error)
      {
#if defined ( TNL_OS_WIN32 ) || defined ( TNL_OS_XBOX )
         DWORD notblock = nonblockingIO;
         S32 error = ioctlsocket(mPlatformSocket, FIONBIO, &notblock);
#else
         U32 notblock = nonblockingIO;
         S32 error;
         error = ioctl(mPlatformSocket, FIONBIO, &notblock);
	 TNLAssert(error == 0, "Could not set non-blocking IO state");
#endif
      }
      else
      {
         logprintf(LogConsumer::LogError, "%s socket error: unable to set broadcast mode on socket.", socketType);
      }

      if(!error)
      {
         logprintf(LogConsumer::LogUDP, "%s socket non-blocking IO set.  Socket initialized.", socketType);
      }
      else
      {
         logprintf(LogConsumer::LogError, "Error prevented successful initialization of %s socket.", socketType);
         closesocket(mPlatformSocket);
         mPlatformSocket = INVALID_SOCKET;
      }
   }
   //TNL_JOURNAL_WRITE_BLOCK(Socket::Socket,
   //   TNL_JOURNAL_WRITE( (mPlatformSocket) );
   //)
}
Example #18
0
/* initialize driver -- returns 1 on success, 0 on error */
static int ati_init(void)
{
	struct usb_device* usb_dev;
	int pipe_fd[2] = { -1, -1 };

	LOGPRINTF(1, "initializing USB receiver");

	rec_buffer_init();

	/* A separate process will be forked to read data from the USB
	 * receiver and write it to a pipe. drv.fd is set to the readable
	 * end of this pipe. */
	if (pipe(pipe_fd) != 0) {
		logperror(LIRC_ERROR, "couldn't open pipe");
		return 0;
	}
	drv.fd = pipe_fd[0];

	usb_dev = find_usb_device();
	if (usb_dev == NULL) {
		logprintf(LIRC_ERROR, "couldn't find a compatible USB device");
		return 0;
	}

	if (!find_device_endpoints(usb_dev)) {
		logprintf(LIRC_ERROR, "couldn't find device endpoints");
		return 0;
	}

	dev_handle = usb_open(usb_dev);
	if (dev_handle == NULL) {
		logperror(LIRC_ERROR, "couldn't open USB receiver");
		goto fail;
	}

	if (usb_claim_interface(dev_handle, 0) != 0) {
		logperror(LIRC_ERROR, "couldn't claim USB interface");
		goto fail;
	}

	errno = 0;
	if ((usb_interrupt_write(dev_handle, dev_ep_out->bEndpointAddress, init1, sizeof(init1), 100) != sizeof(init1))
	    || (usb_interrupt_write(dev_handle, dev_ep_out->bEndpointAddress, init2, sizeof(init2), 100) !=
		sizeof(init2))) {
		logprintf(LIRC_ERROR, "couldn't initialize USB receiver: %s", errno ? strerror(errno) : "short write");
		goto fail;
	}

	snprintf(device_path, sizeof(device_path),
		 "/dev/bus/usb/%s/%s",
		 usb_dev->bus->dirname, usb_dev->filename);
	drv.device = device_path;
	logprintf(LIRC_DEBUG, "atilibusb: using device: %s", device_path);
	child = fork();
	if (child == -1) {
		logperror(LIRC_ERROR, "couldn't fork child process");
		goto fail;
	} else if (child == 0) {
		usb_read_loop(pipe_fd[1]);
	}
	return 1;

fail:
	if (dev_handle) {
		usb_close(dev_handle);
		dev_handle = NULL;
	}
	if (pipe_fd[0] >= 0)
		close(pipe_fd[0]);
	if (pipe_fd[1] >= 0)
		close(pipe_fd[1]);
	return 0;
}
Example #19
0
/* Loop through all files in metalink structure and retrieve them.
   Returns RETROK if all files were downloaded.
   Returns last retrieval error (from retrieve_url) if some files
   could not be downloaded.  */
uerr_t
retrieve_from_metalink (const metalink_t* metalink)
{
  metalink_file_t **mfile_ptr;
  uerr_t last_retr_err = RETROK; /* Store last encountered retrieve error.  */

  FILE *_output_stream = output_stream;
  bool _output_stream_regular = output_stream_regular;
  char *_output_document = opt.output_document;

  DEBUGP (("Retrieving from Metalink\n"));

  /* No files to download.  */
  if (!metalink->files)
    return RETROK;

  if (opt.output_document)
    {
      /* We cannot support output_document as we need to compute checksum
         of downloaded file, and to remove it if the checksum is bad.  */
      logputs (LOG_NOTQUIET,
               _("-O not supported for metalink download. Ignoring.\n"));
    }

  for (mfile_ptr = metalink->files; *mfile_ptr; mfile_ptr++)
    {
      metalink_file_t *mfile = *mfile_ptr;
      metalink_resource_t **mres_ptr;
      char *filename = NULL;
      bool hash_ok = false;

      uerr_t retr_err = METALINK_MISSING_RESOURCE;

      /* -1 -> file should be rejected
         0 -> could not verify
         1 -> verified successfully  */
      char sig_status = 0;

      output_stream = NULL;

      DEBUGP (("Processing metalink file %s...\n", quote (mfile->name)));

      /* Resources are sorted by priority.  */
      for (mres_ptr = mfile->resources; *mres_ptr; mres_ptr++)
        {
          metalink_resource_t *mres = *mres_ptr;
          metalink_checksum_t **mchksum_ptr, *mchksum;
          struct iri *iri;
          struct url *url;
          int url_err;

          if (!RES_TYPE_SUPPORTED (mres->type))
            {
              logprintf (LOG_VERBOSE,
                         _("Resource type %s not supported, ignoring...\n"),
                         quote (mres->type));
              continue;
            }

          retr_err = METALINK_RETR_ERROR;

          /* If output_stream is not NULL, then we have failed on
             previous resource and are retrying. Thus, remove the file.  */
          if (output_stream)
            {
              fclose (output_stream);
              output_stream = NULL;
              if (unlink (filename))
                logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
              xfree (filename);
            }

          /* Parse our resource URL.  */
          iri = iri_new ();
          set_uri_encoding (iri, opt.locale, true);
          url = url_parse (mres->url, &url_err, iri, false);

          if (!url)
            {
              char *error = url_error (mres->url, url_err);
              logprintf (LOG_NOTQUIET, "%s: %s.\n", mres->url, error);
              xfree (error);
              inform_exit_status (URLERROR);
              iri_free (iri);
              continue;
            }
          else
            {
              /* Avoid recursive Metalink from HTTP headers.  */
              bool _metalink_http = opt.metalink_over_http;

              /* Assure proper local file name regardless of the URL
                 of particular Metalink resource.
                 To do that we create the local file here and put
                 it as output_stream. We restore the original configuration
                 after we are finished with the file.  */
              output_stream = unique_create (mfile->name, true, &filename);
              output_stream_regular = true;

              /* Store the real file name for displaying in messages.  */
              opt.output_document = filename;

              opt.metalink_over_http = false;
              DEBUGP (("Storing to %s\n", filename));
              retr_err = retrieve_url (url, mres->url, NULL, NULL,
                                       NULL, NULL, opt.recursive, iri, false);
              opt.metalink_over_http = _metalink_http;
            }
          url_free (url);
          iri_free (iri);

          if (retr_err == RETROK)
            {
              FILE *local_file;

              /* Check the digest.  */
              local_file = fopen (filename, "r");
              if (!local_file)
                {
                  logprintf (LOG_NOTQUIET, _("Could not open downloaded file.\n"));
                  continue;
                }

              for (mchksum_ptr = mfile->checksums; *mchksum_ptr; mchksum_ptr++)
                {
                  char sha256[SHA256_DIGEST_SIZE];
                  char sha256_txt[2 * SHA256_DIGEST_SIZE + 1];

                  mchksum = *mchksum_ptr;

                  /* I have seen both variants...  */
                  if (strcasecmp (mchksum->type, "sha256")
                      && strcasecmp (mchksum->type, "sha-256"))
                    {
                      DEBUGP (("Ignoring unsupported checksum type %s.\n",
                               quote (mchksum->type)));
                      continue;
                    }

                  logprintf (LOG_VERBOSE, _("Computing checksum for %s\n"),
                             quote (mfile->name));

                  sha256_stream (local_file, sha256);
                  wg_hex_to_string (sha256_txt, sha256, SHA256_DIGEST_SIZE);
                  DEBUGP (("Declared hash: %s\n", mchksum->hash));
                  DEBUGP (("Computed hash: %s\n", sha256_txt));
                  if (!strcmp (sha256_txt, mchksum->hash))
                    {
                      logputs (LOG_VERBOSE,
                               _("Checksum matches.\n"));
                      hash_ok = true;
                    }
                  else
                    {
                      logprintf (LOG_NOTQUIET,
                                 _("Checksum mismatch for file %s.\n"),
                                 quote (mfile->name));
                      hash_ok = false;
                    }

                  /* Stop as soon as we checked the supported checksum.  */
                  break;
                } /* Iterate over available checksums.  */
              fclose (local_file);
              local_file = NULL;

              if (!hash_ok)
                continue;

              sig_status = 0; /* Not verified.  */

#ifdef HAVE_GPGME
              /* Check the crypto signature.

                 Note that the signtures from Metalink in XML will not be
                 parsed when using libmetalink version older than 0.1.3.
                 Metalink-over-HTTP is not affected by this problem.  */
              if (mfile->signature)
                {
                  metalink_signature_t *msig = mfile->signature;
                  gpgme_error_t gpgerr;
                  gpgme_ctx_t gpgctx;
                  gpgme_data_t gpgsigdata, gpgdata;
                  gpgme_verify_result_t gpgres;
                  gpgme_signature_t gpgsig;
                  gpgme_protocol_t gpgprot = GPGME_PROTOCOL_UNKNOWN;
                  int fd = -1;

                  /* Initialize the library - as name suggests.  */
                  gpgme_check_version (NULL);

                  /* Open data file.  */
                  fd = open (filename, O_RDONLY);
                  if (fd == -1)
                    {
                      logputs (LOG_NOTQUIET,
                               _("Could not open downloaded file for signature "
                                 "verification.\n"));
                      goto gpg_skip_verification;
                    }

                  /* Assign file descriptor to GPG data structure.  */
                  gpgerr = gpgme_data_new_from_fd (&gpgdata, fd);
                  if (gpgerr != GPG_ERR_NO_ERROR)
                    {
                      logprintf (LOG_NOTQUIET,
                                 "GPGME data_new_from_fd: %s\n",
                                 gpgme_strerror (gpgerr));
                      goto gpg_skip_verification;
                    }

                  /* Prepare new GPGME context.  */
                  gpgerr = gpgme_new (&gpgctx);
                  if (gpgerr != GPG_ERR_NO_ERROR)
                    {
                      logprintf (LOG_NOTQUIET,
                                 "GPGME new: %s\n",
                                 gpgme_strerror (gpgerr));
                      gpgme_data_release (gpgdata);
                      goto gpg_skip_verification;
                    }

                  DEBUGP (("Veryfying signature %s:\n%s\n",
                           quote (msig->mediatype),
                           msig->signature));

                  /* Check signature type.  */
                  if (!strcmp (msig->mediatype, "application/pgp-signature"))
                    gpgprot = GPGME_PROTOCOL_OpenPGP;
                  else /* Unsupported signature type.  */
                    {
                      gpgme_release (gpgctx);
                      gpgme_data_release (gpgdata);
                      goto gpg_skip_verification;
                    }

                  gpgerr = gpgme_set_protocol (gpgctx, gpgprot);
                  if (gpgerr != GPG_ERR_NO_ERROR)
                    {
                      logprintf (LOG_NOTQUIET,
                                 "GPGME set_protocol: %s\n",
                                 gpgme_strerror (gpgerr));
                      gpgme_release (gpgctx);
                      gpgme_data_release (gpgdata);
                      goto gpg_skip_verification;
                    }

                  /* Load the signature.  */
                  gpgerr = gpgme_data_new_from_mem (&gpgsigdata,
                                                    msig->signature,
                                                    strlen (msig->signature),
                                                    0);
                  if (gpgerr != GPG_ERR_NO_ERROR)
                    {
                      logprintf (LOG_NOTQUIET,
                                 _("GPGME data_new_from_mem: %s\n"),
                                 gpgme_strerror (gpgerr));
                      gpgme_release (gpgctx);
                      gpgme_data_release (gpgdata);
                      goto gpg_skip_verification;
                    }

                  /* Verify the signature.  */
                  gpgerr = gpgme_op_verify (gpgctx, gpgsigdata, gpgdata, NULL);
                  if (gpgerr != GPG_ERR_NO_ERROR)
                    {
                      logprintf (LOG_NOTQUIET,
                                 _("GPGME op_verify: %s\n"),
                                 gpgme_strerror (gpgerr));
                      gpgme_data_release (gpgsigdata);
                      gpgme_release (gpgctx);
                      gpgme_data_release (gpgdata);
                      goto gpg_skip_verification;
                    }

                  /* Check the results.  */
                  gpgres = gpgme_op_verify_result (gpgctx);
                  if (!gpgres)
                    {
                      logputs (LOG_NOTQUIET,
                               _("GPGME op_verify_result: NULL\n"));
                      gpgme_data_release (gpgsigdata);
                      gpgme_release (gpgctx);
                      gpgme_data_release (gpgdata);
                      goto gpg_skip_verification;
                    }

                  /* The list is null-terminated.  */
                  for (gpgsig = gpgres->signatures; gpgsig; gpgsig = gpgsig->next)
                    {
                      DEBUGP (("Checking signature 0x%p\n",
                               (void *) gpgsig));
                      DEBUGP (("Summary=0x%x Status=0x%x\n",
                               gpgsig->summary, gpgsig->status & 0xFFFF));

                      if (gpgsig->summary
                          & (GPGME_SIGSUM_VALID | GPGME_SIGSUM_GREEN))
                        {
                          logputs (LOG_VERBOSE,
                                   _("Signature validation suceeded.\n"));
                          sig_status = 1;
                          break;
                        }

                      if (gpgsig->summary & GPGME_SIGSUM_RED)
                        {
                          logputs (LOG_NOTQUIET,
                                   _("Invalid signature. Rejecting resource.\n"));
                          sig_status = -1;
                          break;
                        }

                      if (gpgsig->summary == 0
                          && (gpgsig->status & 0xFFFF) == GPG_ERR_NO_ERROR)
                        {
                          logputs (LOG_VERBOSE,
                                   _("Data matches signature, but signature "
                                     "is not trusted.\n"));
                        }

                      if ((gpgsig->status & 0xFFFF) != GPG_ERR_NO_ERROR)
                        {
                          logprintf (LOG_NOTQUIET,
                                     "GPGME: %s\n",
                                     gpgme_strerror (gpgsig->status & 0xFFFF));
                        }
                    }
                  gpgme_data_release (gpgsigdata);
                  gpgme_release (gpgctx);
                  gpgme_data_release (gpgdata);
gpg_skip_verification:
                  if (fd != -1)
                    close (fd);
                } /* endif (mfile->signature) */
#endif
              /* Stop if file was downloaded with success.  */
              if (sig_status >= 0)
                break;
            } /* endif RETR_OK.  */
        } /* Iterate over resources.  */

      if (retr_err != RETROK)
        {
          logprintf (LOG_VERBOSE, _("Failed to download %s. Skipping resource.\n"),
                     quote (mfile->name));
        }
      else if (!hash_ok)
        {
          retr_err = METALINK_CHKSUM_ERROR;
          logprintf (LOG_NOTQUIET,
                     _("File %s retrieved but checksum does not match. "
                       "\n"), quote (mfile->name));
        }
#ifdef HAVE_GPGME
        /* Signature will be only validated if hash check was successful.  */
      else if (sig_status < 0)
        {
          retr_err = METALINK_SIG_ERROR;
          logprintf (LOG_NOTQUIET,
                     _("File %s retrieved but signature does not match. "
                       "\n"), quote (mfile->name));
        }
#endif
      last_retr_err = retr_err == RETROK ? last_retr_err : retr_err;

      /* Remove the file if error encountered or if option specified.
         Note: the file has been downloaded using *_loop. Therefore, it
         is not necessary to keep the file for continuated download.  */
      if ((retr_err != RETROK || opt.delete_after)
           && filename != NULL && file_exists_p (filename))
        {
          logprintf (LOG_VERBOSE, _("Removing %s.\n"), quote (filename));
          if (unlink (filename))
            logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
        }
      if (output_stream)
        {
          fclose (output_stream);
          output_stream = NULL;
        }
      xfree (filename);
    } /* Iterate over files.  */

  /* Restore original values.  */
  opt.output_document = _output_document;
  output_stream_regular = _output_stream_regular;
  output_stream = _output_stream;

  return last_retr_err;
}
Example #20
0
static int rules_parse(JsonNode *root) {
	int have_error = 0, match = 0;
	unsigned int i = 0;
	struct JsonNode *jrules = NULL;
	char *rule = NULL;
	double active = 1.0;

	if(root->tag == JSON_OBJECT) {
		jrules = json_first_child(root);
		while(jrules) {
			i++;
			if(jrules->tag == JSON_OBJECT) {
				if(json_find_string(jrules, "rule", &rule) != 0) {
					logprintf(LOG_ERR, "config rules #%d \"%s\", missing \"rule\"", i, jrules->key);
					have_error = 1;
					break;
				} else {
					active = 1.0;
					json_find_number(jrules, "active", &active);

					struct rules_t *tmp = rules;
					match = 0;
					while(tmp) {
						if(strcmp(tmp->name, jrules->key) == 0) {
							match = 1;
							break;
						}
						tmp = tmp->next;
					}
					if(match == 1) {
						logprintf(LOG_ERR, "config rules #%d \"%s\" already exists", i, jrules->key);
						have_error = 1;
						break;
					}
					struct rules_t *node = MALLOC(sizeof(struct rules_t));
					if(node == NULL) {
						logprintf(LOG_ERR, "out of memory");
						exit(EXIT_FAILURE);
					}
					node->next = NULL;
					node->values = NULL;
					node->nrdevices = 0;
					node->status = 0;
					node->devices = NULL;
					node->action = NULL;
					node->arguments = NULL;
					if(event_parse_rule(rule, node, 0, i, 1) == -1) {
						for(i=0;i<node->nrdevices;i++) {
							FREE(node->devices[i]);
						}
						if(node->devices != NULL) {
							FREE(node->devices);
						}
						FREE(node);
						have_error = 1;
						break;
					}
					node->status = 0;
					node->rule = MALLOC(strlen(rule)+1);
					if(node->rule == NULL) {
						logprintf(LOG_ERR, "out of memory");
						exit(EXIT_FAILURE);
					}
					strcpy(node->rule, rule);
					node->name = MALLOC(strlen(jrules->key)+1);
					if(node->name == NULL) {
						logprintf(LOG_ERR, "out of memory");
						exit(EXIT_FAILURE);
					}
					strcpy(node->name, jrules->key);
					node->active = (unsigned short)active;

					tmp = rules;
					if(tmp) {
						while(tmp->next != NULL) {
							tmp = tmp->next;
						}
						tmp->next = node;
					} else {
						node->next = rules;
						rules = node;
					}
				}
			}
			jrules = jrules->next;
		}
	} else {
		logprintf(LOG_ERR, "config rules should be placed in an object");
		have_error = 1;
	}

	return have_error;
}
Example #21
0
//
//	Internal version of getreply(), takes additional flags
//	(Used in ftp_recursive.c)
//
//	Get reply to an FTP command
//	This version works properly with multi-line replies
//
//	Results:
//		Success:	Returns the reply code from the ftp server - for multi-line
//			replies, this will be the code from the last line
//		Failure:	600 = Error, 700 = Break, 800 = Timeout
//
//		421 "Service not available, remote server has closed connection"
//		 is now returned for any error as in berkley ftp code
//
//	What do we do in situation for Timeout on read? AD simply calls this
//	an error and reports 421 which closes connection.
//	Should this not handle this and maybe just ignore it or resend command?
//
int _getreply(
	struct ftp_info  *info,
	unsigned long     flags,
	int             (*updatefn)(void *,int,char *),
	void             *updateinfo )
{
struct opusftp_globals *ogp = info->fi_og;
int   actual;			// Bytes received
int   first = 1;		// Is this the first line?
int   multi = 0;		// Multi-line reply
int   currcode;			// Current line's code
int   checkabort_time = 0;	// By default don't check for aborts on replies
char *iobuf;

// Need to allocate buffer for quiet io?
if	(flags & GETREPLY_QUIET)
	{
	if	(!(iobuf = AllocVec( IOBUFSIZE+1, MEMF_CLEAR )))
		{
		info->fi_reply = 600;
		return info->fi_reply;
		}
	}
else
	iobuf = info->fi_iobuf;

if	(info->fi_reply < 0) 	// not accept timeouts
	{
	checkabort_time = 1;

	// -2 is special marker for DEST STOR to return often to update progress bar
	if	(info->fi_reply == -2)
		checkabort_time = 2; 

	}
else
	info->fi_reply = 600;	// Error by default 
	
// Safety
flush_socket_buffer( info );

// Read one line at a time
do
	{
	// EOF or error
	if	((sgets( info, iobuf, IOBUFSIZE, info->fi_cs, checkabort_time )) == 0)
		{
		if	(info->fi_reply == 800)
			info->fi_errno = FTPERR_TIMEOUT;
		else
			info->fi_errno = FTPERR_FAKE_421;

		if	(info->fi_reply < 700)
			info->fi_reply = 600;

		break;
		}

	actual = strlen(iobuf);

	// NULL terminate
	iobuf[actual] = 0;

	// Got at least reply code?
	if	(actual >= 3
		&& isdigit( iobuf[0] )
		&& isdigit( iobuf[1] )
		&& isdigit( iobuf[2] ))
		currcode = iobuf[0] * 100 + iobuf[1] * 10 + iobuf[2] - '0' * 111;
	else
		currcode = 0;

	// Output reply, omitting the code if debug is off
	// No output if doing_noop
	if	(!info->fi_doing_noop)
		{
		if	(!ogp->og_oc.oc_log_debug && currcode)
			{
			if	(updatefn && updateinfo)
				(*updatefn)( updateinfo, -1, iobuf + 4 );

			logprintf( iobuf + 4 );
			}
		else
			{
			if	(updatefn && updateinfo)
				(*updatefn)( updateinfo, -1, iobuf );

			logprintf( iobuf );
			}
		}

	if	(currcode)
		{
		// Invalid code on any line ?
		if	(currcode < 100 || currcode > 559)
			{
			info->fi_reply = 600;
			break;
			}

		// Code is okay so update it
		info->fi_reply = currcode;

		// Start of multi-line reply?
		if	(iobuf[3] == '-')
			{
			if	(!multi)
				multi = 1;
			}
		// End of multi-line reply?
		else if	(multi)
			multi = 0;
		}

	// First block?
	if	(first)
		first = 0;

	// Mangled code on last line of reply
	if	(!multi && !currcode)
		{
		info->fi_reply = 600;
		break;
		}

	} while (multi);

// Convert ERROR codes to 'connection lost' code
if	(info->fi_reply >= 600)
	info->fi_reply = 421;

// Need to free buffer for quiet io?
if	(flags & GETREPLY_QUIET)
	if	(iobuf)
		FreeVec( iobuf );

return info->fi_reply;
}
Example #22
0
/* Change the links in one file.  LINKS is a list of links in the
   document, along with their positions and the desired direction of
   the conversion.  */
static void
convert_links (const char *file, struct urlpos *links)
{
  struct file_memory *fm;
  FILE *fp;
  const char *p;
  downloaded_file_t downloaded_file_return;

  struct urlpos *link;
  int to_url_count = 0, to_file_count = 0;

  logprintf (LOG_VERBOSE, _("Converting %s... "), file);

  {
    /* First we do a "dry run": go through the list L and see whether
       any URL needs to be converted in the first place.  If not, just
       leave the file alone.  */
    int dry_count = 0;
    struct urlpos *dry;
    for (dry = links; dry; dry = dry->next)
      if (dry->convert != CO_NOCONVERT)
        ++dry_count;
    if (!dry_count)
      {
        logputs (LOG_VERBOSE, _("nothing to do.\n"));
        return;
      }
  }

  fm = wget_read_file (file);
  if (!fm)
    {
      logprintf (LOG_NOTQUIET, _("Cannot convert links in %s: %s\n"),
                 file, strerror (errno));
      return;
    }

  downloaded_file_return = downloaded_file (CHECK_FOR_FILE, file);
  if (opt.backup_converted && downloaded_file_return)
    write_backup_file (file, downloaded_file_return);

  /* Before opening the file for writing, unlink the file.  This is
     important if the data in FM is mmaped.  In such case, nulling the
     file, which is what fopen() below does, would make us read all
     zeroes from the mmaped region.  */
  if (unlink (file) < 0 && errno != ENOENT)
    {
      logprintf (LOG_NOTQUIET, _("Unable to delete %s: %s\n"),
                 quote (file), strerror (errno));
      wget_read_file_free (fm);
      return;
    }
  /* Now open the file for writing.  */
  fp = fopen (file, "wb");
  if (!fp)
    {
      logprintf (LOG_NOTQUIET, _("Cannot convert links in %s: %s\n"),
                 file, strerror (errno));
      wget_read_file_free (fm);
      return;
    }

  /* Here we loop through all the URLs in file, replacing those of
     them that are downloaded with relative references.  */
  p = fm->content;
  for (link = links; link; link = link->next)
    {
      char *url_start = fm->content + link->pos;

      if (link->pos >= fm->length)
        {
          DEBUGP (("Something strange is going on.  Please investigate."));
          break;
        }
      /* If the URL is not to be converted, skip it.  */
      if (link->convert == CO_NOCONVERT)
        {
          DEBUGP (("Skipping %s at position %d.\n", link->url->url, link->pos));
          continue;
        }

      /* Echo the file contents, up to the offending URL's opening
         quote, to the outfile.  */
      fwrite (p, 1, url_start - p, fp);
      p = url_start;

      switch (link->convert)
        {
        case CO_CONVERT_TO_RELATIVE:
          /* Convert absolute URL to relative. */
          {
            char *newname = construct_relative (file, link->local_name);
            char *quoted_newname = local_quote_string (newname,
                                                       link->link_css_p);

            if (link->link_css_p)
              p = replace_plain (p, link->size, fp, quoted_newname);
            else if (!link->link_refresh_p)
              p = replace_attr (p, link->size, fp, quoted_newname);
            else
              p = replace_attr_refresh_hack (p, link->size, fp, quoted_newname,
                                             link->refresh_timeout);

            DEBUGP (("TO_RELATIVE: %s to %s at position %d in %s.\n",
                     link->url->url, newname, link->pos, file));
            xfree (newname);
            xfree (quoted_newname);
            ++to_file_count;
            break;
          }
        case CO_CONVERT_TO_COMPLETE:
          /* Convert the link to absolute URL. */
          {
            char *newlink = link->url->url;
            char *quoted_newlink = html_quote_string (newlink);

            if (link->link_css_p)
              p = replace_plain (p, link->size, fp, newlink);
            else if (!link->link_refresh_p)
              p = replace_attr (p, link->size, fp, quoted_newlink);
            else
              p = replace_attr_refresh_hack (p, link->size, fp, quoted_newlink,
                                             link->refresh_timeout);

            DEBUGP (("TO_COMPLETE: <something> to %s at position %d in %s.\n",
                     newlink, link->pos, file));
            xfree (quoted_newlink);
            ++to_url_count;
            break;
          }
        case CO_NULLIFY_BASE:
          /* Change the base href to "". */
          p = replace_attr (p, link->size, fp, "");
          break;
        case CO_NOCONVERT:
          abort ();
          break;
        }
    }

  /* Output the rest of the file. */
  if (p - fm->content < fm->length)
    fwrite (p, 1, fm->length - (p - fm->content), fp);
  fclose (fp);
  wget_read_file_free (fm);

  logprintf (LOG_VERBOSE, "%d-%d\n", to_file_count, to_url_count);
}
Example #23
0
/*
 * Log an SSH packet.
 * If n_blanks != 0, blank or omit some parts.
 * Set of blanking areas must be in increasing order.
 */
void log_packet(void *handle, int direction, int type,
		char *texttype, const void *data, int len,
		int n_blanks, const struct logblank_t *blanks,
		const unsigned long *seq)
{
    struct LogContext *ctx = (struct LogContext *)handle;
    char dumpdata[80], smalldata[5];
    int p = 0, b = 0, omitted = 0;
    int output_pos = 0; /* NZ if pending output in dumpdata */

    if (!(ctx->cfg.logtype == LGTYP_SSHRAW ||
          (ctx->cfg.logtype == LGTYP_PACKETS && texttype)))
	return;

    /* Packet header. */
    if (texttype) {
	if (seq) {
	    logprintf(ctx, "%s packet #0x%lx, type %d / 0x%02x (%s)\r\n",
		      direction == PKT_INCOMING ? "Incoming" : "Outgoing",
		      *seq, type, type, texttype);
	} else {
	    logprintf(ctx, "%s packet type %d / 0x%02x (%s)\r\n",
		      direction == PKT_INCOMING ? "Incoming" : "Outgoing",
		      type, type, texttype);
	}
    } else {
        logprintf(ctx, "%s raw data\r\n",
                  direction == PKT_INCOMING ? "Incoming" : "Outgoing");
    }

    /*
     * Output a hex/ASCII dump of the packet body, blanking/omitting
     * parts as specified.
     */
    while (p < len) {
	int blktype;

	/* Move to a current entry in the blanking array. */
	while ((b < n_blanks) &&
	       (p >= blanks[b].offset + blanks[b].len))
	    b++;
	/* Work out what type of blanking to apply to
	 * this byte. */
	blktype = PKTLOG_EMIT; /* default */
	if ((b < n_blanks) &&
	    (p >= blanks[b].offset) &&
	    (p < blanks[b].offset + blanks[b].len))
	    blktype = blanks[b].type;

	/* If we're about to stop omitting, it's time to say how
	 * much we omitted. */
	if ((blktype != PKTLOG_OMIT) && omitted) {
	    logprintf(ctx, "  (%d byte%s omitted)\r\n",
		      omitted, (omitted==1?"":"s"));
	    omitted = 0;
	}

	/* (Re-)initialise dumpdata as necessary
	 * (start of row, or if we've just stopped omitting) */
	if (!output_pos && !omitted)
	    sprintf(dumpdata, "  %08x%*s\r\n", p-(p%16), 1+3*16+2+16, "");

	/* Deal with the current byte. */
	if (blktype == PKTLOG_OMIT) {
	    omitted++;
	} else {
	    int c;
	    if (blktype == PKTLOG_BLANK) {
		c = 'X';
		sprintf(smalldata, "XX");
	    } else {  /* PKTLOG_EMIT */
		c = ((unsigned char *)data)[p];
		sprintf(smalldata, "%02x", c);
	    }
	    dumpdata[10+2+3*(p%16)] = smalldata[0];
	    dumpdata[10+2+3*(p%16)+1] = smalldata[1];
	    dumpdata[10+1+3*16+2+(p%16)] = (isprint(c) ? c : '.');
	    output_pos = (p%16) + 1;
	}

	p++;

	/* Flush row if necessary */
	if (((p % 16) == 0) || (p == len) || omitted) {
	    if (output_pos) {
		strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n");
		logwrite(ctx, dumpdata, strlen(dumpdata));
		output_pos = 0;
	    }
	}

    }

    /* Tidy up */
    if (omitted)
	logprintf(ctx, "  (%d byte%s omitted)\r\n",
		  omitted, (omitted==1?"":"s"));
    logflush(ctx);
}
Example #24
0
/* The function creates an HTML index containing references to given
   directories and files on the appropriate host.  The references are
   FTP.  */
uerr_t
ftp_index (const char *file, struct urlinfo *u, struct fileinfo *f)
{
  FILE *fp;
  char *upwd;
  char *htclfile;		/* HTML-clean file name */

  if (!opt.dfp)
    {
      fp = fopen (file, "wb");
      if (!fp)
	{
	  logprintf (LOG_NOTQUIET, "%s: %s\n", file, strerror (errno));
	  return FOPENERR;
	}
    }
  else
    fp = opt.dfp;
  if (u->user)
    {
      char *tmpu, *tmpp;        /* temporary, clean user and passwd */

      tmpu = CLEANDUP (u->user);
      tmpp = u->passwd ? CLEANDUP (u->passwd) : NULL;
      upwd = (char *)xmalloc (strlen (tmpu)
			     + (tmpp ? (1 + strlen (tmpp)) : 0) + 2);
      sprintf (upwd, "%s%s%s@", tmpu, tmpp ? ":" : "", tmpp ? tmpp : "");
      free (tmpu);
      FREE_MAYBE (tmpp);
    }
  else
    upwd = xstrdup ("");
  fprintf (fp, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n");
  fprintf (fp, "<html>\n<head>\n<title>");
  fprintf (fp, _("Index of /%s on %s:%d"), u->dir, u->host, u->port);
  fprintf (fp, "</title>\n</head>\n<body>\n<h1>");
  fprintf (fp, _("Index of /%s on %s:%d"), u->dir, u->host, u->port);
  fprintf (fp, "</h1>\n<hr>\n<pre>\n");
  while (f)
    {
      fprintf (fp, "  ");
      if (f->tstamp != -1)
	{
	  /* #### Should we translate the months? */
	  static char *months[] = {
	    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
	    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
	  };
	  struct tm *ptm = localtime ((time_t *)&f->tstamp);

	  fprintf (fp, "%d %s %02d ", ptm->tm_year + 1900, months[ptm->tm_mon],
		  ptm->tm_mday);
	  if (ptm->tm_hour)
	    fprintf (fp, "%02d:%02d  ", ptm->tm_hour, ptm->tm_min);
	  else
	    fprintf (fp, "       ");
	}
      else
	fprintf (fp, _("time unknown       "));
      switch (f->type)
	{
	case FT_PLAINFILE:
	  fprintf (fp, _("File        "));
	  break;
	case FT_DIRECTORY:
	  fprintf (fp, _("Directory   "));
	  break;
	case FT_SYMLINK:
	  fprintf (fp, _("Link        "));
	  break;
	default:
	  fprintf (fp, _("Not sure    "));
	  break;
	}
      htclfile = html_quote_string (f->name);
      fprintf (fp, "<a href=\"ftp://%s%s:%hu", upwd, u->host, u->port);
      if (*u->dir != '/')
	putc ('/', fp);
      fprintf (fp, "%s", u->dir);
      if (*u->dir)
	putc ('/', fp);
      fprintf (fp, "%s", htclfile);
      if (f->type == FT_DIRECTORY)
	putc ('/', fp);
      fprintf (fp, "\">%s", htclfile);
      if (f->type == FT_DIRECTORY)
	putc ('/', fp);
      fprintf (fp, "</a> ");
      if (f->type == FT_PLAINFILE)
	fprintf (fp, _(" (%s bytes)"), legible (f->size));
      else if (f->type == FT_SYMLINK)
	fprintf (fp, "-> %s", f->linkto ? f->linkto : "(nil)");
      putc ('\n', fp);
      free (htclfile);
      f = f->next;
    }
  fprintf (fp, "</pre>\n</body>\n</html>\n");
  free (upwd);
  if (!opt.dfp)
    fclose (fp);
  else
    fflush (fp);
  return FTPOK;
}
Example #25
0
int pinsys_init(void)
{
	signal_length = (drv.code_length + (drv.code_length / BITS_COUNT) * 2) * 1000000 / 1200;

	if (!tty_create_lock(drv.device)) {
		logprintf(LIRC_ERROR, "could not create lock files");
		return 0;
	}
	drv.fd = open(drv.device, O_RDWR | O_NONBLOCK | O_NOCTTY);
	if (drv.fd < 0) {
		int detected;
		/* last character gets overwritten */
		static char auto_lirc_device[] = "/dev/ttyS_";

		tty_delete_lock();
		logprintf(LIRC_WARNING, "could not open %s, autodetecting on /dev/ttyS[0-3]", drv.device);
		logperror(LIRC_WARNING, "pinsys_init()");
		/* it can also mean you compiled serial support as a
		 * module and it isn't inserted, but that's unlikely
		 * unless you're me. */

		detected = autodetect();

		if (detected == -1) {
			logprintf(LIRC_ERROR, "no device found on /dev/ttyS[0-3]");
			tty_delete_lock();
			return 0;
		}
		/* Detected. */
		auto_lirc_device[9] = '0' + detected;
		drv.device = auto_lirc_device;
		drv.fd = open(drv.device, O_RDWR | O_NONBLOCK | O_NOCTTY);
		if (drv.fd  < 0) {
			/* unlikely, but hey. */
			logprintf(LIRC_ERROR, "couldn't open autodetected device \"%s\"", drv.device);
			logperror(LIRC_ERROR, "pinsys_init()");
			tty_delete_lock();
			return 0;
		}
	}
	if (!tty_reset(drv.fd)) {
		logprintf(LIRC_ERROR, "could not reset tty");
		pinsys_deinit();
		return 0;
	}
	if (!tty_setbaud(drv.fd, 1200)) {
		logprintf(LIRC_ERROR, "could not set baud rate");
		pinsys_deinit();
		return 0;
	}
	/* set RTS, clear DTR */
	if (!tty_set(drv.fd, 1, 0) || !tty_clear(drv.fd, 0, 1)) {
		logprintf(LIRC_ERROR, "could not set modem lines (DTR/RTS)");
		pinsys_deinit();
		return 0;
	}

	/* I dunno, but when lircd starts may log `reading of byte 1
	 * failed' I know that happened when testing, it's a zero
	 * byte. Problem is, flushing doesn't fix it. It's not fatal,
	 * it's an indication that it gets fixed.  still... */

	if (tcflush(drv.fd, TCIFLUSH) < 0) {
		logprintf(LIRC_ERROR, "could not flush input buffer");
		pinsys_deinit();
		return 0;
	}
	return 1;
}
Example #26
0
void CRcon::Packet_ConnectionLost(Packet* pPacket)
{
	in_addr in;
	in.s_addr = pPacket->playerId.binaryAddress;
	logprintf("[RCON] Admin [%s] has lost connection.", inet_ntoa(in));
}
Example #27
0
void protocol_init(void) {
	logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

	#include "433.92/protocol_init.h"
	#include "API/protocol_init.h"
	#include "generic/protocol_init.h"
	#include "GPIO/protocol_init.h"
	#include "network/protocol_init.h"
	#include "core/protocol_init.h"

#ifndef _WIN32
	void *handle = NULL;
	void (*init)(void);
	void (*compatibility)(struct module_t *module);
	char path[PATH_MAX];
	struct module_t module;
	char pilight_version[strlen(PILIGHT_VERSION)+1];
	char pilight_commit[3];
	char *protocol_root = NULL;
	int check1 = 0, check2 = 0, valid = 1, protocol_root_free = 0;
	strcpy(pilight_version, PILIGHT_VERSION);

	struct dirent *file = NULL;
	DIR *d = NULL;
	struct stat s;

	memset(pilight_commit, '\0', 3);

	if(settings_find_string("protocol-root", &protocol_root) != 0) {
		/* If no protocol root was set, use the default protocol root */
		if((protocol_root = MALLOC(strlen(PROTOCOL_ROOT)+1)) == NULL) {
			fprintf(stderr, "out of memory\n");
			exit(EXIT_FAILURE);
		}
		strcpy(protocol_root, PROTOCOL_ROOT);
		protocol_root_free = 1;
	}
	size_t len = strlen(protocol_root);
	if(protocol_root[len-1] != '/') {
		strcat(protocol_root, "/");
	}

	if((d = opendir(protocol_root))) {
		while((file = readdir(d)) != NULL) {
			memset(path, '\0', PATH_MAX);
			sprintf(path, "%s%s", protocol_root, file->d_name);
			if(stat(path, &s) == 0) {
				/* Check if file */
				if(S_ISREG(s.st_mode)) {
					if(strstr(file->d_name, ".so") != NULL) {
						valid = 1;
						if((handle = dso_load(path)) != NULL) {

							init = dso_function(handle, "init");
							compatibility = dso_function(handle, "compatibility");
							if(init != NULL && compatibility != NULL) {
								compatibility(&module);
								if(module.name != NULL && module.version != NULL && module.reqversion != NULL) {
									char ver[strlen(module.reqversion)+1];
									strcpy(ver, module.reqversion);

									if((check1 = vercmp(ver, pilight_version)) > 0) {
										valid = 0;
									}

									if(check1 == 0 && module.reqcommit != NULL) {
										char com[strlen(module.reqcommit)+1];
										strcpy(com, module.reqcommit);
										sscanf(HASH, "v%*[0-9].%*[0-9]-%[0-9]-%*[0-9a-zA-Z\n\r]", pilight_commit);

										if(strlen(pilight_commit) > 0 && (check2 = vercmp(com, pilight_commit)) > 0) {
											valid = 0;
										}
									}
									if(valid == 1) {
										char tmp[strlen(module.name)+1];
										strcpy(tmp, module.name);
										protocol_remove(tmp);
										init();
										logprintf(LOG_DEBUG, "loaded protocol %s v%s", file->d_name, module.version);
									} else {
										if(module.reqcommit != NULL) {
											logprintf(LOG_ERR, "protocol %s requires at least pilight v%s (commit %s)", file->d_name, module.reqversion, module.reqcommit);
										} else {
											logprintf(LOG_ERR, "protocol %s requires at least pilight v%s", file->d_name, module.reqversion);
										}
									}
								} else {
									logprintf(LOG_ERR, "invalid module %s", file->d_name);
								}
							}
						}
					}
				}
			} else {
				perror("stat");
			}
		}
		closedir(d);
	}
	if(protocol_root_free) {
		FREE(protocol_root);
	}
#endif
}
Example #28
0
bool
ssl_check_certificate (int fd, const char *host)
{
  X509 *cert;
  GENERAL_NAMES *subjectAltNames;
  char common_name[256];
  long vresult;
  bool success = true;
  bool alt_name_checked = false;

  /* If the user has specified --no-check-cert, we still want to warn
     him about problems with the server's certificate.  */
  const char *severity = opt.check_cert ? _("ERROR") : _("WARNING");

  struct openssl_transport_context *ctx = fd_transport_context (fd);
  SSL *conn = ctx->conn;
  assert (conn != NULL);

  cert = SSL_get_peer_certificate (conn);
  if (!cert)
    {
      logprintf (LOG_NOTQUIET, _("%s: No certificate presented by %s.\n"),
                 severity, quotearg_style (escape_quoting_style, host));
      success = false;
      goto no_cert;             /* must bail out since CERT is NULL */
    }

  IF_DEBUG
    {
      char *subject = _get_rfc2253_formatted (X509_get_subject_name (cert));
      char *issuer = _get_rfc2253_formatted (X509_get_issuer_name (cert));
      DEBUGP (("certificate:\n  subject: %s\n  issuer:  %s\n",
               quotearg_n_style (0, escape_quoting_style, subject),
               quotearg_n_style (1, escape_quoting_style, issuer)));
      xfree (subject);
      xfree (issuer);
    }

  vresult = SSL_get_verify_result (conn);
  if (vresult != X509_V_OK)
    {
      char *issuer = _get_rfc2253_formatted (X509_get_issuer_name (cert));
      logprintf (LOG_NOTQUIET,
                 _("%s: cannot verify %s's certificate, issued by %s:\n"),
                 severity, quotearg_n_style (0, escape_quoting_style, host),
                 quote_n (1, issuer));
      xfree(issuer);

      /* Try to print more user-friendly (and translated) messages for
         the frequent verification errors.  */
      switch (vresult)
        {
        case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
          logprintf (LOG_NOTQUIET,
                     _("  Unable to locally verify the issuer's authority.\n"));
          break;
        case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
        case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
          logprintf (LOG_NOTQUIET,
                     _("  Self-signed certificate encountered.\n"));
          break;
        case X509_V_ERR_CERT_NOT_YET_VALID:
          logprintf (LOG_NOTQUIET, _("  Issued certificate not yet valid.\n"));
          break;
        case X509_V_ERR_CERT_HAS_EXPIRED:
          logprintf (LOG_NOTQUIET, _("  Issued certificate has expired.\n"));
          break;
        default:
          /* For the less frequent error strings, simply provide the
             OpenSSL error message.  */
          logprintf (LOG_NOTQUIET, "  %s\n",
                     X509_verify_cert_error_string (vresult));
        }
      success = false;
      /* Fall through, so that the user is warned about *all* issues
         with the cert (important with --no-check-certificate.)  */
    }

  /* Check that HOST matches the common name in the certificate.
     #### The following remains to be done:

     - When matching against common names, it should loop over all
       common names and choose the most specific one, i.e. the last
       one, not the first one, which the current code picks.

     - Ensure that ASN1 strings from the certificate are encoded as
       UTF-8 which can be meaningfully compared to HOST.  */

  subjectAltNames = X509_get_ext_d2i (cert, NID_subject_alt_name, NULL, NULL);

  if (subjectAltNames)
    {
      /* Test subject alternative names */

      /* Do we want to check for dNSNAmes or ipAddresses (see RFC 2818)?
       * Signal it by host_in_octet_string. */
      ASN1_OCTET_STRING *host_in_octet_string = a2i_IPADDRESS (host);

      int numaltnames = sk_GENERAL_NAME_num (subjectAltNames);
      int i;
      for (i=0; i < numaltnames; i++)
        {
          const GENERAL_NAME *name =
            sk_GENERAL_NAME_value (subjectAltNames, i);
          if (name)
            {
              if (host_in_octet_string)
                {
                  if (name->type == GEN_IPADD)
                    {
                      /* Check for ipAddress */
                      /* TODO: Should we convert between IPv4-mapped IPv6
                       * addresses and IPv4 addresses? */
                      alt_name_checked = true;
                      if (!ASN1_STRING_cmp (host_in_octet_string,
                            name->d.iPAddress))
                        break;
                    }
                }
              else if (name->type == GEN_DNS)
                {
                  /* dNSName should be IA5String (i.e. ASCII), however who
                   * does trust CA? Convert it into UTF-8 for sure. */
                  unsigned char *name_in_utf8 = NULL;

                  /* Check for dNSName */
                  alt_name_checked = true;

                  if (0 <= ASN1_STRING_to_UTF8 (&name_in_utf8, name->d.dNSName))
                    {
                      /* Compare and check for NULL attack in ASN1_STRING */
                      if (pattern_match ((char *)name_in_utf8, host) &&
                            (strlen ((char *)name_in_utf8) ==
                                (size_t) ASN1_STRING_length (name->d.dNSName)))
                        {
                          OPENSSL_free (name_in_utf8);
                          break;
                        }
                      OPENSSL_free (name_in_utf8);
                    }
                }
            }
        }
      sk_GENERAL_NAME_pop_free(subjectAltNames, GENERAL_NAME_free);
      if (host_in_octet_string)
        ASN1_OCTET_STRING_free(host_in_octet_string);

      if (alt_name_checked == true && i >= numaltnames)
        {
          logprintf (LOG_NOTQUIET,
              _("%s: no certificate subject alternative name matches\n"
                "\trequested host name %s.\n"),
                     severity, quote_n (1, host));
          success = false;
        }
    }

  if (alt_name_checked == false)
    {
      /* Test commomName */
      X509_NAME *xname = X509_get_subject_name(cert);
      common_name[0] = '\0';
      X509_NAME_get_text_by_NID (xname, NID_commonName, common_name,
                                 sizeof (common_name));

      if (!pattern_match (common_name, host))
        {
          logprintf (LOG_NOTQUIET, _("\
    %s: certificate common name %s doesn't match requested host name %s.\n"),
                     severity, quote_n (0, common_name), quote_n (1, host));
          success = false;
        }
Example #29
0
static void parseopts(int argc, char *argv[])
{
	static const struct option long_options[] = {
		{ "config", 1, 0, 'c' },
		{ "syslog", 0, 0, 's' },
		{ "nosimd", 0, 0, 'S' },
		{ "daemonize", 0, 0, 'D' },
		{ 0, 0, 0, 0 }
	};
	char *configname = NULL, *cfgname, *filename = "/etc/ax25/soundmodem.conf";
	unsigned int verblevel = 2, tosyslog = 0, simd = 1, schedrr = 0, lockmem = 0, daemonize = 0;
        int c, err = 0;
	xmlDocPtr doc;
	xmlNodePtr node;
        int pfds[2];
	pid_t pid;
	unsigned char uch;	

        while ((c = getopt_long(argc, argv, "v:sSc:RD" MLOCKOPT, long_options, NULL)) != EOF) {
                switch (c) {
                case 'v':
                        verblevel = strtoul(optarg, NULL, 0);
                        break;

		case 's':
			tosyslog = 1;
			break;

		case 'S':
			simd = 0;
			break;

		case 'c':
			configname = optarg;
			break;

                case 'R':
                        schedrr = 1;
                        break;

#ifdef HAVE_MLOCKALL
                case 'M':
                        lockmem = 1;
                        break;
#endif /* HAVE_MLOCKALL */

		case 'D':
			daemonize = 1;
			break;

                default:
                        err++;
                        break;
                }
        }
	if (err) {
                fprintf(stderr, "usage: [-v <verblevel>] [-s] [-S] [-R]" MLOCKHLP " [-c <configname>] <configfile>\n");
                exit(1);
        }
	loginit(verblevel, tosyslog);
	if (daemonize) {
		if (pipe(pfds))
			logerr(MLOG_FATAL, "pipe");
		switch (pid = fork()) {
		case -1:
			logerr(MLOG_FATAL, "fork");

		case 0: /* child process */
			close(pfds[0]);
			setsid(); /* become a process group leader and drop controlling terminal */
			fclose(stdin); /* no more standard in */
			break;
			
		default: /* parent process */
			close(pfds[1]);
			err = read(pfds[0], &uch, sizeof(uch));
			if (err != sizeof(uch))
				logprintf(MLOG_FATAL, "SoundModem init failed\n");
			exit(0);
		}
        }
	initsimd(simd);
#if 0
	if (optind >= argc)
		logprintf(MLOG_FATAL, "no configuration file specified\n");
#endif
        if (optind < argc)
                filename = argv[optind];
	doc = xmlParseFile(filename);
	if (!doc || !doc->children || !doc->children->name)
		logprintf(MLOG_FATAL, "Error parsing config file \"%s\"\n", filename);
	if (strcmp(doc->children->name, "modem"))
		logprintf(MLOG_FATAL, "Config file does not contain modem data\n");
	for (node = doc->children->children; node; node = node->next) {
		if (!node->name || strcmp(node->name, "configuration"))
			continue;
		if (!configname)
			break;
		cfgname = xmlGetProp(node, "name");
		if (cfgname && !strcmp(cfgname, configname))
			break;
	}
	if (!node)
		logprintf(MLOG_FATAL, "Configuartion not found\n");
	if (!node->children)
		logprintf(MLOG_FATAL, "Configuration empty\n");
	err = parsecfg(doc, node->children, &state, &schedrr);
	xmlFreeDoc(doc);
	if (err)
		exit(1);
        /*
         * lock memory down
         */
#ifdef HAVE_MLOCKALL
        if (lockmem) {
                if (mlockall(MCL_CURRENT | MCL_FUTURE) == -1) 
                        logerr(MLOG_ERROR, "mlockall");
        }
#endif /* HAVE_MLOCKALL */
#ifdef HAVE_SCHED_H
        if (schedrr) {
                struct sched_param schp;
                memset(&schp, 0, sizeof(schp));
                schp.sched_priority = sched_get_priority_min(SCHED_RR)+1;
                if (sched_setscheduler(0, SCHED_RR, &schp) != 0)
                        logerr(MLOG_ERROR, "sched_setscheduler");
        }
#endif /* HAVE_SCHED_H */
	if (daemonize) {
		uch = 0;
		if (write(pfds[1], &uch, sizeof(uch)) != sizeof(uch))
                        logerr(MLOG_ERROR, "write");
                close(pfds[1]);
	}
}
Example #30
-1
bool
ssl_init (void)
{
  SSL_METHOD const *meth;
  long ssl_options = 0;

#if OPENSSL_VERSION_NUMBER >= 0x00907000
  if (ssl_true_initialized == 0)
    {
      OPENSSL_config (NULL);
      ssl_true_initialized = 1;
    }
#endif

  if (ssl_ctx)
    /* The SSL has already been initialized. */
    return true;

  /* Init the PRNG.  If that fails, bail out.  */
  init_prng ();
  if (RAND_status () != 1)
    {
      logprintf (LOG_NOTQUIET,
                 _("Could not seed PRNG; consider using --random-file.\n"));
      goto error;
    }

#if OPENSSL_VERSION_NUMBER >= 0x00907000
  OPENSSL_load_builtin_modules();
  ENGINE_load_builtin_engines();
  CONF_modules_load_file(NULL, NULL,
      CONF_MFLAGS_DEFAULT_SECTION|CONF_MFLAGS_IGNORE_MISSING_FILE);
#endif
  SSL_library_init ();
  SSL_load_error_strings ();
  SSLeay_add_all_algorithms ();
  SSLeay_add_ssl_algorithms ();

  switch (opt.secure_protocol)
    {
#ifndef OPENSSL_NO_SSL2
    case secure_protocol_sslv2:
      meth = SSLv2_client_method ();
      break;
#endif

#ifndef OPENSSL_NO_SSL3
    case secure_protocol_sslv3:
      meth = SSLv3_client_method ();
      break;
#endif

    case secure_protocol_auto:
    case secure_protocol_pfs:
      meth = SSLv23_client_method ();
      ssl_options |= SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
      break;
    case secure_protocol_tlsv1:
      meth = TLSv1_client_method ();
      break;

#if OPENSSL_VERSION_NUMBER >= 0x10001000
    case secure_protocol_tlsv1_1:
      meth = TLSv1_1_client_method ();
      break;

    case secure_protocol_tlsv1_2:
      meth = TLSv1_2_client_method ();
      break;
#else
    case secure_protocol_tlsv1_1:
      logprintf (LOG_NOTQUIET, _("Your OpenSSL version is too old to support TLSv1.1\n"));
      goto error;

    case secure_protocol_tlsv1_2:
      logprintf (LOG_NOTQUIET, _("Your OpenSSL version is too old to support TLSv1.2\n"));
      goto error;
#endif

    default:
      logprintf (LOG_NOTQUIET, _("OpenSSL: unimplemented 'secure-protocol' option value %d\n"), opt.secure_protocol);
      logprintf (LOG_NOTQUIET, _("Please report this issue to [email protected]\n"));
      abort ();
    }

  /* The type cast below accommodates older OpenSSL versions (0.9.8)
     where SSL_CTX_new() is declared without a "const" argument. */
  ssl_ctx = SSL_CTX_new ((SSL_METHOD *)meth);
  if (!ssl_ctx)
    goto error;

  if (ssl_options)
    SSL_CTX_set_options (ssl_ctx, ssl_options);

  /* OpenSSL ciphers: https://www.openssl.org/docs/apps/ciphers.html
   * Since we want a good protection, we also use HIGH (that excludes MD4 ciphers and some more)
   */
  if (opt.secure_protocol == secure_protocol_pfs)
    SSL_CTX_set_cipher_list (ssl_ctx, "HIGH:MEDIUM:!RC4:!SRP:!PSK:!RSA:!aNULL@STRENGTH");

  SSL_CTX_set_default_verify_paths (ssl_ctx);
  SSL_CTX_load_verify_locations (ssl_ctx, opt.ca_cert, opt.ca_directory);

  if (opt.crl_file)
    {
      X509_STORE *store = SSL_CTX_get_cert_store (ssl_ctx);
      X509_LOOKUP *lookup;

      if (!(lookup = X509_STORE_add_lookup (store, X509_LOOKUP_file ()))
          || (!X509_load_crl_file (lookup, opt.crl_file, X509_FILETYPE_PEM)))
        goto error;

      X509_STORE_set_flags (store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
    }

  /* SSL_VERIFY_NONE instructs OpenSSL not to abort SSL_connect if the
     certificate is invalid.  We verify the certificate separately in
     ssl_check_certificate, which provides much better diagnostics
     than examining the error stack after a failed SSL_connect.  */
  SSL_CTX_set_verify (ssl_ctx, SSL_VERIFY_NONE, NULL);

  /* Use the private key from the cert file unless otherwise specified. */
  if (opt.cert_file && !opt.private_key)
    {
      opt.private_key = opt.cert_file;
      opt.private_key_type = opt.cert_type;
    }

  if (opt.cert_file)
    if (SSL_CTX_use_certificate_file (ssl_ctx, opt.cert_file,
                                      key_type_to_ssl_type (opt.cert_type))
        != 1)
      goto error;
  if (opt.private_key)
    if (SSL_CTX_use_PrivateKey_file (ssl_ctx, opt.private_key,
                                     key_type_to_ssl_type (opt.private_key_type))
        != 1)
      goto error;

  /* Since fd_write unconditionally assumes partial writes (and
     handles them correctly), allow them in OpenSSL.  */
  SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);

  /* The OpenSSL library can handle renegotiations automatically, so
     tell it to do so.  */
  SSL_CTX_set_mode (ssl_ctx, SSL_MODE_AUTO_RETRY);

  return true;

 error:
  if (ssl_ctx)
    SSL_CTX_free (ssl_ctx);
  print_errors ();
  return false;
}