コード例 #1
0
ファイル: httptest.c プロジェクト: tjyang/cpam
void add_http_test(testitem_t *t)
{
	http_data_t *httptest;

	char *dnsip = NULL;
	ssloptions_t *sslopt = NULL;
	char *sslopt_ciphers = NULL;
	int sslopt_version = SSLVERSION_DEFAULT;
	char *sslopt_clientcert = NULL;
	int  httpversion = HTTPVER_11;
	cookielist_t *ck = NULL;
	int firstcookie = 1;
	char *decodedurl;
	strbuffer_t *httprequest = newstrbuffer(0);

	/* Allocate the private data and initialize it */
	httptest = (http_data_t *) calloc(1, sizeof(http_data_t));
	t->privdata = (void *) httptest;

	decodedurl = decode_url(t->testspec, &httptest->weburl);
	if (!decodedurl) {
		errprintf("Invalid URL for http check: %s\n", t->testspec);
		return;
	}

	httptest->url = strdup(decodedurl);
	httptest->contlen = -1;
	httptest->parsestatus = (httptest->weburl.proxyurl ? httptest->weburl.proxyurl->parseerror : httptest->weburl.desturl->parseerror);

	/* If there was a parse error in the URL, dont run the test */
	if (httptest->parsestatus) return;


	if (httptest->weburl.proxyurl && (httptest->weburl.proxyurl->ip == NULL)) {
		dnsip = dnsresolve(httptest->weburl.proxyurl->host);
		if (dnsip) {
			httptest->weburl.proxyurl->ip = strdup(dnsip);
		}
		else {
			dbgprintf("Could not resolve URL hostname '%s'\n", httptest->weburl.proxyurl->host);
		}
	}
	else if (httptest->weburl.desturl->ip == NULL) {
		dnsip = dnsresolve(httptest->weburl.desturl->host);
		if (dnsip) {
			httptest->weburl.desturl->ip = strdup(dnsip);
		}
		else {
			dbgprintf("Could not resolve URL hostname '%s'\n", httptest->weburl.desturl->host);
		}
	}

	switch (httptest->weburl.testtype) {
	  case WEBTEST_PLAIN:
	  case WEBTEST_STATUS:
		httptest->contentcheck = CONTENTCHECK_NONE;
		break;

	  case WEBTEST_CONTENT:
		{
			FILE *contentfd;
			char contentfn[PATH_MAX];
			sprintf(contentfn, "%s/content/%s.substring", xgetenv("XYMONHOME"), commafy(t->host->hostname));
			contentfd = fopen(contentfn, "r");
			if (contentfd) {
				char l[MAX_LINE_LEN];
				char *p;

				if (fgets(l, sizeof(l), contentfd)) {
					p = strchr(l, '\n'); if (p) { *p = '\0'; };
					httptest->weburl.expdata = strdup(l);
				}
				else {
					httptest->contstatus = STATUS_CONTENTMATCH_NOFILE;
				}
				fclose(contentfd);
			}
			else {
				httptest->contstatus = STATUS_CONTENTMATCH_NOFILE;
			}
			httptest->contentcheck = CONTENTCHECK_REGEX;
		}
		break;

	  case WEBTEST_CONT:
		httptest->contentcheck = ((*httptest->weburl.expdata == '#') ?  CONTENTCHECK_DIGEST : CONTENTCHECK_REGEX);
		break;

	  case WEBTEST_NOCONT:
		httptest->contentcheck = CONTENTCHECK_NOREGEX;
		break;

	  case WEBTEST_POST:
	  case WEBTEST_SOAP:
		if (httptest->weburl.expdata == NULL) {
			httptest->contentcheck = CONTENTCHECK_NONE;
		}
		else {
			httptest->contentcheck = ((*httptest->weburl.expdata == '#') ?  CONTENTCHECK_DIGEST : CONTENTCHECK_REGEX);
		}
		break;

	  case WEBTEST_NOPOST:
	  case WEBTEST_NOSOAP:
		if (httptest->weburl.expdata == NULL) {
			httptest->contentcheck = CONTENTCHECK_NONE;
		}
		else {
			httptest->contentcheck = CONTENTCHECK_NOREGEX;
		}
		break;

	  case WEBTEST_TYPE:
		httptest->contentcheck = CONTENTCHECK_CONTENTTYPE;
		break;
	}

	/* Compile the hashes and regex's for those tests that use it */
	switch (httptest->contentcheck) {
	  case CONTENTCHECK_DIGEST:
		{
			char *hashfunc;

			httptest->exp = (void *) strdup(httptest->weburl.expdata+1);
			hashfunc = strchr(httptest->exp, ':');
			if (hashfunc) {
				*hashfunc = '\0';
				httptest->digestctx = digest_init(httptest->exp);
				*hashfunc = ':';
			}
		}
		break;

	  case CONTENTCHECK_REGEX:
	  case CONTENTCHECK_NOREGEX:
		{
			int status;

			httptest->exp = (void *) malloc(sizeof(regex_t));
			status = regcomp((regex_t *)httptest->exp, httptest->weburl.expdata, REG_EXTENDED|REG_NOSUB);
			if (status) {
				errprintf("Failed to compile regexp '%s' for URL %s\n", httptest->weburl.expdata, httptest->url);
				httptest->contstatus = STATUS_CONTENTMATCH_BADREGEX;
			}
		}
		break;

	  case CONTENTCHECK_CONTENTTYPE:
		httptest->exp = httptest->weburl.expdata;
		break;
	}

	if (httptest->weburl.desturl->schemeopts) {
		if      (strstr(httptest->weburl.desturl->schemeopts, "3"))      sslopt_version = SSLVERSION_V3;
		else if (strstr(httptest->weburl.desturl->schemeopts, "2"))      sslopt_version = SSLVERSION_V2;

		if      (strstr(httptest->weburl.desturl->schemeopts, "h"))      sslopt_ciphers = ciphershigh;
		else if (strstr(httptest->weburl.desturl->schemeopts, "m"))      sslopt_ciphers = ciphersmedium;

		if      (strstr(httptest->weburl.desturl->schemeopts, "10"))     httpversion    = HTTPVER_10;
		else if (strstr(httptest->weburl.desturl->schemeopts, "11"))     httpversion    = HTTPVER_11;
	}

	/* Get any cookies */
	load_cookies();

	/* Generate the request */
	addtobuffer(httprequest, (httptest->weburl.postdata ? "POST " : "GET "));
	switch (httpversion) {
		case HTTPVER_10: 
			addtobuffer(httprequest, (httptest->weburl.proxyurl ? httptest->url : httptest->weburl.desturl->relurl));
			addtobuffer(httprequest, " HTTP/1.0\r\n"); 
			break;

		case HTTPVER_11: 
			/*
			 * Experience shows that even though HTTP/1.1 says you should send the
			 * full URL, some servers (e.g. SunOne App server 7) choke on it.
			 * So just send the good-old relative URL unless we're proxying.
			 */
			addtobuffer(httprequest, (httptest->weburl.proxyurl ? httptest->url : httptest->weburl.desturl->relurl));
			addtobuffer(httprequest, " HTTP/1.1\r\n"); 
			addtobuffer(httprequest, "Connection: close\r\n"); 
			break;
	}

	addtobuffer(httprequest, "Host: ");
	addtobuffer(httprequest, httptest->weburl.desturl->host);
	if ((httptest->weburl.desturl->port != 80) && (httptest->weburl.desturl->port != 443)) {
		char hostporthdr[20];

		sprintf(hostporthdr, ":%d", httptest->weburl.desturl->port);
		addtobuffer(httprequest, hostporthdr);
	}
	addtobuffer(httprequest, "\r\n");

	if (httptest->weburl.postdata) {
		char hdr[100];
		int contlen = strlen(httptest->weburl.postdata);

		if (strncmp(httptest->weburl.postdata, "file:", 5) == 0) {
			/* Load the POST data from a file */
			FILE *pf = fopen(httptest->weburl.postdata+5, "r");
			if (pf == NULL) {
				errprintf("Cannot open POST data file %s\n", httptest->weburl.postdata+5);
				xfree(httptest->weburl.postdata);
				httptest->weburl.postdata = strdup("");
				contlen = 0;
			}
			else {
				struct stat st;

				if (fstat(fileno(pf), &st) == 0) {
					int n;

					xfree(httptest->weburl.postdata);
					httptest->weburl.postdata = (char *)malloc(st.st_size + 1); *(httptest->weburl.postdata) = '\0';
					n = fread(httptest->weburl.postdata, 1, st.st_size, pf);
					if (n == st.st_size) {
						*(httptest->weburl.postdata+n) = '\0';
						contlen = n;
					}
					else {
						errprintf("Cannot read file %s: %s\n", httptest->weburl.postdata+5, strerror(errno));
						contlen = 0;
					}
				}
				else {
					errprintf("Cannot stat file %s\n", httptest->weburl.postdata+5);
					httptest->weburl.postdata = strdup("");
					contlen = 0;
				}

				fclose(pf);
			}
		}

		addtobuffer(httprequest, "Content-type: ");
		if      (httptest->weburl.postcontenttype) 
			addtobuffer(httprequest, httptest->weburl.postcontenttype);
		else if ((httptest->weburl.testtype == WEBTEST_SOAP) || (httptest->weburl.testtype == WEBTEST_NOSOAP)) 
			addtobuffer(httprequest, "application/soap+xml; charset=utf-8");
		else 
			addtobuffer(httprequest, "application/x-www-form-urlencoded");
		addtobuffer(httprequest, "\r\n");

		sprintf(hdr, "Content-Length: %d\r\n", contlen);
		addtobuffer(httprequest, hdr);
	}
	{
		char useragent[100];
		void *hinfo;
		char *browser = NULL;

		hinfo = hostinfo(t->host->hostname);
		if (hinfo) browser = xmh_item(hinfo, XMH_BROWSER);

		if (browser) {
			sprintf(useragent, "User-Agent: %s\r\n", browser);
		}
		else {
			sprintf(useragent, "User-Agent: Xymon xymonnet/%s\r\n", VERSION);
		}

		addtobuffer(httprequest, useragent);
	}
	if (httptest->weburl.desturl->auth) {
		if (strncmp(httptest->weburl.desturl->auth, "CERT:", 5) == 0) {
			sslopt_clientcert = httptest->weburl.desturl->auth+5;
		}
		else {
			addtobuffer(httprequest, "Authorization: Basic ");
			addtobuffer(httprequest, base64encode(httptest->weburl.desturl->auth));
			addtobuffer(httprequest, "\r\n");
		}
	}
	if (httptest->weburl.proxyurl && httptest->weburl.proxyurl->auth) {
		addtobuffer(httprequest, "Proxy-Authorization: Basic ");
		addtobuffer(httprequest, base64encode(httptest->weburl.proxyurl->auth));
		addtobuffer(httprequest, "\r\n");
	}
	for (ck = cookiehead; (ck); ck = ck->next) {
		int useit = 0;

		if (ck->tailmatch) {
			int startpos = strlen(httptest->weburl.desturl->host) - strlen(ck->host);

			if (startpos > 0) useit = (strcmp(httptest->weburl.desturl->host+startpos, ck->host) == 0);
		}
		else useit = (strcmp(httptest->weburl.desturl->host, ck->host) == 0);
		if (useit) useit = (strncmp(ck->path, httptest->weburl.desturl->relurl, strlen(ck->path)) == 0);

		if (useit) {
			if (firstcookie) {
				addtobuffer(httprequest, "Cookie: ");
				firstcookie = 0;
			}
			addtobuffer(httprequest, ck->name);
			addtobuffer(httprequest, "=");
			addtobuffer(httprequest, ck->value);
			addtobuffer(httprequest, "\r\n");
		}
	}

	/* Some standard stuff */
	addtobuffer(httprequest, "Accept: */*\r\n");
	addtobuffer(httprequest, "Pragma: no-cache\r\n");

	if ((httptest->weburl.testtype == WEBTEST_SOAP) || (httptest->weburl.testtype == WEBTEST_NOSOAP)) {
		/* Must provide a SOAPAction header */
		addtobuffer(httprequest, "SOAPAction: ");
		addtobuffer(httprequest, httptest->url);
		addtobuffer(httprequest, "\r\n");
	}
	
	/* The final blank line terminates the headers */
	addtobuffer(httprequest, "\r\n");

	/* Post data goes last */
	if (httptest->weburl.postdata) addtobuffer(httprequest, httptest->weburl.postdata);

	/* Pickup any SSL options the user wants */
	if (sslopt_ciphers || (sslopt_version != SSLVERSION_DEFAULT) || sslopt_clientcert){
		sslopt = (ssloptions_t *) malloc(sizeof(ssloptions_t));
		sslopt->cipherlist = sslopt_ciphers;
		sslopt->sslversion = sslopt_version;
		sslopt->clientcert = sslopt_clientcert;
	}

	/* Add to TCP test queue */
	if (httptest->weburl.proxyurl == NULL) {
		httptest->tcptest = add_tcp_test(httptest->weburl.desturl->ip, 
						 httptest->weburl.desturl->port, 
						 httptest->weburl.desturl->scheme,
						 sslopt, t->srcip,
						 t->testspec, t->silenttest, grabstrbuffer(httprequest), 
						 httptest, tcp_http_data_callback, tcp_http_final_callback);
	}
	else {
		httptest->tcptest = add_tcp_test(httptest->weburl.proxyurl->ip, 
						 httptest->weburl.proxyurl->port, 
						 httptest->weburl.proxyurl->scheme,
						 sslopt, t->srcip,
						 t->testspec, t->silenttest, grabstrbuffer(httprequest), 
						 httptest, tcp_http_data_callback, tcp_http_final_callback);
	}
}
コード例 #2
0
ファイル: server.c プロジェクト: GroovIM/transport
/* Startup the server.  CTRL must have been allocated by the caller
   and set to the default values. */
int
gpg_server (ctrl_t ctrl)
{
  int rc;
  int filedes[2];
  assuan_context_t ctx = NULL;
  static const char hello[] = ("GNU Privacy Guard's OpenPGP server "
                               VERSION " ready");

  /* We use a pipe based server so that we can work from scripts.
     assuan_init_pipe_server will automagically detect when we are
     called with a socketpair and ignore FILEDES in this case.  */
  filedes[0] = assuan_fdopen (0);
  filedes[1] = assuan_fdopen (1);
  rc = assuan_new (&ctx);
  if (rc)
    {
      log_error ("failed to allocate the assuan context: %s\n",
		 gpg_strerror (rc));
      goto leave;
    }
  
  rc = assuan_init_pipe_server (ctx, filedes);
  if (rc)
    {
      log_error ("failed to initialize the server: %s\n", gpg_strerror (rc));
      goto leave;
    }

  rc = register_commands (ctx);
  if (rc)
    {
      log_error ("failed to the register commands with Assuan: %s\n",
                 gpg_strerror(rc));
      goto leave;
    }

  assuan_set_pointer (ctx, ctrl);
  if (opt.verbose || opt.debug)
    {
      char *tmp = NULL;
      const char *s1 = getenv ("GPG_AGENT_INFO");

      if (asprintf (&tmp,
                    "Home: %s\n"
                    "Config: %s\n"
                    "AgentInfo: %s\n"
                    "%s",
                    opt.homedir,
                    "fixme: need config filename",
                    s1?s1:"[not set]",
                    hello) > 0)
        {
          assuan_set_hello_line (ctx, tmp);
          free (tmp);
        }
    }
  else
    assuan_set_hello_line (ctx, hello);
  assuan_register_reset_notify (ctx, reset_notify);
  assuan_register_input_notify (ctx, input_notify);
  assuan_register_output_notify (ctx, output_notify);
  assuan_register_option_handler (ctx, option_handler);

  ctrl->server_local = xtrycalloc (1, sizeof *ctrl->server_local);
  if (!ctrl->server_local)
    {
      rc = gpg_error_from_syserror ();
      goto leave;
    }
  ctrl->server_local->assuan_ctx = ctx;
  ctrl->server_local->message_fd = GNUPG_INVALID_FD;

  if (DBG_ASSUAN)
    assuan_set_log_stream (ctx, log_get_stream ());

  for (;;)
    {
      rc = assuan_accept (ctx);
      if (rc == -1)
        {
          rc = 0;
          break;
        }
      else if (rc)
        {
          log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
          break;
        }
      
      rc = assuan_process (ctx);
      if (rc)
        {
          log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
          continue;
        }
    }

 leave:
  xfree (ctrl->server_local);
  ctrl->server_local = NULL;
  assuan_release (ctx);
  return rc;
}
コード例 #3
0
ファイル: xvdisp.c プロジェクト: aosm/X11server
static int 
ProcXvQueryImageAttributes(ClientPtr client)
{
  xvQueryImageAttributesReply rep;
  int size, num_planes, i;
  CARD16 width, height;
  XvImagePtr pImage = NULL;
  XvPortPtr pPort;
  int *offsets;
  int *pitches;
  int planeLength;
  REQUEST(xvQueryImageAttributesReq);

  REQUEST_SIZE_MATCH(xvQueryImageAttributesReq);

  if(!(pPort = LOOKUP_PORT(stuff->port, client) ))
    {
      client->errorValue = stuff->port;
      return (_XvBadPort);
    }
  
  for(i = 0; i < pPort->pAdaptor->nImages; i++) {
      if(pPort->pAdaptor->pImages[i].id == stuff->id) {
	  pImage = &(pPort->pAdaptor->pImages[i]);
	  break;
      }
  }

#ifdef XvMCExtension
  if(!pImage)
     pImage = XvMCFindXvImage(pPort, stuff->id);
#endif

  if(!pImage)
     return BadMatch;

  num_planes = pImage->num_planes;

  if(!(offsets = xalloc(num_planes << 3)))
	return BadAlloc;
  pitches = offsets + num_planes;

  width = stuff->width;
  height = stuff->height;

  size = (*pPort->pAdaptor->ddQueryImageAttributes)(client, pPort, pImage,
					&width, &height, offsets, pitches);

  rep.type = X_Reply;
  rep.sequenceNumber = client->sequence;
  rep.length = planeLength = num_planes << 1;
  rep.num_planes = num_planes;
  rep.width = width;
  rep.height = height;
  rep.data_size = size;
 
  _WriteQueryImageAttributesReply(client, &rep);
  if(client->swapped)
    SwapLongs((CARD32*)offsets, planeLength);
  WriteToClient(client, planeLength << 2, (char*)offsets);

  xfree(offsets);

  return Success;
}
コード例 #4
0
ファイル: allocate.c プロジェクト: IFCA/slurm
/*
 * Create job description structure based off srun options
 * (see opt.h)
 */
job_desc_msg_t *
job_desc_msg_create_from_opts (void)
{
	job_desc_msg_t *j = xmalloc(sizeof(*j));
	hostlist_t hl = NULL;

	slurm_init_job_desc_msg(j);
#ifdef HAVE_REAL_CRAY
	uint64_t pagg_id = job_getjid(getpid());
	/*
	 * Interactive sessions require pam_job.so in /etc/pam.d/common-session
	 * since creating sgi_job containers requires root permissions. This is
	 * the only exception where we allow the fallback of using the SID to
	 * confirm the reservation (caught later, in do_basil_confirm).
	 */
	if (pagg_id == (uint64_t)-1) {
		error("No SGI job container ID detected - please enable the "
		      "Cray job service via /etc/init.d/job");
	} else {
		if (!j->select_jobinfo)
			j->select_jobinfo = select_g_select_jobinfo_alloc();

		select_g_select_jobinfo_set(j->select_jobinfo,
					    SELECT_JOBDATA_PAGG_ID, &pagg_id);
	}
#endif

	j->contiguous     = opt.contiguous;
	j->features       = opt.constraints;
	j->gres           = opt.gres;
	if (opt.immediate == 1)
		j->immediate = opt.immediate;
	if (opt.job_name)
		j->name   = opt.job_name;
	else
		j->name   = opt.cmd_name;
	if (opt.argc > 0) {
		j->argc    = 1;
		j->argv    = (char **) xmalloc(sizeof(char *) * 2);
		j->argv[0] = xstrdup(opt.argv[0]);
	}
	if (opt.acctg_freq >= 0)
		j->acctg_freq     = opt.acctg_freq;
	j->reservation    = opt.reservation;
	j->wckey          = opt.wckey;

	j->req_nodes      = xstrdup(opt.nodelist);

	/* simplify the job allocation nodelist,
	 * not laying out tasks until step */
	if (j->req_nodes) {
		hl = hostlist_create(j->req_nodes);
		xfree(opt.nodelist);
		opt.nodelist = hostlist_ranged_string_xmalloc(hl);
		hostlist_uniq(hl);
		xfree(j->req_nodes);
		j->req_nodes = hostlist_ranged_string_xmalloc(hl);
		hostlist_destroy(hl);

	}

	if (opt.distribution == SLURM_DIST_ARBITRARY
	   && !j->req_nodes) {
		error("With Arbitrary distribution you need to "
		      "specify a nodelist or hostfile with the -w option");
		return NULL;
	}
	j->exc_nodes      = opt.exc_nodes;
	j->partition      = opt.partition;
	j->min_nodes      = opt.min_nodes;
	if (opt.sockets_per_node != NO_VAL)
		j->sockets_per_node    = opt.sockets_per_node;
	if (opt.cores_per_socket != NO_VAL)
		j->cores_per_socket      = opt.cores_per_socket;
	if (opt.threads_per_core != NO_VAL)
		j->threads_per_core    = opt.threads_per_core;
	j->user_id        = opt.uid;
	j->dependency     = opt.dependency;
	if (opt.nice)
		j->nice   = NICE_OFFSET + opt.nice;

	if (opt.cpu_bind)
		j->cpu_bind       = opt.cpu_bind;
	if (opt.cpu_bind_type)
		j->cpu_bind_type  = opt.cpu_bind_type;
	if (opt.mem_bind)
		j->mem_bind       = opt.mem_bind;
	if (opt.mem_bind_type)
		j->mem_bind_type  = opt.mem_bind_type;
	if (opt.plane_size != NO_VAL)
		j->plane_size     = opt.plane_size;
	j->task_dist      = opt.distribution;

	j->group_id       = opt.gid;
	j->mail_type      = opt.mail_type;

	if (opt.ntasks_per_node != NO_VAL)
		j->ntasks_per_node   = opt.ntasks_per_node;
	if (opt.ntasks_per_socket != NO_VAL)
		j->ntasks_per_socket = opt.ntasks_per_socket;
	if (opt.ntasks_per_core != NO_VAL)
		j->ntasks_per_core   = opt.ntasks_per_core;

	if (opt.mail_user)
		j->mail_user = opt.mail_user;
	if (opt.begin)
		j->begin_time = opt.begin;
	if (opt.licenses)
		j->licenses = opt.licenses;
	if (opt.network)
		j->network = opt.network;
	if (opt.account)
		j->account = opt.account;
	if (opt.comment)
		j->comment = opt.comment;
	if (opt.qos)
		j->qos = opt.qos;
	if (opt.cwd)
		j->work_dir = opt.cwd;

	if (opt.hold)
		j->priority     = 0;
	if (opt.jobid != NO_VAL)
		j->job_id	= opt.jobid;
#ifdef HAVE_BG
	if (opt.geometry[0] > 0) {
		int i;
		for (i = 0; i < SYSTEM_DIMENSIONS; i++)
			j->geometry[i] = opt.geometry[i];
	}
#endif

	memcpy(j->conn_type, opt.conn_type, sizeof(j->conn_type));

	if (opt.reboot)
		j->reboot = 1;
	if (opt.no_rotate)
		j->rotate = 0;

	if (opt.blrtsimage)
		j->blrtsimage = opt.blrtsimage;
	if (opt.linuximage)
		j->linuximage = opt.linuximage;
	if (opt.mloaderimage)
		j->mloaderimage = opt.mloaderimage;
	if (opt.ramdiskimage)
		j->ramdiskimage = opt.ramdiskimage;

	if (opt.max_nodes)
		j->max_nodes    = opt.max_nodes;
	else if (opt.nodes_set) {
		/* On an allocation if the max nodes isn't set set it
		 * to do the same behavior as with salloc or sbatch.
		 */
		j->max_nodes    = opt.min_nodes;
	}
	if (opt.pn_min_cpus != NO_VAL)
		j->pn_min_cpus    = opt.pn_min_cpus;
	if (opt.pn_min_memory != NO_VAL)
		j->pn_min_memory = opt.pn_min_memory;
	else if (opt.mem_per_cpu != NO_VAL)
		j->pn_min_memory = opt.mem_per_cpu | MEM_PER_CPU;
	if (opt.pn_min_tmp_disk != NO_VAL)
		j->pn_min_tmp_disk = opt.pn_min_tmp_disk;
	if (opt.overcommit) {
		j->min_cpus    = opt.min_nodes;
		j->overcommit  = opt.overcommit;
	} else if (opt.cpus_set)
		j->min_cpus    = opt.ntasks * opt.cpus_per_task;
	else
		j->min_cpus    = opt.ntasks;
	if (opt.ntasks_set)
		j->num_tasks   = opt.ntasks;

	if (opt.cpus_set)
		j->cpus_per_task = opt.cpus_per_task;

	if (opt.no_kill)
		j->kill_on_node_fail   = 0;
	if (opt.time_limit != NO_VAL)
		j->time_limit          = opt.time_limit;
	if (opt.time_min != NO_VAL)
		j->time_min            = opt.time_min;
	j->shared = opt.shared;

	if (opt.warn_signal)
		j->warn_signal = opt.warn_signal;
	if (opt.warn_time)
		j->warn_time = opt.warn_time;

	if (opt.req_switch >= 0)
		j->req_switch = opt.req_switch;
	if (opt.wait4switch >= 0)
		j->wait4switch = opt.wait4switch;

	/* srun uses the same listening port for the allocation response
	 * message as all other messages */
	j->alloc_resp_port = slurmctld_comm_addr.port;
	j->other_port = slurmctld_comm_addr.port;

	if (opt.spank_job_env_size) {
		j->spank_job_env      = opt.spank_job_env;
		j->spank_job_env_size = opt.spank_job_env_size;
	}

	return (j);
}
コード例 #5
0
ファイル: wildcards.c プロジェクト: ziirish/shelldone
int
sd_plugin_main (void **data)
{
    int i, k, argc;
    char **argv = NULL;
    void *tmp = data[0];
    command **tmpc = (command **)tmp;
    command *cmd = *tmpc;

    if (cmd->argc == 0)
        return 1;

    /* check if we are the first parser */
    unsigned int first = (cmd->argcf == 0);
    if (first)
    {
        cmd->argvf = xcalloc (cmd->argc, sizeof (char *));
        cmd->argcf = cmd->argc;
    }
    else
    {
        /* if not, copy the args because we are gonna change it a lot */
        argv = xcalloc (cmd->argcf, sizeof (char *));
        argc = cmd->argcf;
        for (i = 0; i < argc; i++)
        {
            argv[i] = xstrdup (cmd->argvf[i]);
        }
    }

    for (i = 0, k = 0; i < (first ? (cmd->argc) : (argc)); i++)
    {
        char *temp = (first ? cmd->argv[i] : argv[i]);

        escape_char (NULL, '\'');

        if (/*!(cmd->protected[i] & SINGLE_QUOTE) &&*/
            strpbrk (temp,"*?[]$`") != NULL)
        {
            wordexp_t p;
            int j;
            int r = wordexp (temp, &p, 0);
            if (r != 0)
            {
                fprintf (stderr, "shelldone: syntax error near '%s'\n",
                                 temp);

                if (!first)
                {
                    int z;
                    for (z = 0; z < argc; z++)
                        xfree (argv[z]);
                    xfree (argv);
                }

                return -1;
            }
            if (p.we_wordc == 0 || (p.we_wordc == 1 &&
                xstrcmp (p.we_wordv[0],temp) == 0))
            {
                /*
                fprintf (stderr, "shelldone: '%s' => '%s', k: %d %d\n",
                                 temp,
                                 cmd->argvf[k],
                                 k,
                                 cmd->argcf);
                */
                if (r == 0)
                    wordfree (&p);

                if (cmd->argvf[k] != NULL)
                    xfree (cmd->argvf[k]);

                cmd->argvf[k] = xmalloc (1 * sizeof (char));
                *(cmd->argvf[k]) = '\0';

                k++;

/*                return -1;*/
            }
            else if (r == 0)
            {
                int argcf = cmd->argcf;
                if (p.we_wordc > 1)
                {
                    cmd->argcf += p.we_wordc - 1;
                    cmd->argvf = xrealloc (cmd->argvf,cmd->argcf * sizeof(char *));
                }

                for (j = 0; j < (int) p.we_wordc; j++)
                {
                    char *t = xstrdup (p.we_wordv[j]);
                    if (k+j < argcf && cmd->argvf[k+j] != NULL)
                        xfree (cmd->argvf[k+j]);
                    cmd->argvf[k+j] = t;
                }
                k += j;
                wordfree (&p);
            }
        }
        else
        {
            if (first)
            {
                if (cmd->argvf[k] != NULL)
                    xfree (cmd->argvf[k]);
                cmd->argvf[k] = xstrdup (cmd->argv[i]);
            }
            k++;
        }
    }
    if (!first)
    {
        for (i = 0; i < argc; i++)
            xfree (argv[i]);
        xfree (argv);
    }
    if (first)
        cmd->argcf = k;

    return 1;
}
コード例 #6
0
ファイル: req.c プロジェクト: gyliu513/slurm
static int
_handle_attach(int fd, stepd_step_rec_t *job, uid_t uid)
{
	srun_info_t *srun;
	int rc = SLURM_SUCCESS;

	debug("_handle_attach for job %u.%u", job->jobid, job->stepid);

	srun       = xmalloc(sizeof(srun_info_t));
	srun->key  = (srun_key_t *)xmalloc(SLURM_IO_KEY_SIZE);

	debug("sizeof(srun_info_t) = %d, sizeof(slurm_addr_t) = %d",
	      (int) sizeof(srun_info_t), (int) sizeof(slurm_addr_t));
	safe_read(fd, &srun->ioaddr, sizeof(slurm_addr_t));
	safe_read(fd, &srun->resp_addr, sizeof(slurm_addr_t));
	safe_read(fd, srun->key, SLURM_IO_KEY_SIZE);

	/*
	 * Check if jobstep is actually running.
	 */
	if (job->state != SLURMSTEPD_STEP_RUNNING) {
		rc = ESLURMD_JOB_NOTRUNNING;
		goto done;
	}

	/*
	 * At the moment, it only makes sense for the slurmd to make this
	 * call, so only _slurm_authorized_user is allowed.
	 */
	if (!_slurm_authorized_user(uid)) {
		error("uid %ld attempt to attach to job %u.%u owned by %ld",
		      (long) uid, job->jobid, job->stepid, (long)job->uid);
		rc = EPERM;
		goto done;
	}

	list_prepend(job->sruns, (void *) srun);
	rc = io_client_connect(srun, job);
	debug("  back from io_client_connect, rc = %d", rc);
done:
	/* Send the return code */
	safe_write(fd, &rc, sizeof(int));

	debug("  in _handle_attach rc = %d", rc);
	if (rc == SLURM_SUCCESS) {
		/* Send response info */
		uint32_t *pids, *gtids;
		int len, i;

		debug("  in _handle_attach sending response info");
		len = job->node_tasks * sizeof(uint32_t);
		pids = xmalloc(len);
		gtids = xmalloc(len);

		if (job->task != NULL) {
			for (i = 0; i < job->node_tasks; i++) {
				if (job->task[i] == NULL)
					continue;
				pids[i] = (uint32_t)job->task[i]->pid;
				gtids[i] = job->task[i]->gtid;
			}
		}

		safe_write(fd, &job->node_tasks, sizeof(uint32_t));
		safe_write(fd, pids, len);
		safe_write(fd, gtids, len);
		xfree(pids);
		xfree(gtids);

		for (i = 0; i < job->node_tasks; i++) {
			if (job->task[i] && job->task[i]->argv) {
				len = strlen(job->task[i]->argv[0]) + 1;
				safe_write(fd, &len, sizeof(int));
				safe_write(fd, job->task[i]->argv[0], len);
			} else {
				len = 0;
				safe_write(fd, &len, sizeof(int));
			}
		}
	}

	return SLURM_SUCCESS;
rwfail:
	return SLURM_FAILURE;
}
コード例 #7
0
ファイル: in_sysctl.c プロジェクト: noushi/bmon
static void sysctl_read(void)
{
	int mib[] = {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, 0};
	size_t n;
	char *buf, *next, *lim;

	if (sysctl(mib, 6, NULL, &n, NULL, 0) < 0)
		quit("sysctl() failed");

	if (c_debug)
		fprintf(stderr, "sysctl 1-pass n=%d\n", (int) n);

	buf = xcalloc(1, n);

	if (sysctl(mib, 6, buf, &n, NULL, 0) < 0)
		quit("sysctl() failed");

	if (c_debug)
		fprintf(stderr, "sysctl 2-pass n=%d\n", (int) n);

	lim = buf + n;
	next = buf;

	while (next < lim) {
		char ifname[IFNAME_MAX];
		int iflen = sizeof(ifname) - 1;
		struct if_msghdr *ifm, *nextifm;
		struct sockaddr_dl *sdl;
		struct item *it;

		memset(ifname, 0, sizeof(ifname));

		ifm = (struct if_msghdr *) next;
		if (ifm->ifm_type != RTM_IFINFO)
			break;

		next += ifm->ifm_msglen;
		while (next < lim) {
			nextifm = (struct if_msghdr *) next;
			if (nextifm->ifm_type != RTM_NEWADDR)
				break;
			next += nextifm->ifm_msglen;
		}

		sdl = (struct sockaddr_dl *) (ifm + 1);

		if (sdl->sdl_family != AF_LINK)
			continue;

		if (cfg_show_only_running && !(ifm->ifm_flags & IFF_UP))
			continue;

		if (iflen > sd->sdl_nlen)
			iflen = sdl->sdl_nlen;

		memcpy(ifname, sdl->sdl_data, iflen);
		
		if (c_debug)
			fprintf(stderr, "Processing %s\n", ifname);

		it = lookup_item(get_local_node(), ifname, 0, 0);
		if (it == NULL)
			continue;

		set_item_attrs(it, ATTR(BYTES), ATTR(PACKETS), ATTR(BYTES));

		update_attr(it, ATTR(PACKETS),
			    ifm->ifm_data.ifi_ipackets,
			    ifm->ifm_data.ifi_opackets,
			    RX_PROVIDED | TX_PROVIDED);

		update_attr(it, ATTR(BYTES),
			    ifm->ifm_data.ifi_ibytes,
			    ifm->ifm_data.ifi_obytes,
			    RX_PROVIDED | TX_PROVIDED);

		update_attr(it, ATTR(ERRORS),
			    ifm->ifm_data.ifi_ierrors,
			    ifm->ifm_data.ifi_oerrors,
			    RX_PROVIDED | TX_PROVIDED);

		update_attr(it, ATTR(COLLISIONS),
			    0, ifm->ifm_data.ifi_collisions,
			    TX_PROVIDED);

		update_attr(it, ATTR(MULTICAST),
			    ifm->ifm_data.ifi_imcasts,
			    0,
			    RX_PROVIDED);

		update_attr(it, ATTR(DROP),
			    0,
			    ifm->ifm_data.ifi_iqdrops,
			    TX_PROVIDED);

		notify_update(it, NULL);
		increase_lifetime(it, 1);
	}

	xfree(buf);
}
コード例 #8
0
ファイル: dump-netsnmp.c プロジェクト: pan0007/libsmi
static void printHeaderTypedef(FILE *f, SmiModule *smiModule,
			       SmiNode *groupNode)
{
    SmiNode *smiNode;
    SmiType *smiType;
    char    *cModuleName, *cGroupName, *cName;
    unsigned minSize, maxSize;

    cModuleName = translateLower(smiModule->name);
    cGroupName = translate(groupNode->name);

    fprintf(f,
	    "/*\n"
	    " * C type definitions for %s::%s.\n"
	    " */\n\n",
	    smiModule->name, groupNode->name);
    
    fprintf(f, "typedef struct %s {\n", cGroupName);
	    
    for (smiNode = smiGetFirstChildNode(groupNode);
	 smiNode;
	 smiNode = smiGetNextChildNode(smiNode)) {
	if (smiNode->nodekind & (SMI_NODEKIND_COLUMN | SMI_NODEKIND_SCALAR)
#if 0
	    && (smiNode->access == SMI_ACCESS_READ_ONLY
		|| smiNode->access == SMI_ACCESS_READ_WRITE)
#endif
	    ) {
	    smiType = smiGetNodeType(smiNode);
	    if (!smiType) {
		continue;
	    }
	    
	    cName = translate(smiNode->name);
	    switch (smiType->basetype) {
	    case SMI_BASETYPE_OBJECTIDENTIFIER:
		maxSize = smiGetMaxSize(smiType);
		minSize = smiGetMinSize(smiType);
		fprintf(f,
			"    uint32_t  *%s;\n", cName);
		if (maxSize != minSize) {
		    fprintf(f,
			    "    size_t    _%sLength;\n", cName);
		}
		break;
	    case SMI_BASETYPE_OCTETSTRING:
	    case SMI_BASETYPE_BITS:
		maxSize = smiGetMaxSize(smiType);
		minSize = smiGetMinSize(smiType);
		fprintf(f,
			"    u_char    *%s;\n", cName);
		if (maxSize != minSize) {
		    fprintf(f,
			    "    size_t    _%sLength;\n", cName);
		}
		break;
	    case SMI_BASETYPE_ENUM:
	    case SMI_BASETYPE_INTEGER32:
		fprintf(f,
			"    int32_t   *%s;\n", cName);
		break;
	    case SMI_BASETYPE_UNSIGNED32:
		fprintf(f,
			"    uint32_t  *%s;\n", cName);
		break;
	    case SMI_BASETYPE_INTEGER64:
		fprintf(f,
			"    int64_t   *%s; \n", cName);
		break;
	    case SMI_BASETYPE_UNSIGNED64:
		fprintf(f,
			"    uint64_t  *%s; \n", cName);
		break;
	    default:
		fprintf(f,
			"    /* ?? */  __%s; \n", cName);
		break;
	    }
	    xfree(cName);
	}
    }
    
    fprintf(f,
	    "    void      *_clientData;\t\t"
	    "/* pointer to client data structure */\n");
    if (groupNode->nodekind == SMI_NODEKIND_ROW) {
	fprintf(f, "    struct %s *_nextPtr;\t"
		"/* pointer to next table entry */\n", cGroupName);
    }
    fprintf(f,
	    "\n    /* private space to hold actual values */\n\n");

    for (smiNode = smiGetFirstChildNode(groupNode);
	 smiNode;
	 smiNode = smiGetNextChildNode(smiNode)) {
	if (smiNode->nodekind & (SMI_NODEKIND_COLUMN | SMI_NODEKIND_SCALAR)
#if 0
	    && (smiNode->access == SMI_ACCESS_READ_ONLY
		|| smiNode->access == SMI_ACCESS_READ_WRITE)
#endif
	    ) {
	    smiType = smiGetNodeType(smiNode);
	    if (!smiType) {
		continue;
	    }
	    
	    cName = translate(smiNode->name);
	    switch (smiType->basetype) {
	    case SMI_BASETYPE_OBJECTIDENTIFIER:
		maxSize = smiGetMaxSize(smiType);
		fprintf(f,
			"    uint32_t  __%s[%u];\n", cName, maxSize);
		break;
	    case SMI_BASETYPE_OCTETSTRING:
	    case SMI_BASETYPE_BITS:
		maxSize = smiGetMaxSize(smiType);
		fprintf(f,
			"    u_char    __%s[%u];\n", cName, maxSize);
		break;
	    case SMI_BASETYPE_ENUM:
	    case SMI_BASETYPE_INTEGER32:
		fprintf(f,
			"    int32_t   __%s;\n", cName);
		break;
	    case SMI_BASETYPE_UNSIGNED32:
		fprintf(f,
			"    uint32_t  __%s;\n", cName);
		break;
	    case SMI_BASETYPE_INTEGER64:
		fprintf(f,
			"    int64_t   __%s; \n", cName);
		break;
	    case SMI_BASETYPE_UNSIGNED64:
		fprintf(f,
			"    uint64_t  __%s; \n", cName);
		break;
	    default:
		fprintf(f,
			"    /* ?? */  __%s; \n", cName);
		break;
	    }
	    xfree(cName);
	}
    }

    fprintf(f, "} %s_t;\n\n", cGroupName);

    fprintf(f,
	    "/*\n"
	    " * C manager interface stubs for %s::%s.\n"
	    " */\n\n",
	    smiModule->name, groupNode->name);
	    
    fprintf(f, "extern int\n"
	    "%s_mgr_get_%s(struct snmp_session *s, %s_t **%s);\n",
	    cModuleName, cGroupName, cGroupName, cGroupName);
    fprintf(f, "\n");

    fprintf(f,
	    "/*\n"
	    " * C agent interface stubs for %s::%s.\n"
	    " */\n\n",
	    smiModule->name, groupNode->name);
    
    fprintf(f, "extern int\n"
	    "%s_agt_read_%s(%s_t *%s);\n",
	    cModuleName, cGroupName, cGroupName, cGroupName);
    fprintf(f, "extern int\n"
	    "%s_agt_register_%s();\n\n",
	    cModuleName, cGroupName);
    xfree(cGroupName);
    xfree(cModuleName);
}
コード例 #9
0
ファイル: dump-netsnmp.c プロジェクト: pan0007/libsmi
static void printAgtDefinesGroup(FILE *f, SmiNode *groupNode, int cnt)
{
    char         *cName, *cGroupName;
    SmiNode   	 *smiNode;
    SmiType   	 *smiType;
    int	      	 num = 0;
    unsigned int i;
    
    if (cnt == 1) {
	fprintf(f,
	"/*\n"
	" * Definitions of tags that are used internally to read/write\n"
	" * the selected object type. These tags should be unique.\n"
	" */\n\n");
    }

    cGroupName = translate(groupNode->name);

    for (smiNode = smiGetFirstChildNode(groupNode);
	 smiNode;
	 smiNode = smiGetNextChildNode(smiNode)) {
	if (smiNode->nodekind & (SMI_NODEKIND_COLUMN | SMI_NODEKIND_SCALAR)
	    && (smiNode->access == SMI_ACCESS_READ_ONLY
		|| smiNode->access == SMI_ACCESS_READ_WRITE)) {
	    num++;
	    cName = translateUpper(smiNode->name);
	    fprintf(f, "#define %-32s %d\n", cName,
		    smiNode->oid[smiNode->oidlen-1]);
	    xfree(cName);
	}
    }
    fprintf(f, "\n");

    if (num) {
	fprintf(f, "static oid %s_base[] = {", cGroupName);
	for (i = 0; i < groupNode->oidlen; i++) {
	    fprintf(f, "%s%d", i ? ", " : "", groupNode->oid[i]);
	}
	fprintf(f, "};\n\n");
	fprintf(f, "struct variable %s_variables[] = {\n", cGroupName);
	for (smiNode = smiGetFirstChildNode(groupNode);
	     smiNode;
	     smiNode = smiGetNextChildNode(smiNode)) {
	    if (smiNode->nodekind & (SMI_NODEKIND_COLUMN | SMI_NODEKIND_SCALAR)
		&& (smiNode->access == SMI_ACCESS_READ_ONLY
		    || smiNode->access == SMI_ACCESS_READ_WRITE)) {
		smiType = smiGetNodeType(smiNode);
		if (!smiType) {
		    continue;
		}
		cName = translateUpper(smiNode->name);
		fprintf(f, "    { %s, %s, %s, read_%s_stub, %d, {%d} },\n",
			cName, getBaseTypeString(smiType->basetype),
			getAccessString(smiNode->access),
			cGroupName, 1, smiNode->oid[smiNode->oidlen-1]);
		xfree(cName);
	    }
	}
	fprintf(f, "};\n\n");
    }

    xfree(cGroupName);
}
コード例 #10
0
ファイル: dump-netsnmp.c プロジェクト: pan0007/libsmi
static void printMgrGetMethod(FILE *f, SmiModule *smiModule,
			      SmiNode *groupNode)
{
    SmiNode *smiNode;
    char    *cModuleName, *cGroupName;

    cModuleName = translateLower(smiModule->name);
    cGroupName = translate(groupNode->name);

    fprintf(f,
	    "int %s_mgr_get_%s(struct snmp_session *s, %s_t **%s)\n"
	    "{\n"
	    "    struct snmp_session *peer;\n"
	    "    struct snmp_pdu *request, *response;\n"
	    "    struct variable_list *vars;\n"
	    "    int status;\n"
	    "\n",
	    cModuleName, cGroupName, cGroupName, cGroupName);

    fprintf(f,
	    "    request = snmp_pdu_create(SNMP_MSG_GETNEXT);\n");
	    
    for (smiNode = smiGetFirstChildNode(groupNode);
	 smiNode;
	 smiNode = smiGetNextChildNode(smiNode)) {
	if (smiNode->nodekind & (SMI_NODEKIND_COLUMN | SMI_NODEKIND_SCALAR)
	    && (smiNode->access == SMI_ACCESS_READ_ONLY
		|| smiNode->access == SMI_ACCESS_READ_WRITE)) {
	    fprintf(f,
	    "    snmp_add_null_var(request, %s, sizeof(%s)/sizeof(oid));\n",
		    smiNode->name, smiNode->name);
	}
    }

    fprintf(f,
	    "\n"
	    "    peer = snmp_open(s);\n"
	    "    if (!peer) {\n"
	    "        snmp_free_pdu(request);\n"
	    "        return -1;\n"
	    "    }\n"
	    "\n"
	    "    status = snmp_synch_response(peer, request, &response);\n"
	    "    if (status != STAT_SUCCESS) {\n"
	    "        if (response) snmp_free_pdu(response);\n"
	    "        snmp_close(peer);\n"
	    "        return -2;\n"
	    "    }\n"
	    "\n");

    /* generate code for error checking and handling */

    fprintf(f,
	    "    *%s = (%s_t *) malloc(sizeof(%s_t));\n"
	    "    if (! *%s) {\n"
	    "        if (response) snmp_free_pdu(response);\n"
	    "        snmp_close(peer);\n"
	    "        return -4;\n"
	    "    }\n"
	    "\n",
	    cGroupName, cGroupName, cGroupName, cGroupName);

    fprintf(f,
	    "    for (vars = response->variables; vars; vars = vars->next_variable) {\n");
    printMgrGetScalarAssignement(f, groupNode);
    fprintf(f,
	    "    }\n"
	    "\n");


#if 0
    if (response->errstat != SNMP_ERR_NOERROR) {
	return -3;
    }

    /* copy to data structures */

    /* cleanup */

#endif

    fprintf(f,
	    "    if (response) snmp_free_pdu(response);\n"
	    "\n"
	    "    if (snmp_close(peer) == 0) {\n"
	    "        return -5;\n"
	    "    }\n"
	    "\n"
	    "    return 0;\n"
	    "}\n\n");

    xfree(cGroupName);
    xfree(cModuleName);
}
コード例 #11
0
ファイル: dump-netsnmp.c プロジェクト: pan0007/libsmi
static void dumpAgtImpl(SmiModule *smiModule, char *baseName)
{
    char	*stubModuleName, *cModuleName;
    FILE	*f;

    stubModuleName = xmalloc(strlen(baseName) + 10);
    strcpy(stubModuleName, baseName);
    strcat(stubModuleName, "-agt");
    

    f = createFile(stubModuleName, ".c");
    if (! f) {
	xfree(stubModuleName);
        return;
    }

    cModuleName = translateLower(smiModule->name);

    fprintf(f,
	    "/*\n"
	    " * This C file has been generated by smidump "
	    SMI_VERSION_STRING ".\n"
	    " * It is intended to be used with the NET-SNMP agent library.\n"
	    " *\n"
	    " * This C file is derived from the %s module.\n"
	    " *\n * $I" "d$\n"
	    " */\n\n", smiModule->name );
	
    fprintf(f,
	    "#include <stdio.h>\n"
	    "#include <string.h>\n"
	    "#include <malloc.h>\n"
	    "\n"
	    "#include \"%s.h\"\n"
	    "\n"
	    "#include <ucd-snmp/asn1.h>\n"
	    "#include <ucd-snmp/snmp.h>\n"
	    "#include <ucd-snmp/snmp_api.h>\n"
	    "#include <ucd-snmp/snmp_impl.h>\n"
	    "#include <ucd-snmp/snmp_vars.h>\n"
	    "\n",
	    baseName);

    fprintf(f,
	    "static oid %s_caps[] = {0,0};\n"
	    "\n",
	    cModuleName);

    fprintf(f,
	    "void init_%s(void)\n"
	    "{\n"
#if 0
	    /* create an entry in the sysORTable */
	    
	    register_sysORTable(if_mib_caps, sizeof(if_mib_caps),
				"IF-MIB implementation version 0.0.");
	    
	    /* register the various parts of the MIB */
	    
	    register_interfaces();
	    register_ifEntry();
	    
	    /* register essential callbacks */
	    
	    snmp_register_callback(SNMP_CALLBACK_LIBRARY,
				   SNMP_CALLBACK_SHUTDOWN,
				   term_if_mib, NULL);
#endif
	    "}\n"
	    "\n",
	    cModuleName);


    fprintf(f,
	    "void deinit_%s()\n"
	    "{\n"
	    "    unregister_sysORTable(%s_caps, sizeof(%s_caps));\n"
	    "}\n"
	    "\n",
	    cModuleName, cModuleName, cModuleName);

    fprintf(f,
	    "int term_%s()\n"
	    "{\n"
	    "    deinit_%s();\n"
	    "    return 0;\n"
	    "}\n"
	    "\n",
	    cModuleName, cModuleName);

    xfree(cModuleName);
    
    if (fflush(f) || ferror(f)) {
	perror("smidump: write error");
	exit(1);
    }

    fclose(f);
    xfree(stubModuleName);
}
コード例 #12
0
ファイル: selector.c プロジェクト: zanaka/Grama
/* Ruby finalizer for selector objects */
static void NIO_Selector_free(struct NIO_Selector *selector)
{
    NIO_Selector_shutdown(selector);
    xfree(selector);
}
コード例 #13
0
ファイル: authfile.c プロジェクト: marschap/libpam-ssh
static Key *
key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
                      char **commentp)
{
    int i, check1, check2, cipher_type;
    off_t len;
    Buffer buffer, decrypted;
    u_char *cp;
    CipherContext ciphercontext;
    Cipher *cipher;
    Key *prv = NULL;
    struct stat st;

    if (fstat(fd, &st) < 0) {
        error("fstat for key file %.200s failed: %.100s",
              filename, strerror(errno));
        close(fd);
        return NULL;
    }
    len = st.st_size;

    buffer_init(&buffer);
    cp = buffer_append_space(&buffer, len);

    if (read(fd, cp, (size_t) len) != (size_t) len) {
        debug("Read from key file %.200s failed: %.100s", filename,
              strerror(errno));
        buffer_free(&buffer);
        close(fd);
        return NULL;
    }

    /* Check that it is at least big enough to contain the ID string. */
    if (len < sizeof(authfile_id_string)) {
        debug3("Not a RSA1 key file %.200s.", filename);
        buffer_free(&buffer);
        close(fd);
        return NULL;
    }
    /*
     * Make sure it begins with the id string.  Consume the id string
     * from the buffer.
     */
    for (i = 0; i < sizeof(authfile_id_string); i++)
        if (buffer_get_char(&buffer) != authfile_id_string[i]) {
            debug3("Not a RSA1 key file %.200s.", filename);
            buffer_free(&buffer);
            close(fd);
            return NULL;
        }

    /* Read cipher type. */
    cipher_type = buffer_get_char(&buffer);
    (void) buffer_get_int(&buffer);	/* Reserved data. */

    /* Read the public key from the buffer. */
    (void) buffer_get_int(&buffer);
    prv = key_new_private(KEY_RSA1);

    buffer_get_bignum(&buffer, prv->rsa->n);
    buffer_get_bignum(&buffer, prv->rsa->e);
    if (commentp)
        *commentp = buffer_get_string(&buffer, NULL);
    else
        xfree(buffer_get_string(&buffer, NULL));

    /* Check that it is a supported cipher. */
    cipher = cipher_by_number(cipher_type);
    if (cipher == NULL) {
        debug("Unsupported cipher %d used in key file %.200s.",
              cipher_type, filename);
        buffer_free(&buffer);
        goto fail;
    }
    /* Initialize space for decrypted data. */
    buffer_init(&decrypted);
    cp = buffer_append_space(&decrypted, buffer_len(&buffer));

    /* Rest of the buffer is encrypted.  Decrypt it using the passphrase. */
    cipher_set_key_string(&ciphercontext, cipher, passphrase,
                          CIPHER_DECRYPT);
    cipher_crypt(&ciphercontext, cp,
                 buffer_ptr(&buffer), buffer_len(&buffer));
    cipher_cleanup(&ciphercontext);
    memset(&ciphercontext, 0, sizeof(ciphercontext));
    buffer_free(&buffer);

    check1 = buffer_get_char(&decrypted);
    check2 = buffer_get_char(&decrypted);
    if (check1 != buffer_get_char(&decrypted) ||
            check2 != buffer_get_char(&decrypted)) {
        if (strcmp(passphrase, "") != 0)
            debug("Bad passphrase supplied for key file %.200s.",
                  filename);
        /* Bad passphrase. */
        buffer_free(&decrypted);
        goto fail;
    }
    /* Read the rest of the private key. */
    buffer_get_bignum(&decrypted, prv->rsa->d);
    buffer_get_bignum(&decrypted, prv->rsa->iqmp);		/* u */
    /* in SSL and SSH v1 p and q are exchanged */
    buffer_get_bignum(&decrypted, prv->rsa->q);		/* p */
    buffer_get_bignum(&decrypted, prv->rsa->p);		/* q */

    /* calculate p-1 and q-1 */
    rsa_generate_additional_parameters(prv->rsa);

    buffer_free(&decrypted);

    /* enable blinding */
    if (RSA_blinding_on(prv->rsa, NULL) != 1) {
        error("key_load_private_rsa1: RSA_blinding_on failed");
        goto fail;
    }
    close(fd);
    return prv;

fail:
    if (commentp)
        xfree(*commentp);
    close(fd);
    key_free(prv);
    return NULL;
}
コード例 #14
0
ファイル: httptest.c プロジェクト: tjyang/cpam
int tcp_http_data_callback(unsigned char *buf, unsigned int len, void *priv)
{
	/*
	 * This callback receives data from HTTP servers.
	 * While doing that, it splits out the data into a
	 * buffer for the HTTP headers, and a buffer for the
	 * HTTP content-data.
	 * Return 1 if data is complete, 0 if more data wanted.
	 */

	http_data_t *item = (http_data_t *) priv;

	if (item->gotheaders) {
		unsigned int len1chunk = 0;
		int i;

		/*
		 * We already have the headers, so just stash away the data
		 */


		while (len > 0) {
			dbgprintf("HDC IN : state=%d, leftinchunk=%d, len=%d\n", item->chunkstate, item->leftinchunk, len);
			switch (item->chunkstate) {
			  case CHUNK_NOTCHUNKED:
				len1chunk = len;
				if ((item->contlen > 0) && (item->contlen >= len)) item->contlen -= len;
				break;

			  case CHUNK_INIT:
				/* We're about to pick up a chunk length */
				item->leftinchunk = 0;
				item->chunkstate = CHUNK_GETLEN;
				len1chunk = 0;
				break;

			  case CHUNK_GETLEN:
				/* We are collecting the length of the chunk */
				i = hexvalue(*buf);
				if (i == -1) {
					item->chunkstate = CHUNK_SKIPLENCR;
				}
				else {
					item->leftinchunk = item->leftinchunk*16 + i;
					buf++; len--;
				}
				len1chunk = 0;
				break;
				
			  case CHUNK_SKIPLENCR:
				/* We've got the length, now skip to the next LF */
				if (*buf == '\n') {
					buf++; len--; 
					item->chunkstate = ((item->leftinchunk > 0) ? CHUNK_DATA : CHUNK_NOMORE);
				}
				else if ((*buf == '\r') || (*buf == ' ')) {
					buf++; len--;
				}
				else {
					errprintf("Yikes - strange data following chunk len. Saw a '%c'\n", *buf);
					buf++; len--;
				}
				len1chunk = 0;
				break;

			  case CHUNK_DATA:
				/* Passing off the data */
				if (len > item->leftinchunk) len1chunk = item->leftinchunk;
				else len1chunk = len;
				item->leftinchunk -= len1chunk;
				if (item->leftinchunk == 0) item->chunkstate = CHUNK_SKIPENDCR;
				break;

			  case CHUNK_SKIPENDCR:
				/* Skip CR/LF after a chunk */
				if (*buf == '\n') {
					buf++; len--; item->chunkstate = CHUNK_DONE;
				}
				else if (*buf == '\r') {
					buf++; len--;
				}
				else {
					errprintf("Yikes - strange data following chunk data. Saw a '%c'\n", *buf);
					buf++; len--;
				}
				len1chunk = 0;
				break;

			  case CHUNK_DONE:
				/* One chunk is done, continue with the next */
				len1chunk = 0;
				item->chunkstate = CHUNK_GETLEN;
				break;

			  case CHUNK_NOMORE:
				/* All chunks done. Skip the rest (trailers) */
				len1chunk = 0;
				len = 0;
			}

			if (len1chunk > 0) {
				switch (item->contentcheck) {
				  case CONTENTCHECK_NONE:
				  case CONTENTCHECK_CONTENTTYPE:
					/* No need to save output - just drop it */
					break;

				  case CONTENTCHECK_REGEX:
				  case CONTENTCHECK_NOREGEX:
					/* Save the full data */
					if ((item->output == NULL) || (item->outlen == 0)) {
						item->output = (unsigned char *)malloc(len1chunk+1);
					}
					else {
						item->output = (unsigned char *)realloc(item->output, item->outlen+len1chunk+1);
					}

					memcpy(item->output+item->outlen, buf, len1chunk);
					item->outlen += len1chunk;
					*(item->output + item->outlen) = '\0'; /* Just in case ... */
					break;

				  case CONTENTCHECK_DIGEST:
					/* Run the data through our digest routine, but discard the raw data */
					if ((item->digestctx == NULL) || (digest_data(item->digestctx, buf, len1chunk) != 0)) {
						errprintf("Failed to hash data for digest\n");
					}
					break;
				}

				buf += len1chunk;
				len -= len1chunk;
				dbgprintf("HDC OUT: state=%d, leftinchunk=%d, len=%d\n", item->chunkstate, item->leftinchunk, len);
			}
		}
	}
	else {
		/*
		 * Havent seen the end of headers yet.
		 */
		unsigned char *p;

		/* First, add this to the header-buffer */
		if (item->headers == NULL) {
			item->headers = (unsigned char *) malloc(len+1);
		}
		else {
			item->headers = (unsigned char *) realloc(item->headers, item->hdrlen+len+1);
		}

		memcpy(item->headers+item->hdrlen, buf, len);
		item->hdrlen += len;
		*(item->headers + item->hdrlen) = '\0';

check_for_endofheaders:
		/* 
		 * Now see if we have the end-of-headers delimiter.
		 * This SHOULD be <cr><lf><cr><lf>, but RFC 2616 says
		 * you SHOULD recognize just plain <lf><lf>.
		 * So try the second form, if the first one is not there.
		 */
		p=strstr(item->headers, "\r\n\r\n");
		if (p) {
			p += 4;
		}
		else {
			p = strstr(item->headers, "\n\n");
			if (p) p += 2;
		}

		if (p) {
			int http1subver, httpstatus;
			unsigned int bytesindata;
			char *p1, *xferencoding;
			int contlen;

			/* We have an end-of-header delimiter, but it could be just a "100 Continue" response */
			sscanf(item->headers, "HTTP/1.%d %d", &http1subver, &httpstatus);
			if (httpstatus == 100) {
				/* 
				 * It's a "100"  continue-status.
				 * Just drop this set of headers, and move on.
				 */
				item->hdrlen -= (p - item->headers);
				if (item->hdrlen > 0) {
					memmove(item->headers, p, item->hdrlen);
					*(item->headers + item->hdrlen) = '\0';
					goto check_for_endofheaders;
				}
				else {
					xfree(item->headers);
					item->headers = NULL;
					item->hdrlen = 0;
					return 0;
				}

				/* Should never go here ... */
			}


			/* We did find the end-of-header delimiter, and it is not a "100" status. */
			item->gotheaders = 1;

			/* p points at the first byte of DATA. So the header ends 1 or 2 bytes before. */
			*(p-1) = '\0';
			if (*(p-2) == '\r') { *(p-2) = '\0'; } /* NULL-terminate the headers. */

			/* See if the transfer uses chunks */
			p1 = item->headers; xferencoding = NULL; contlen = 0;
			do {
				if (strncasecmp(p1, "Transfer-encoding:", 18) == 0) {
					p1 += 18; while (isspace((int)*p1)) p1++;
					xferencoding = p1;
				}
				else if (strncasecmp(p1, "Content-Length:", 15) == 0) {
					p1 += 15; while (isspace((int)*p1)) p1++;
					contlen = atoi(p1);
				}
				else {
					p1 = strchr(p1, '\n'); if (p1) p1++;
				}
			} while (p1 && (xferencoding == NULL));

			if (xferencoding && (strncasecmp(xferencoding, "chunked", 7) == 0)) {
				item->chunkstate = CHUNK_INIT;
			}
			item->contlen = (contlen ? contlen : -1);

			bytesindata = item->hdrlen - (p - item->headers);
			item->hdrlen = strlen(item->headers);
			if (*p) {
				/* 
				 * We received some content data together with the
				 * headers. Save these to the content-data area.
				 */
				tcp_http_data_callback(p, bytesindata, priv);
			}
		}
	}

	if (item->chunkstate == CHUNK_NOTCHUNKED) 
		/* Not chunked - we're done if contlen reaches 0 */
		return (item->contlen == 0);
	else 
		/* Chunked - we're done if we reach state NOMORE*/
		return (item->chunkstate == CHUNK_NOMORE);
}
コード例 #15
0
ファイル: req.c プロジェクト: gyliu513/slurm
static void *
_handle_accept(void *arg)
{
	/*struct request_params *param = (struct request_params *)arg;*/
	int fd = ((struct request_params *)arg)->fd;
	stepd_step_rec_t *job = ((struct request_params *)arg)->job;
	int req;
	int len;
	Buf buffer;
	void *auth_cred;
	int rc;
	uid_t uid;
	gid_t gid;

	debug3("Entering _handle_accept (new thread)");
	xfree(arg);

	safe_read(fd, &req, sizeof(int));
	if (req != REQUEST_CONNECT) {
		error("First message must be REQUEST_CONNECT");
		goto fail;
	}

	safe_read(fd, &len, sizeof(int));
	buffer = init_buf(len);
	safe_read(fd, get_buf_data(buffer), len);

	/* Unpack and verify the auth credential */
	auth_cred = g_slurm_auth_unpack(buffer);
	if (auth_cred == NULL) {
		error("Unpacking authentication credential: %s",
		      g_slurm_auth_errstr(g_slurm_auth_errno(NULL)));
		free_buf(buffer);
		goto fail;
	}
	rc = g_slurm_auth_verify(auth_cred, NULL, 2, NULL);
	if (rc != SLURM_SUCCESS) {
		error("Verifying authentication credential: %s",
		      g_slurm_auth_errstr(g_slurm_auth_errno(auth_cred)));
		(void) g_slurm_auth_destroy(auth_cred);
		free_buf(buffer);
		goto fail;
	}

	/* Get the uid & gid from the credential, then destroy it. */
	uid = g_slurm_auth_get_uid(auth_cred, NULL);
	gid = g_slurm_auth_get_gid(auth_cred, NULL);
	debug3("  Identity: uid=%d, gid=%d", uid, gid);
	g_slurm_auth_destroy(auth_cred);
	free_buf(buffer);

	rc = SLURM_SUCCESS;
	safe_write(fd, &rc, sizeof(int));

	while (1) {
		rc = _handle_request(fd, job, uid, gid);
		if (rc != SLURM_SUCCESS)
			break;
	}

	if (close(fd) == -1)
		error("Closing accepted fd: %m");

	pthread_mutex_lock(&message_lock);
	message_connections--;
	pthread_cond_signal(&message_cond);
	pthread_mutex_unlock(&message_lock);

	debug3("Leaving  _handle_accept");
	return NULL;

fail:
	rc = SLURM_FAILURE;
	safe_write(fd, &rc, sizeof(int));
rwfail:
	if (close(fd) == -1)
		error("Closing accepted fd after error: %m");
	debug("Leaving  _handle_accept on an error");
	return NULL;
}
コード例 #16
0
ファイル: dump-netsnmp.c プロジェクト: pan0007/libsmi
static void printAgtReadMethod(FILE *f, SmiNode *groupNode)
{
    SmiNode   *smiNode;
    SmiType   *smiType;
    char      *cName, *sName, *lName;

    sName = translate(groupNode->name);

    fprintf(f,
	    "static unsigned char *\nread_%s_stub(struct variable *vp,\n"
	    "    oid     *name,\n"
	    "    size_t  *length,\n"
	    "    int     exact,\n"
	    "    size_t  *var_len,\n"
	    "    WriteMethod **write_method)\n"
	    "{\n", sName);

    fprintf(f, "    static %s_t %s;\n\n", sName, sName);
    
    smiNode = smiGetFirstChildNode(groupNode);
    if (smiNode && smiNode->nodekind == SMI_NODEKIND_SCALAR) {
	fprintf(f,
		"    /* check whether the instance identifier is valid */\n"
		"\n"
		"    if (header_generic(vp, name, length, exact, var_len,\n"
		"                       write_method) == MATCH_FAILED) {\n"
		"        return NULL;\n"
		"    }\n"
		"\n");
    }

    fprintf(f,
	    "    /* call the user supplied function to retrieve values */\n"
	    "\n"
	    "    read_%s(&%s);\n"
	    "\n", sName, sName);

    fprintf(f,
	    "    /* return the current value of the variable */\n"
	    "\n"
	    "    switch (vp->magic) {\n"
	    "\n");

    for (smiNode = smiGetFirstChildNode(groupNode);
	 smiNode;
	 smiNode = smiGetNextChildNode(smiNode)) {
	if (smiNode->nodekind & (SMI_NODEKIND_COLUMN | SMI_NODEKIND_SCALAR)
	    && (smiNode->access == SMI_ACCESS_READ_ONLY
		|| smiNode->access == SMI_ACCESS_READ_WRITE)) {
	    cName = translateUpper(smiNode->name);
	    lName = translate(smiNode->name);
	    smiType = smiGetNodeType(smiNode);
	    if (! smiType) {
		continue;
	    }
	    fprintf(f, "    case %s:\n", cName);
	    switch (smiType->basetype) {
	    case SMI_BASETYPE_OBJECTIDENTIFIER:
		fprintf(f,
			"        *var_len = %s._%sLength;\n"
			"        return (unsigned char *) %s.%s;\n",
			sName, lName, sName, lName);
		break;
	    case SMI_BASETYPE_OCTETSTRING:
	    case SMI_BASETYPE_BITS:
		fprintf(f,
			"        *var_len = %s._%sLength;\n"
			"        return (unsigned char *) %s.%s;\n",
			sName, lName, sName, lName);
		break;
	    case SMI_BASETYPE_ENUM:
	    case SMI_BASETYPE_INTEGER32:
	    case SMI_BASETYPE_UNSIGNED32:
		fprintf(f,
			"        return (unsigned char *) &%s.%s;\n",
			sName, lName);
		break;
	    default:
		fprintf(f,
			"        /* add code to return the value here */\n");
	    }
	    fprintf(f, "\n");
	    xfree(cName);
	    xfree(lName);
	}
    }

    fprintf(f,
	    "    default:\n"
	    "         ERROR_MSG(\"\");\n"
	    "    }\n"
	    "\n"
	    "    return NULL;\n"
	    "}\n"
	    "\n");

    xfree(sName);
}
コード例 #17
0
ファイル: req.c プロジェクト: gyliu513/slurm
static int
_handle_checkpoint_tasks(int fd, stepd_step_rec_t *job, uid_t uid)
{
	int rc = SLURM_SUCCESS;
	time_t timestamp;
	int len;
	char *image_dir = NULL;

	debug3("_handle_checkpoint_tasks for job %u.%u",
	       job->jobid, job->stepid);

	safe_read(fd, &timestamp, sizeof(time_t));
	safe_read(fd, &len, sizeof(int));
	if (len) {
		image_dir = xmalloc (len);
		safe_read(fd, image_dir, len); /* '\0' terminated */
	}

	debug3("  uid = %d", uid);
	if (uid != job->uid && !_slurm_authorized_user(uid)) {
		debug("checkpoint req from uid %ld for job %u.%u "
		      "owned by uid %ld",
		      (long)uid, job->jobid, job->stepid, (long)job->uid);
		rc = EPERM;
		goto done;
	}

	if (job->ckpt_timestamp &&
	    timestamp == job->ckpt_timestamp) {
		debug("duplicate checkpoint req for job %u.%u, "
		      "timestamp %ld. discarded.",
		      job->jobid, job->stepid, (long)timestamp);
		rc = ESLURM_ALREADY_DONE; /* EINPROGRESS? */
		goto done;
	}

	/*
	 * Sanity checks
	 */
	if (job->pgid <= (pid_t)1) {
		debug ("step %u.%u invalid [jmgr_pid:%d pgid:%u]",
		       job->jobid, job->stepid, job->jmgr_pid, job->pgid);
		rc = ESLURMD_JOB_NOTRUNNING;
		goto done;
	}

	pthread_mutex_lock(&suspend_mutex);
	if (suspended) {
		rc = ESLURMD_STEP_SUSPENDED;
		pthread_mutex_unlock(&suspend_mutex);
		goto done;
	}

	/* set timestamp in case another request comes */
	job->ckpt_timestamp = timestamp;

	/* TODO: do we need job->ckpt_dir any more,
	 *	except for checkpoint/xlch? */
/*	if (! image_dir) { */
/*		image_dir = xstrdup(job->ckpt_dir); */
/*	} */

	/* call the plugin to send the request */
	if (checkpoint_signal_tasks(job, image_dir) != SLURM_SUCCESS) {
		rc = -1;
		verbose("Error sending checkpoint request to %u.%u: %s",
			job->jobid, job->stepid, slurm_strerror(rc));
	} else {
		verbose("Sent checkpoint request to %u.%u",
			job->jobid, job->stepid);
	}

	pthread_mutex_unlock(&suspend_mutex);

done:
	/* Send the return code */
	safe_write(fd, &rc, sizeof(int));
	xfree(image_dir);
	return SLURM_SUCCESS;
rwfail:
	return SLURM_FAILURE;
}
コード例 #18
0
ファイル: dump-netsnmp.c プロジェクト: pan0007/libsmi
static void printMgrGetScalarAssignement(FILE *f, SmiNode *groupNode)
{
    SmiNode *smiNode;
    SmiType *smiType;
    char    *cGroupName, *cName;
    unsigned maxSize, minSize;

    cGroupName = translate(groupNode->name);

    for (smiNode = smiGetFirstChildNode(groupNode);
	 smiNode;
	 smiNode = smiGetNextChildNode(smiNode)) {
	if (smiNode->nodekind & (SMI_NODEKIND_COLUMN | SMI_NODEKIND_SCALAR)
	    && (smiNode->access == SMI_ACCESS_READ_ONLY
		|| smiNode->access == SMI_ACCESS_READ_WRITE)) {

	    smiType = smiGetNodeType(smiNode);
	    if (!smiType) {
		continue;
	    }
	    
	    cName = translate(smiNode->name);
	    fprintf(f,
		    "        if (vars->name_length > sizeof(%s)/sizeof(oid)\n"
		    "            && memcmp(vars->name, %s, sizeof(%s)) == 0) {\n",
		    cName, cName, cName);
	    switch (smiType->basetype) {
	    case SMI_BASETYPE_INTEGER32:
	    case SMI_BASETYPE_UNSIGNED32:
	    case SMI_BASETYPE_ENUM:
		fprintf(f,
			"            (*%s)->__%s = *vars->val.integer;\n"
			"            (*%s)->%s = &((*%s)->__%s);\n",
			cGroupName, cName,
			cGroupName, cName, cGroupName, cName);
		break;
	    case SMI_BASETYPE_OCTETSTRING:
	    case SMI_BASETYPE_BITS:
		maxSize = smiGetMaxSize(smiType);
		minSize = smiGetMinSize(smiType);
		fprintf(f,
			"            memcpy((*%s)->__%s, vars->val.string, vars->val_len);\n",
			cGroupName, cName);
		if (minSize != maxSize) {
		    fprintf(f,
			    "            (*%s)->_%sLength = vars->val_len;\n",
			    cGroupName, cName);
		}
		fprintf(f,
			"            (*%s)->%s = (*%s)->__%s;\n",
			cGroupName, cName, cGroupName, cName);
		break;
	    case SMI_BASETYPE_OBJECTIDENTIFIER:
		break;
	    default:
		break;
	    }
	    fprintf(f,
		    "        }\n");
	    xfree(cName);
	}
    }

    xfree(cGroupName);
}
コード例 #19
0
ファイル: jit.c プロジェクト: ArmstrongJ/insight-debugger
static int
mem_bfd_iovec_close (struct bfd *abfd, void *stream)
{
  xfree (stream);
  return 1;
}
コード例 #20
0
ファイル: send.c プロジェクト: Johan-M/pilight
int main(int argc, char **argv) {
	// memtrack();

	wiringXLog = _lognone;

	log_file_disable();
	log_shell_enable();
	log_level_set(LOG_NOTICE);

	if(!(progname = MALLOC(13))) {
		logprintf(LOG_ERR, "out of memory");
		exit(EXIT_FAILURE);
	}
	strcpy(progname, "pilight-send");

	struct options_t *options = NULL;
	struct ssdp_list_t *ssdp_list = NULL;

	int sockfd = 0;
	char *args = NULL, *recvBuff = NULL;

	/* Hold the name of the protocol */
	char *protobuffer = NULL;
	/* Does this protocol exists */
	int match = 0;

	/* Do we need to print the help */
	int help = 0;
	/* Do we need to print the version */
	int version = 0;
	/* Do we need to print the protocol help */
	int protohelp = 0;

	char *uuid = NULL;
	char *server = NULL;
	unsigned short port = 0;

	/* Hold the final protocol struct */
	protocol_t *protocol = NULL;
	JsonNode *code = NULL;

	/* Define all CLI arguments of this program */
	options_add(&options, 'H', "help", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'V', "version", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'p', "protocol", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'S', "server", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	options_add(&options, 'P', "port", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "[0-9]{1,4}");
	options_add(&options, 'U', "uuid", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "[a-zA-Z0-9]{4}-[a-zA-Z0-9]{2}-[a-zA-Z0-9]{2}-[a-zA-Z0-9]{2}-[a-zA-Z0-9]{6}");

	/* Get the protocol to be used */
	while(1) {
		int c;
		c = options_parse(&options, argc, argv, 0, &args);
		if(c == -1)
			break;
		if(c == -2)
			c = 'H';
		switch(c) {
			case 'p':
				if(strlen(args) == 0) {
					logprintf(LOG_ERR, "options '-p' and '--protocol' require an argument");
					exit(EXIT_FAILURE);
				} else {
					if(!(protobuffer = REALLOC(protobuffer, strlen(args)+1))) {
						logprintf(LOG_ERR, "out of memory");
						exit(EXIT_FAILURE);
					}
					strcpy(protobuffer, args);
				}
			break;
			case 'V':
				version = 1;
			break;
			case 'H':
				help = 1;
			break;
			case 'S':
				if(!(server = REALLOC(server, strlen(args)+1))) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(server, args);
			break;
			case 'P':
				port = (unsigned short)atoi(args);
			break;
			case 'U':
				if(!(uuid = REALLOC(uuid, strlen(args)+1))) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(uuid, args);
			break;
			default:;
		}
	}

	/* Initialize protocols */
	protocol_init();

	/* Check if a protocol was given */
	if(protobuffer && strlen(protobuffer) > 0 && strcmp(protobuffer, "-V") != 0) {
		if(strlen(protobuffer) > 0 && version) {
			printf("-p and -V cannot be combined\n");
		} else {
			struct protocols_t *pnode = protocols;
			/* Retrieve the used protocol */
			while(pnode) {
				/* Check if the protocol exists */
				protocol = pnode->listener;
				if(protocol_device_exists(protocol, protobuffer) == 0 && match == 0 && protocol->createCode != NULL) {
					match=1;
					/* Check if the protocol requires specific CLI arguments
					   and merge them with the main CLI arguments */
					if(protocol->options && help == 0) {
						options_merge(&options, &protocol->options);
					} else if(help == 1) {
						protohelp=1;
					}
					break;
				}
				pnode = pnode->next;
			}
			/* If no protocols matches the requested protocol */
			if(!match) {
				logprintf(LOG_ERR, "this protocol is not supported or doesn't support sending");
			}
		}
	}

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = options_parse(&options, argc, argv, 2, &args);

		if(c == -1)
			break;
		if(c == -2) {
			if(match == 1) {
				protohelp = 1;
			} else {
				help = 1;
			}
		break;
		}
	}

	/* Display help or version information */
	if(version == 1) {
		printf("%s %s\n", progname, PILIGHT_VERSION);
		goto close;
	} else if(help == 1 || protohelp == 1 || match == 0) {
		if(protohelp == 1 && match == 1 && protocol->printHelp)
			printf("Usage: %s -p %s [options]\n", progname, protobuffer);
		else
			printf("Usage: %s -p protocol [options]\n", progname);
		if(help == 1) {
			printf("\t -H --help\t\t\tdisplay this message\n");
			printf("\t -V --version\t\t\tdisplay version\n");
			printf("\t -p --protocol=protocol\t\tthe protocol that you want to control\n");
			printf("\t -S --server=x.x.x.x\t\tconnect to server address\n");
			printf("\t -P --port=xxxx\t\t\tconnect to server port\n");
			printf("\t -C --config\t\t\tconfig file\n");
			printf("\t -U --uuid=xxx-xx-xx-xx-xxxxxx\tUUID\n");
		}
		if(protohelp == 1 && match == 1 && protocol->printHelp) {
			printf("\n\t[%s]\n", protobuffer);
			protocol->printHelp();
		} else {
			printf("\nThe supported protocols are:\n");
			struct protocols_t *pnode = protocols;
			/* Retrieve the used protocol */
			while(pnode) {
				protocol = pnode->listener;
				if(protocol->createCode) {
					struct protocol_devices_t *tmpdev = protocol->devices;
					while(tmpdev) {
						struct pname_t *node = MALLOC(sizeof(struct pname_t));
						if(!node) {
							logprintf(LOG_ERR, "out of memory");
							exit(EXIT_FAILURE);
						}
						if(!(node->name = MALLOC(strlen(tmpdev->id)+1))) {
							logprintf(LOG_ERR, "out of memory");
							exit(EXIT_FAILURE);
						}
						strcpy(node->name, tmpdev->id);
						if(!(node->desc = MALLOC(strlen(tmpdev->desc)+1))) {
							logprintf(LOG_ERR, "out of memory");
							exit(EXIT_FAILURE);
						}
						strcpy(node->desc, tmpdev->desc);
						node->next = pname;
						pname = node;
						tmpdev = tmpdev->next;
					}
				}
				pnode = pnode->next;
			}
			sort_list();
			struct pname_t *ptmp = NULL;
			while(pname) {
				ptmp = pname;
				printf("\t %s\t\t",ptmp->name);
				if(strlen(ptmp->name) < 7)
					printf("\t");
				if(strlen(ptmp->name) < 15)
					printf("\t");
				printf("%s\n", ptmp->desc);
				FREE(ptmp->name);
				FREE(ptmp->desc);
				pname = pname->next;
				FREE(ptmp);
			}
			FREE(pname);
		}
		goto close;
	}

	code = json_mkobject();
	int itmp = 0;
	/* Check if we got sufficient arguments from this protocol */
	struct options_t *tmp = options;
	while(tmp) {
		if(strlen(tmp->name) > 0) {
			/* Only send the CLI arguments that belong to this protocol, the protocol name
			and those that are called by the user */
			if((options_get_id(&protocol->options, tmp->name, &itmp) == 0)
			    && tmp->vartype == JSON_STRING && tmp->string_ != NULL
				&& (strlen(tmp->string_) > 0)) {
				if(isNumeric(tmp->string_) == 0) {
					char *ptr = strstr(tmp->string_, ".");
					int decimals = 0;
					if(ptr != NULL) {
						decimals = (int)(strlen(tmp->string_)-((size_t)(ptr-tmp->string_)+1));
					}
					json_append_member(code, tmp->name, json_mknumber(atof(tmp->string_), decimals));
				} else {
					json_append_member(code, tmp->name, json_mkstring(tmp->string_));
				}
			}
			if(strcmp(tmp->name, "protocol") == 0 && strlen(tmp->string_) > 0) {
				JsonNode *jprotocol = json_mkarray();
				json_append_element(jprotocol, json_mkstring(tmp->string_));
				json_append_member(code, "protocol", jprotocol);
			}
		}
		tmp = tmp->next;
	}

	if(protocol->createCode(code) == 0) {
		if(protocol->message) {
			json_delete(protocol->message);
		}
		if(server && port > 0) {
			if((sockfd = socket_connect(server, port)) == -1) {
				logprintf(LOG_ERR, "could not connect to pilight-daemon");
				goto close;
			}
		} else if(ssdp_seek(&ssdp_list) == -1) {
			logprintf(LOG_ERR, "no pilight ssdp connections found");
			goto close;
		} else {
			if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1) {
				logprintf(LOG_ERR, "could not connect to pilight-daemon");
				goto close;
			}
		}
		if(ssdp_list) {
			ssdp_free(ssdp_list);
		}

		socket_write(sockfd, "{\"action\":\"identify\"}");
		if(socket_read(sockfd, &recvBuff, 0) != 0
		   || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
			goto close;
		}

		JsonNode *json = json_mkobject();
		json_append_member(json, "action", json_mkstring("send"));
		if(uuid != NULL) {
			json_append_member(code, "uuid", json_mkstring(uuid));
		}
		json_append_member(json, "code", code);
		char *output = json_stringify(json, NULL);
		socket_write(sockfd, output);
		json_free(output);
		json_delete(json);

		if(socket_read(sockfd, &recvBuff, 0) != 0
		   || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
			logprintf(LOG_ERR, "failed to send codes");
			goto close;
		}
	}
close:
	if(sockfd > 0) {
		socket_close(sockfd);
	}
	if(recvBuff != NULL) {
		FREE(recvBuff);
	}
	if(server != NULL) {
		FREE(server);
	}
	if(protobuffer != NULL) {
		FREE(protobuffer);
	}
	if(uuid != NULL) {
		FREE(uuid);
	}
	log_shell_disable();
	protocol_gc();
	options_delete(options);
	options_gc();
	config_gc();
	threads_gc();
	dso_gc();
	log_gc();
	FREE(progname);
	xfree();

	return EXIT_SUCCESS;
}
コード例 #21
0
ファイル: node_select.c プロジェクト: kwangiit/SLURMPP
/*
 * Initialize context for node selection plugin
 */
extern int slurm_select_init(bool only_default)
{
	int retval = SLURM_SUCCESS;
	char *type = NULL;
	int i, j, len;
	DIR *dirp;
	struct dirent *e;
	char *dir_array = NULL, *head = NULL;
	char *plugin_type = "select";

	if ( init_run && select_context )
		return retval;

	slurm_mutex_lock( &select_context_lock );

	if ( select_context )
		goto done;

	type = slurm_get_select_type();
	if (working_cluster_rec) {
		/* just ignore warnings here */
	} else {
#ifdef HAVE_XCPU
		if (strcasecmp(type, "select/linear")) {
			error("%s is incompatible with XCPU use", type);
			fatal("Use SelectType=select/linear");
		}
#endif
		if (!strcasecmp(type, "select/linear")) {
			uint16_t cr_type = slurm_get_select_type_param();
			if ((cr_type & CR_SOCKET) || (cr_type & CR_CORE) ||
			    (cr_type & CR_CPU))
				fatal("Invalid SelectTypeParameter "
				      "for select/linear");
		}

#ifdef HAVE_BG
		if (strcasecmp(type, "select/bluegene")) {
			error("%s is incompatible with BlueGene", type);
			fatal("Use SelectType=select/bluegene");
		}
#else
		if (!strcasecmp(type, "select/bluegene")) {
			fatal("Requested SelectType=select/bluegene "
			      "in slurm.conf, but not running on a BG[L|P|Q] "
			      "system.  If looking to emulate a BG[L|P|Q] "
			      "system use --enable-bgl-emulation or "
			      "--enable-bgp-emulation respectively.");
		}
#endif

#ifdef HAVE_CRAY
		if (strcasecmp(type, "select/cray")) {
			error("%s is incompatible with Cray", type);
			fatal("Use SelectType=select/cray");
		}
#else
		if (!strcasecmp(type, "select/cray")) {
			fatal("Requested SelectType=select/cray "
			      "in slurm.conf, but not running on a Cray "
			      "system.  If looking to emulate a Cray "
			      "system use --enable-cray-emulation.");
		}
#endif
	}

	select_context_cnt = 0;
	if (only_default) {
		ops = xmalloc(sizeof(slurm_select_ops_t));
		select_context = xmalloc(sizeof(plugin_context_t));
		if ((select_context[0] = plugin_context_create(
			     plugin_type, type, (void **)&ops[0],
			     node_select_syms, sizeof(node_select_syms)))) {
			select_context_default = 0;
			select_context_cnt++;
		}
		goto skip_load_all;
	}

	if (!(dir_array = slurm_get_plugin_dir())) {
		error("plugin_load_and_link: No plugin dir given");
		goto done;
	}

	head = dir_array;
	for (i=0; ; i++) {
		bool got_colon = 0;
		if (dir_array[i] == ':') {
			dir_array[i] = '\0';
			got_colon = 1;
		} else if (dir_array[i] != '\0')
			continue;

		/* Open the directory. */
		if (!(dirp = opendir(head))) {
			error("cannot open plugin directory %s", head);
			goto done;
		}

		while (1) {
			char full_name[128];

			if (!(e = readdir( dirp )))
				break;
			/* Check only files with select_ in them. */
			if (strncmp(e->d_name, "select_", 7))
				continue;

			len = strlen(e->d_name);
#if defined(__CYGWIN__)
			len -= 4;
#else
			len -= 3;
#endif
			/* Check only shared object files */
			if (strcmp(e->d_name+len,
#if defined(__CYGWIN__)
				   ".dll"
#else
				   ".so"
#endif
				    ))
				continue;
			/* add one for the / */
			len++;
			xassert(len<sizeof(full_name));
			snprintf(full_name, len, "select/%s", e->d_name+7);
			for (j=0; j<select_context_cnt; j++) {
				if (!strcmp(full_name,
					    select_context[j]->type))
					break;
			}
			if (j >= select_context_cnt) {
				xrealloc(ops,
					 (sizeof(slurm_select_ops_t) *
					  (select_context_cnt + 1)));
				xrealloc(select_context,
					 (sizeof(plugin_context_t) *
					  (select_context_cnt + 1)));

				select_context[select_context_cnt] =
					plugin_context_create(
						plugin_type, full_name,
						(void **)&ops[
							select_context_cnt],
						node_select_syms,
						sizeof(node_select_syms));
				if (select_context[select_context_cnt]) {
					/* set the default */
					if (!strcmp(full_name, type))
						select_context_default =
							select_context_cnt;
					select_context_cnt++;
				}
			}
		}

		closedir(dirp);

		if (got_colon) {
			head = dir_array + i + 1;
		} else
			break;
	}

skip_load_all:
	if (select_context_default == -1)
		fatal("Can't find plugin for %s", type);

	/* Insure that plugin_id is valid and unique */
	for (i=0; i<select_context_cnt; i++) {
		for (j=i+1; j<select_context_cnt; j++) {
			if (*(ops[i].plugin_id) !=
			    *(ops[j].plugin_id))
				continue;
			fatal("SelectPlugins: Duplicate plugin_id %u for "
			      "%s and %s",
			      *(ops[i].plugin_id),
			      select_context[i]->type,
			      select_context[j]->type);
		}
		if (*(ops[i].plugin_id) < 100) {
			fatal("SelectPlugins: Invalid plugin_id %u (<100) %s",
			      *(ops[i].plugin_id),
			      select_context[i]->type);
		}

	}
	init_run = true;

done:
	slurm_mutex_unlock( &select_context_lock );
	xfree(type);
	xfree(dir_array);
	return retval;
}
コード例 #22
0
ファイル: handle_bot.cpp プロジェクト: BNETDocs/pvpgn-server
		extern int handle_bot_packet(t_connection * c, t_packet const * const packet)
		{
			t_packet * rpacket;

			if (!c)
			{
				eventlog(eventlog_level_error, __FUNCTION__, "[{}] got NULL connection", conn_get_socket(c));
				return -1;
			}
			if (!packet)
			{
				eventlog(eventlog_level_error, __FUNCTION__, "[{}] got NULL packet", conn_get_socket(c));
				return -1;
			}
			if (packet_get_class(packet) != packet_class_raw)
			{
				eventlog(eventlog_level_error, __FUNCTION__, "[{}] got bad packet (class {})", conn_get_socket(c), (int)packet_get_class(packet));
				return -1;
			}

			{
				char const * const linestr = packet_get_str_const(packet, 0, MAX_MESSAGE_LEN);

				if (packet_get_size(packet) < 2) /* empty line */
					return 0;
				if (!linestr)
				{
					eventlog(eventlog_level_warn, __FUNCTION__, "[{}] line too long", conn_get_socket(c));
					return 0;
				}

				switch (conn_get_state(c))
				{
				case conn_state_connected:
					conn_add_flags(c, MF_PLUG);
					conn_set_clienttag(c, CLIENTTAG_BNCHATBOT_UINT);

					{
						char const * temp = linestr;

						if (temp[0] == '\004') /* FIXME: no echo, ignore for now (we always do no echo) */
							temp = &temp[1];

						if (temp[0] == '\0') /* empty line */
						{
							conn_set_state(c, conn_state_bot_username); /* don't look for ^D or reset tag and flags */
							break;
						}

						conn_set_state(c, conn_state_bot_password);

						if (conn_set_loggeduser(c, temp) < 0)
							eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not set username to \"{}\"", conn_get_socket(c), temp);

						{
							char const * const msg = "\r\nPassword: "******"[{}] could not create rpacket", conn_get_socket(c));
								break;
							}
#if 1 /* don't echo */
							packet_append_ntstring(rpacket, conn_get_loggeduser(c));
#endif
							packet_append_ntstring(rpacket, msg);
							conn_push_outqueue(c, rpacket);
							packet_del_ref(rpacket);
						}
					}
					break;

				case conn_state_bot_username:
					conn_set_state(c, conn_state_bot_password);

					if (conn_set_loggeduser(c, linestr) < 0)
						eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not set username to \"{}\"", conn_get_socket(c), linestr);

					{
						char const * const temp = "\r\nPassword: "******"[{}] could not create rpacket", conn_get_socket(c));
							break;
						}
#if 1 /* don't echo */
						packet_append_ntstring(rpacket, linestr);
#endif
						packet_append_ntstring(rpacket, temp);
						conn_push_outqueue(c, rpacket);
						packet_del_ref(rpacket);
					}
					break;

				case conn_state_bot_password:
				{
												char const * const tempa = "\r\nLogin failed.\r\n\r\nUsername: "******"\r\nAccount has no bot access.\r\n\r\nUsername: "******"[{}] could not create rpacket", conn_get_socket(c));
														break;
													}

													packet_append_ntstring(rpacket, tempa);
													conn_push_outqueue(c, rpacket);
													packet_del_ref(rpacket);
													break;
												}
												if (connlist_find_connection_by_accountname(loggeduser))
												{
													eventlog(eventlog_level_info, __FUNCTION__, "[{}] bot login for \"{}\" refused (already logged in)", conn_get_socket(c), loggeduser);
													conn_set_state(c, conn_state_bot_username);

													if (!(rpacket = packet_create(packet_class_raw)))
													{
														eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not create rpacket", conn_get_socket(c));
														break;
													}

													packet_append_ntstring(rpacket, tempa);
													conn_push_outqueue(c, rpacket);
													packet_del_ref(rpacket);
													break;
												}
												if (!(account = accountlist_find_account(loggeduser)))
												{
													eventlog(eventlog_level_info, __FUNCTION__, "[{}] bot login for \"{}\" refused (bad account)", conn_get_socket(c), loggeduser);
													conn_set_state(c, conn_state_bot_username);

													if (!(rpacket = packet_create(packet_class_raw)))
													{
														eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not create rpacket", conn_get_socket(c));
														break;
													}

													packet_append_ntstring(rpacket, tempa);
													conn_push_outqueue(c, rpacket);
													packet_del_ref(rpacket);
													break;
												}
												if ((oldstrhash1 = account_get_pass(account)))
												{
													if (hash_set_str(&oldpasshash1, oldstrhash1) < 0)
													{
														eventlog(eventlog_level_info, __FUNCTION__, "[{}] bot login for \"{}\" refused (corrupted passhash1?)", conn_get_socket(c), loggeduser);
														conn_set_state(c, conn_state_bot_username);

														if (!(rpacket = packet_create(packet_class_raw)))
														{
															eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not create rpacket", conn_get_socket(c));
															break;
														}

														packet_append_ntstring(rpacket, tempa);
														conn_push_outqueue(c, rpacket);
														packet_del_ref(rpacket);
														break;
													}

													testpass = xstrdup(linestr);
													{
														strtolower(testpass);
													}
													if (bnet_hash(&trypasshash1, std::strlen(testpass), testpass) < 0) /* FIXME: force to lowercase */
													{
														eventlog(eventlog_level_info, __FUNCTION__, "[{}] bot login for \"{}\" refused (unable to hash password)", conn_get_socket(c), loggeduser);
														conn_set_state(c, conn_state_bot_username);

														xfree((void *)testpass);

														if (!(rpacket = packet_create(packet_class_raw)))
														{
															eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not create rpacket", conn_get_socket(c));
															break;
														}

														packet_append_ntstring(rpacket, tempa);
														conn_push_outqueue(c, rpacket);
														packet_del_ref(rpacket);
														break;
													}
													xfree((void *)testpass);
													if (hash_eq(trypasshash1, oldpasshash1) != 1)
													{
														eventlog(eventlog_level_info, __FUNCTION__, "[{}] bot login for \"{}\" refused (wrong password)", conn_get_socket(c), loggeduser);
														conn_set_state(c, conn_state_bot_username);

														if (!(rpacket = packet_create(packet_class_raw)))
														{
															eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not create rpacket", conn_get_socket(c));
															break;
														}

														packet_append_ntstring(rpacket, tempa);
														conn_push_outqueue(c, rpacket);
														packet_del_ref(rpacket);
														break;
													}


													if (account_get_auth_botlogin(account) != 1) /* default to false */
													{
														eventlog(eventlog_level_info, __FUNCTION__, "[{}] bot login for \"{}\" refused (no bot access)", conn_get_socket(c), loggeduser);
														conn_set_state(c, conn_state_bot_username);

														if (!(rpacket = packet_create(packet_class_raw)))
														{
															eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not create rpacket", conn_get_socket(c));
															break;
														}

														packet_append_ntstring(rpacket, tempb);
														conn_push_outqueue(c, rpacket);
														packet_del_ref(rpacket);
														break;
													}
													else if (account_get_auth_lock(account) == 1) /* default to false */
													{
														eventlog(eventlog_level_info, __FUNCTION__, "[{}] bot login for \"{}\" refused (this account is locked)", conn_get_socket(c), loggeduser);
														conn_set_state(c, conn_state_bot_username);

														if (!(rpacket = packet_create(packet_class_raw)))
														{
															eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not create rpacket", conn_get_socket(c));
															break;
														}

														packet_append_ntstring(rpacket, tempb);
														conn_push_outqueue(c, rpacket);
														packet_del_ref(rpacket);
														break;
													}

													eventlog(eventlog_level_info, __FUNCTION__, "[{}] \"{}\" bot logged in (correct password)", conn_get_socket(c), loggeduser);
#ifdef WITH_LUA
													if (lua_handle_user(c, NULL, NULL, luaevent_user_login) == 1)
													{
														// feature to break login from Lua
														conn_set_state(c, conn_state_destroy);
														break;
													}
#endif
												}
												else
												{
													eventlog(eventlog_level_info, __FUNCTION__, "[{}] \"{}\" bot logged in (no password)", conn_get_socket(c), loggeduser);
												}
												if (!(rpacket = packet_create(packet_class_raw))) /* if we got this far, let them std::log in even if this fails */
													eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not create rpacket", conn_get_socket(c));
												else
												{
													packet_append_ntstring(rpacket, "\r\n");
													conn_push_outqueue(c, rpacket);
													packet_del_ref(rpacket);
												}

												conn_login(c, account, loggeduser);

												message_send_text(c, message_type_uniqueid, c, loggeduser);

												if (conn_set_channel(c, CHANNEL_NAME_CHAT) < 0)
													conn_set_channel(c, CHANNEL_NAME_BANNED); /* should not fail */
				}
					break;

				case conn_state_loggedin:
				{
											t_channel const * channel;

											conn_set_idletime(c);

											if ((channel = conn_get_channel(c)))
												channel_message_log(channel, c, 1, linestr);
											/* we don't log game commands currently */

											if (linestr[0] == '/')
												handle_command(c, linestr);
											else
											if (channel && !conn_quota_exceeded(c, linestr))
												channel_message_send(channel, message_type_talk, c, linestr);
											/* else discard */
				}
					break;

				default:
					eventlog(eventlog_level_error, __FUNCTION__, "[{}] unknown bot connection state {}", conn_get_socket(c), (int)conn_get_state(c));
				}
			}

			return 0;
		}
コード例 #23
0
static int
process_intf(struct distr_msg_hdr *hdr, const char *nodename,
             struct distr_msg_intf *intf, char *from)
{
    char *intfname;
    int remaining, offset;

    uint32_t handle = 0;
    int parent = 0, level = 0, link = 0, index = 0;

    intf_t *local_intf;
    node_t *remote_node;

    intfname = ((char *) intf) + sizeof(*intf);

    if (c_debug)
        fprintf(stderr, "Processing interface %s (offset: %d " \
                "optslen: %d namelen: %d hdrsize: %d)\n",
                intfname ? intfname : "null", ntohs(intf->i_offset),
                intf->i_optslen, intf->i_namelen, sizeof(*intf));

    if (intf->i_namelen < 4 || intf->i_namelen > IFNAME_MAX) {
        if (c_debug)
            fprintf(stderr, "Discarding malformed packet (invalid namelen %d)\n",
                    intf->i_namelen);
        return -1;
    }

    if ('\0' == *intfname) {
        if (c_debug)
            fprintf(stderr, "Discarding malformed packet (empty linkname)\n");
        return -1;
    }

    index = ntohs(intf->i_index);

    if (intf->i_optslen) {
        offset = sizeof(*intf) + intf->i_namelen;
        remaining = intf->i_optslen;

        while (remaining > 0) {
            struct distr_msg_ifopt *opt;

            opt = (struct distr_msg_ifopt *) (((char *) intf) + offset);

            if (opt->io_len > (remaining - sizeof(*opt))) {
                if (c_debug)
                    fprintf(stderr, "Discarding malformed packet (invalid opt len)\n");
                return -1;
            }

            switch (opt->io_type) {
            case IFOPT_HANDLE:
                if (opt->io_len != sizeof(uint32_t)) {
                    if (c_debug)
                        fprintf(stderr, "Discarding malformed packet " \
                                "(invalid opt len for handle)\n");
                    return -1;
                }

                handle = ntohl(*(uint32_t *) (((char *) opt) + sizeof (*opt)));
                break;

            case IFOPT_PARENT:
                parent = ntohs(opt->io_pad);
                break;

            case IFOPT_LEVEL:
                level = ntohs(opt->io_pad);
                break;

            case IFOPT_LINK:
                link = ntohs(opt->io_pad);
                break;
            }

            remaining -= (sizeof(*opt) + opt->io_len);
            offset += (sizeof(*opt) + opt->io_len);
        }

        if (remaining < 0)
            if (c_debug)
                fprintf(stderr, "Leftover from options: %d\n", abs(remaining));
    }

    remote_node = lookup_node(nodename, 1);

    if (NULL == remote_node) {
        if (c_debug)
            fprintf(stderr, "Could not create node entry for remote node\n");
        return -1;
    }

    if (remote_node->n_from)
        xfree((void *) remote_node->n_from);
    remote_node->n_from = strdup(from);

    local_intf = lookup_intf(remote_node, intfname, handle, parent);

    if (NULL == local_intf) {
        if (c_debug)
            fprintf(stderr, "Could not crate interface for remote interface\n");
        return -1;
    }

    offset = sizeof(*intf) + intf->i_optslen + intf->i_namelen;
    remaining = ntohs(intf->i_offset) - offset;

    while (remaining > 0) {
        struct distr_msg_attr *attr;
        attr = (struct distr_msg_attr *) (((char *) intf) + offset);

        if (c_debug)
            fprintf(stderr, "Attribute type %d %llu %llu\n",
                    attr->a_type, attr->a_rx, attr->a_tx);

        if (attr->a_type >= ATTR_MAX)
            goto skip;

        if (attr->a_type == BYTES) {
            local_intf->i_rx_bytes.r_total = attr->a_rx;
            local_intf->i_tx_bytes.r_total = attr->a_tx;
            local_intf->i_rx_bytes.r_overflows = attr->a_rx_overflows;
            local_intf->i_tx_bytes.r_overflows = attr->a_tx_overflows;
        } else if (attr->a_type == PACKETS) {
            local_intf->i_rx_packets.r_total = attr->a_rx;
            local_intf->i_tx_packets.r_total = attr->a_tx;
            local_intf->i_rx_packets.r_overflows = attr->a_rx_overflows;
            local_intf->i_tx_packets.r_overflows = attr->a_tx_overflows;
        } else {
            int flags = (attr->a_flags & ATTR_RX_PROVIDED ? RX_PROVIDED : 0) |
                        (attr->a_flags & ATTR_TX_PROVIDED ? TX_PROVIDED : 0);

            update_attr(local_intf, attr->a_type, attr->a_rx, attr->a_tx,
                        flags);
        }

skip:
        remaining -= sizeof(*attr);
        offset += sizeof(*attr);
    }

    if (intf->i_flags & IF_IS_CHILD)
        local_intf->i_is_child = 1;
    local_intf->i_level = level;
    local_intf->i_link = link;

    notify_update(local_intf);
    increase_lifetime(local_intf, 1);

    if (remaining < 0)
        if (c_debug)
            fprintf(stderr, "Leftover from attributes: %d\n", abs(remaining));

    return 0;
}
コード例 #24
0
ファイル: sk-packet.c プロジェクト: equivalence1/criu
int packet_receive_one(struct nlmsghdr *hdr, void *arg)
{
	struct packet_diag_msg *m;
	struct nlattr *tb[PACKET_DIAG_MAX + 1];
	struct packet_sock_desc *sd;

	m = NLMSG_DATA(hdr);
	nlmsg_parse(hdr, sizeof(struct packet_diag_msg),
			tb, PACKET_DIAG_MAX, NULL);
	pr_info("Collect packet sock %u %u\n", m->pdiag_ino, (unsigned int)m->pdiag_num);

	if (!tb[PACKET_DIAG_INFO]) {
		pr_err("No packet sock info in nlm\n");
		return -1;
	}

	if (!tb[PACKET_DIAG_MCLIST]) {
		pr_err("No packet sock mclist in nlm\n");
		return -1;
	}

	sd = xmalloc(sizeof(*sd));
	if (!sd)
		return -1;

	sd->file_id = 0;
	sd->type = m->pdiag_type;
	sd->proto = htons(m->pdiag_num);
	sd->rx = NULL;
	sd->tx = NULL;
	memcpy(&sd->nli, nla_data(tb[PACKET_DIAG_INFO]), sizeof(sd->nli));

	if (packet_save_mreqs(sd, tb[PACKET_DIAG_MCLIST]))
		goto err;

	if (tb[PACKET_DIAG_FANOUT])
		sd->fanout = *(__u32 *)RTA_DATA(tb[PACKET_DIAG_FANOUT]);
	else
		sd->fanout = NO_FANOUT;

	if (tb[PACKET_DIAG_RX_RING]) {
		sd->rx = xmalloc(sizeof(*sd->rx));
		if (sd->rx == NULL)
			goto err;
		memcpy(sd->rx, RTA_DATA(tb[PACKET_DIAG_RX_RING]), sizeof(*sd->rx));
	}

	if (tb[PACKET_DIAG_TX_RING]) {
		sd->tx = xmalloc(sizeof(*sd->tx));
		if (sd->tx == NULL)
			goto err;
		memcpy(sd->tx, RTA_DATA(tb[PACKET_DIAG_TX_RING]), sizeof(*sd->tx));
	}

	return sk_collect_one(m->pdiag_ino, PF_PACKET, &sd->sd);
err:
	xfree(sd->tx);
	xfree(sd->rx);
	xfree(sd);
	return -1;
}
コード例 #25
0
ファイル: job_submit_pbs.c プロジェクト: BYUHPC/slurm
static void _xlate_before(char *depend, uint32_t submit_uid, uint32_t my_job_id)
{
	uint32_t job_id;
	char *last_ptr = NULL, *new_dep = NULL, *tok, *type;
	struct job_record *job_ptr;
        pthread_attr_t attr;
	pthread_t dep_thread;


	tok = strtok_r(depend, ":", &last_ptr);
	if (!strcmp(tok, "before"))
		type = "after";
	else if (!strcmp(tok, "beforeany"))
		type = "afterany";
	else if (!strcmp(tok, "beforenotok"))
		type = "afternotok";
	else if (!strcmp(tok, "beforeok"))
		type = "afterok";
	else {
		info("%s: discarding invalid job dependency option %s",
		     plugin_type, tok);
		return;
	}

	tok = strtok_r(NULL, ":", &last_ptr);
	while (tok) {
		job_id = atoi(tok);
		job_ptr = find_job_record(job_id);
		if (!job_ptr) {
			info("%s: discarding invalid job dependency before %s",
			     plugin_type, tok);
		} else if ((submit_uid != job_ptr->user_id) &&
			   !validate_super_user(submit_uid)) {
			error("%s: Security violation: uid %u trying to alter "
			      "job %u belonging to uid %u", 
			      plugin_type, submit_uid, job_ptr->job_id,
			      job_ptr->user_id);
		} else if ((!IS_JOB_PENDING(job_ptr)) ||
			   (job_ptr->details == NULL)) {
			info("%s: discarding job before dependency on "
			     "non-pending job %u",
			     plugin_type, job_ptr->job_id);
		} else {
			if (job_ptr->details->dependency) {
				xstrcat(new_dep, job_ptr->details->dependency);
				xstrcat(new_dep, ",");
			}
			xstrfmtcat(new_dep, "%s:%u", type, my_job_id);
			xfree(job_ptr->details->dependency);
			job_ptr->details->dependency = new_dep;
			new_dep = NULL;
			_decr_depend_cnt(job_ptr);

			slurm_attr_init(&attr);
			pthread_attr_setdetachstate(&attr,
						    PTHREAD_CREATE_DETACHED);
			pthread_create(&dep_thread, &attr, _dep_agent, job_ptr);
			slurm_attr_destroy(&attr);
		}
		tok = strtok_r(NULL, ":", &last_ptr);
	}
}
コード例 #26
0
ファイル: t-protect.c プロジェクト: CryptoBITDigital/gnupg-1
static void
test_agent_protect (void)
{
  /* Protect the key encoded in canonical format in PLAINKEY.  We assume
     a valid S-Exp here. */

  unsigned int i;
  int ret;
  struct key_spec
  {
    const char *string;
  };
  /* Valid RSA key.  */
  struct key_spec key_rsa_valid =
    {
      "\x28\x31\x31\x3A\x70\x72\x69\x76\x61\x74\x65\x2D\x6B\x65\x79\x28\x33\x3A\x72\x73"
      "\x61\x28\x31\x3A\x6E\x31\x32\x39\x3A\x00\xB6\xB5\x09\x59\x6A\x9E\xCA\xBC\x93\x92"
      "\x12\xF8\x91\xE6\x56\xA6\x26\xBA\x07\xDA\x85\x21\xA9\xCA\xD4\xC0\x8E\x64\x0C\x04"
      "\x05\x2F\xBB\x87\xF4\x24\xEF\x1A\x02\x75\xA4\x8A\x92\x99\xAC\x9D\xB6\x9A\xBE\x3D"
      "\x01\x24\xE6\xC7\x56\xB1\xF7\xDF\xB9\xB8\x42\xD6\x25\x1A\xEA\x6E\xE8\x53\x90\x49"
      "\x5C\xAD\xA7\x3D\x67\x15\x37\xFC\xE5\x85\x0A\x93\x2F\x32\xBA\xB6\x0A\xB1\xAC\x1F"
      "\x85\x2C\x1F\x83\xC6\x25\xE7\xA7\xD7\x0C\xDA\x9E\xF1\x6D\x5C\x8E\x47\x73\x9D\x77"
      "\xDF\x59\x26\x1A\xBE\x84\x54\x80\x7F\xF4\x41\xE1\x43\xFB\xD3\x7F\x85\x45\x29\x28"
      "\x31\x3A\x65\x33\x3A\x01\x00\x01\x29\x28\x31\x3A\x64\x31\x32\x38\x3A\x07\x7A\xD3"
      "\xDE\x28\x42\x45\xF4\x80\x6A\x1B\x82\xB7\x9E\x61\x6F\xBD\xE8\x21\xC8\x2D\x69\x1A"
      "\x65\x66\x5E\x57\xB5\xFA\xD3\xF3\x4E\x67\xF4\x01\xE7\xBD\x2E\x28\x69\x9E\x89\xD9"
      "\xC4\x96\xCF\x82\x19\x45\xAE\x83\xAC\x7A\x12\x31\x17\x6A\x19\x6B\xA6\x02\x7E\x77"
      "\xD8\x57\x89\x05\x5D\x50\x40\x4A\x7A\x2A\x95\xB1\x51\x2F\x91\xF1\x90\xBB\xAE\xF7"
      "\x30\xED\x55\x0D\x22\x7D\x51\x2F\x89\xC0\xCD\xB3\x1A\xC0\x6F\xA9\xA1\x95\x03\xDD"
      "\xF6\xB6\x6D\x0B\x42\xB9\x69\x1B\xFD\x61\x40\xEC\x17\x20\xFF\xC4\x8A\xE0\x0C\x34"
      "\x79\x6D\xC8\x99\xE5\x29\x28\x31\x3A\x70\x36\x35\x3A\x00\xD5\x86\xC7\x8E\x5F\x1B"
      "\x4B\xF2\xE7\xCD\x7A\x04\xCA\x09\x19\x11\x70\x6F\x19\x78\x8B\x93\xE4\x4E\xE2\x0A"
      "\xAF\x46\x2E\x83\x63\xE9\x8A\x72\x25\x3E\xD8\x45\xCC\xBF\x24\x81\xBB\x35\x1E\x85"
      "\x57\xC8\x5B\xCF\xFF\x0D\xAB\xDB\xFF\x8E\x26\xA7\x9A\x09\x38\x09\x6F\x27\x29\x28"
      "\x31\x3A\x71\x36\x35\x3A\x00\xDB\x0C\xDF\x60\xF2\x6F\x2A\x29\x6C\x88\xD6\xBF\x9F"
      "\x8E\x5B\xE4\x5C\x0D\xDD\x71\x3C\x96\xCC\x73\xEB\xCB\x48\xB0\x61\x74\x09\x43\xF2"
      "\x1D\x2A\x93\xD6\xE4\x2A\x72\x11\xE7\xF0\x2A\x95\xDC\xED\x6C\x39\x0A\x67\xAD\x21"
      "\xEC\xF7\x39\xAE\x8A\x0C\xA4\x6F\xF2\xEB\xB3\x29\x28\x31\x3A\x75\x36\x34\x3A\x33"
      "\x14\x91\x95\xF1\x69\x12\xDB\x20\xA4\x8D\x02\x0D\xBC\x3B\x9E\x38\x81\xB3\x9D\x72"
      "\x2B\xF7\x93\x78\xF6\x34\x0F\x43\x14\x8A\x6E\x9F\xC5\xF5\x3E\x28\x53\xB7\x38\x7B"
      "\xA4\x44\x3B\xA5\x3A\x52\xFC\xA8\x17\x3D\xE6\xE8\x5B\x42\xF9\x78\x3D\x4A\x78\x17"
      "\xD0\x68\x0B\x29\x29\x29\x00"
    };
  /* This RSA key is missing the last closing brace.  */
  struct key_spec key_rsa_bogus_0 =
    {
      "\x28\x31\x31\x3A\x70\x72\x69\x76\x61\x74\x65\x2D\x6B\x65\x79\x28\x33\x3A\x72\x73"
      "\x61\x28\x31\x3A\x6E\x31\x32\x39\x3A\x00\xB6\xB5\x09\x59\x6A\x9E\xCA\xBC\x93\x92"
      "\x12\xF8\x91\xE6\x56\xA6\x26\xBA\x07\xDA\x85\x21\xA9\xCA\xD4\xC0\x8E\x64\x0C\x04"
      "\x05\x2F\xBB\x87\xF4\x24\xEF\x1A\x02\x75\xA4\x8A\x92\x99\xAC\x9D\xB6\x9A\xBE\x3D"
      "\x01\x24\xE6\xC7\x56\xB1\xF7\xDF\xB9\xB8\x42\xD6\x25\x1A\xEA\x6E\xE8\x53\x90\x49"
      "\x5C\xAD\xA7\x3D\x67\x15\x37\xFC\xE5\x85\x0A\x93\x2F\x32\xBA\xB6\x0A\xB1\xAC\x1F"
      "\x85\x2C\x1F\x83\xC6\x25\xE7\xA7\xD7\x0C\xDA\x9E\xF1\x6D\x5C\x8E\x47\x73\x9D\x77"
      "\xDF\x59\x26\x1A\xBE\x84\x54\x80\x7F\xF4\x41\xE1\x43\xFB\xD3\x7F\x85\x45\x29\x28"
      "\x31\x3A\x65\x33\x3A\x01\x00\x01\x29\x28\x31\x3A\x64\x31\x32\x38\x3A\x07\x7A\xD3"
      "\xDE\x28\x42\x45\xF4\x80\x6A\x1B\x82\xB7\x9E\x61\x6F\xBD\xE8\x21\xC8\x2D\x69\x1A"
      "\x65\x66\x5E\x57\xB5\xFA\xD3\xF3\x4E\x67\xF4\x01\xE7\xBD\x2E\x28\x69\x9E\x89\xD9"
      "\xC4\x96\xCF\x82\x19\x45\xAE\x83\xAC\x7A\x12\x31\x17\x6A\x19\x6B\xA6\x02\x7E\x77"
      "\xD8\x57\x89\x05\x5D\x50\x40\x4A\x7A\x2A\x95\xB1\x51\x2F\x91\xF1\x90\xBB\xAE\xF7"
      "\x30\xED\x55\x0D\x22\x7D\x51\x2F\x89\xC0\xCD\xB3\x1A\xC0\x6F\xA9\xA1\x95\x03\xDD"
      "\xF6\xB6\x6D\x0B\x42\xB9\x69\x1B\xFD\x61\x40\xEC\x17\x20\xFF\xC4\x8A\xE0\x0C\x34"
      "\x79\x6D\xC8\x99\xE5\x29\x28\x31\x3A\x70\x36\x35\x3A\x00\xD5\x86\xC7\x8E\x5F\x1B"
      "\x4B\xF2\xE7\xCD\x7A\x04\xCA\x09\x19\x11\x70\x6F\x19\x78\x8B\x93\xE4\x4E\xE2\x0A"
      "\xAF\x46\x2E\x83\x63\xE9\x8A\x72\x25\x3E\xD8\x45\xCC\xBF\x24\x81\xBB\x35\x1E\x85"
      "\x57\xC8\x5B\xCF\xFF\x0D\xAB\xDB\xFF\x8E\x26\xA7\x9A\x09\x38\x09\x6F\x27\x29\x28"
      "\x31\x3A\x71\x36\x35\x3A\x00\xDB\x0C\xDF\x60\xF2\x6F\x2A\x29\x6C\x88\xD6\xBF\x9F"
      "\x8E\x5B\xE4\x5C\x0D\xDD\x71\x3C\x96\xCC\x73\xEB\xCB\x48\xB0\x61\x74\x09\x43\xF2"
      "\x1D\x2A\x93\xD6\xE4\x2A\x72\x11\xE7\xF0\x2A\x95\xDC\xED\x6C\x39\x0A\x67\xAD\x21"
      "\xEC\xF7\x39\xAE\x8A\x0C\xA4\x6F\xF2\xEB\xB3\x29\x28\x31\x3A\x75\x36\x34\x3A\x33"
      "\x14\x91\x95\xF1\x69\x12\xDB\x20\xA4\x8D\x02\x0D\xBC\x3B\x9E\x38\x81\xB3\x9D\x72"
      "\x2B\xF7\x93\x78\xF6\x34\x0F\x43\x14\x8A\x6E\x9F\xC5\xF5\x3E\x28\x53\xB7\x38\x7B"
      "\xA4\x44\x3B\xA5\x3A\x52\xFC\xA8\x17\x3D\xE6\xE8\x5B\x42\xF9\x78\x3D\x4A\x78\x17"
      "\xD0\x68\x0B\x29\x29\x00"
    };
  /* This RSA key is the `e' value.  */
  struct key_spec key_rsa_bogus_1 =
    {
      "\x28\x31\x31\x3A\x70\x72\x69\x76\x61\x74\x65\x2D\x6B\x65\x79\x28\x33\x3A\x72\x73"
      "\x61\x28\x31\x3A\x6E\x31\x32\x39\x3A\x00\xA8\x80\xB6\x71\xF4\x95\x9F\x49\x84\xED"
      "\xC1\x1D\x5F\xFF\xED\x14\x7B\x9C\x6A\x62\x0B\x7B\xE2\x3E\x41\x48\x49\x85\xF5\x64"
      "\x50\x04\x9D\x30\xFC\x84\x1F\x01\xC3\xC3\x15\x03\x48\x6D\xFE\x59\x0B\xB0\xD0\x3E"
      "\x68\x8A\x05\x7A\x62\xB0\xB9\x6E\xC5\xD2\xA8\xEE\x0C\x6B\xDE\x5E\x3D\x8E\xE8\x8F"
      "\xB3\xAE\x86\x99\x7E\xDE\x2B\xC2\x4D\x60\x51\xDB\xB1\x2C\xD0\x38\xEC\x88\x62\x3E"
      "\xA9\xDD\x11\x53\x04\x17\xE4\xF2\x07\x50\xDC\x44\xED\x14\xF5\x0B\xAB\x9C\xBC\x24"
      "\xC6\xCB\xAD\x0F\x05\x25\x94\xE2\x73\xEB\x14\xD5\xEE\x5E\x18\xF0\x40\x31\x29\x28"
      "\x31\x3A\x64\x31\x32\x38\x3A\x40\xD0\x55\x9D\x2A\xA7\xBC\xBF\xE2\x3E\x33\x98\x71"
      "\x7B\x37\x3D\xB8\x38\x57\xA1\x43\xEA\x90\x81\x42\xCA\x23\xE1\xBF\x9C\xA8\xBC\xC5"
      "\x9B\xF8\x9D\x77\x71\xCD\xD3\x85\x8B\x20\x3A\x92\xE9\xBC\x79\xF3\xF7\xF5\x6D\x15"
      "\xA3\x58\x3F\xC2\xEB\xED\x72\xD4\xE0\xCF\xEC\xB3\xEC\xEB\x09\xEA\x1E\x72\x6A\xBA"
      "\x95\x82\x2C\x7E\x30\x95\x66\x3F\xA8\x2D\x40\x0F\x7A\x12\x4E\xF0\x71\x0F\x97\xDB"
      "\x81\xE4\x39\x6D\x24\x58\xFA\xAB\x3A\x36\x73\x63\x01\x77\x42\xC7\x9A\xEA\x87\xDA"
      "\x93\x8F\x6C\x64\xAD\x9E\xF0\xCA\xA2\x89\xA4\x0E\xB3\x25\x73\x29\x28\x31\x3A\x70"
      "\x36\x35\x3A\x00\xC3\xF7\x37\x3F\x9D\x93\xEC\xC7\x5E\x4C\xB5\x73\x29\x62\x35\x80"
      "\xC6\x7C\x1B\x1E\x68\x5F\x92\x56\x77\x0A\xE2\x8E\x95\x74\x87\xA5\x2F\x83\x2D\xF7"
      "\xA1\xC2\x78\x54\x18\x6E\xDE\x35\xF0\x9F\x7A\xCA\x80\x5C\x83\x5C\x44\xAD\x8B\xE7"
      "\x5B\xE2\x63\x7D\x6A\xC7\x98\x97\x29\x28\x31\x3A\x71\x36\x35\x3A\x00\xDC\x1F\xB1"
      "\xB3\xD8\x13\xE0\x09\x19\xFD\x1C\x58\xA1\x2B\x02\xB4\xC8\xF2\x1C\xE7\xF9\xC6\x3B"
      "\x68\xB9\x72\x43\x86\xEF\xA9\x94\x68\x02\xEF\x7D\x77\xE0\x0A\xD1\xD7\x48\xFD\xCD"
      "\x98\xDA\x13\x8A\x76\x48\xD4\x0F\x63\x28\xFA\x01\x1B\xF3\xC7\x15\xB8\x53\x22\x7E"
      "\x77\x29\x28\x31\x3A\x75\x36\x35\x3A\x00\xB3\xBB\x4D\xEE\x5A\xAF\xD0\xF2\x56\x8A"
      "\x10\x2D\x6F\x4B\x2D\x76\x49\x9B\xE9\xA8\x60\x5D\x9E\x7E\x50\x86\xF1\xA1\x0F\x28"
      "\x9B\x7B\xE8\xDD\x1F\x87\x4E\x79\x7B\x50\x12\xA7\xB4\x8B\x52\x38\xEC\x7C\xBB\xB9"
      "\x55\x87\x11\x1C\x74\xE7\x7F\xA0\xBA\xE3\x34\x5D\x61\xBF\x29\x29\x29\x00"
    };

  struct
  {
    const char *key;
    const char *passphrase;
    int no_result_expected;
    int compare_results;
    unsigned char *result_expected;
    size_t resultlen_expected;
    int ret_expected;
    unsigned char *result;
    size_t resultlen;
  } specs[] =
    {
      /* Invalid S-Expressions  */
      /* - non-NULL  */
      { "",
	"passphrase", 1, 0, NULL, 0, GPG_ERR_INV_SEXP, NULL, 0 },
      /* - NULL; disabled, this segfaults  */
      //{ NULL,
      //  "passphrase", 1, NULL, 0, GPG_ERR_INV_SEXP, NULL, 0 },

      /* Valid and invalid keys.  */
      { key_rsa_valid.string,
	"passphrase", 0, 0, NULL, 0, 0, NULL, 0 },
      { key_rsa_bogus_0.string,
	"passphrase", 0, 0, NULL, 0, GPG_ERR_INV_SEXP, NULL, 0 },
      { key_rsa_bogus_1.string,
	"passphrase", 0, 0, NULL, 0, GPG_ERR_INV_SEXP, NULL, 0 },

      /* FIXME: add more test data.  */
    };

  for (i = 0; i < DIM (specs); i++)
    {
      ret = agent_protect ((const unsigned char*)specs[i].key,
                           specs[i].passphrase,
			   &specs[i].result, &specs[i].resultlen, 0);
      if (gpg_err_code (ret) != specs[i].ret_expected)
	{
	  printf ("agent_protect() returned `%i/%s'; expected `%i/%s'\n",
		  ret, gpg_strerror (ret),
		  specs[i].ret_expected, gpg_strerror (specs[i].ret_expected));
	  abort ();
	}

      if (specs[i].no_result_expected)
	{
	  assert (! specs[i].result);
	  assert (! specs[i].resultlen);
	}
      else
	{
	  if (specs[i].compare_results)
	    {
	      assert (specs[i].resultlen == specs[i].resultlen_expected);
	      if (specs[i].result_expected)
		assert (! memcmp (specs[i].result, specs[i].result_expected,
				  specs[i].resultlen));
	      else
		assert (! specs[i].result);
	    }
	  xfree (specs[i].result);
	}
    }
}
コード例 #27
0
ファイル: kexgexs.c プロジェクト: 0x00evil/obfuscated-openssh
void
kexgex_server(Kex *kex)
{
	BIGNUM *shared_secret = NULL, *dh_client_pub = NULL;
	Key *server_host_key;
	DH *dh;
	u_char *kbuf, *hash, *signature = NULL, *server_host_key_blob = NULL;
	u_int sbloblen, klen, slen, hashlen;
	int omin = -1, min = -1, omax = -1, max = -1, onbits = -1, nbits = -1;
	int type, kout;

	if (kex->load_host_key == NULL)
		fatal("Cannot load hostkey");
	server_host_key = kex->load_host_key(kex->hostkey_type);
	if (server_host_key == NULL)
		fatal("Unsupported hostkey type %d", kex->hostkey_type);

	type = packet_read();
	switch (type) {
	case SSH2_MSG_KEX_DH_GEX_REQUEST:
		debug("SSH2_MSG_KEX_DH_GEX_REQUEST received");
		omin = min = packet_get_int();
		onbits = nbits = packet_get_int();
		omax = max = packet_get_int();
		min = MAX(DH_GRP_MIN, min);
		max = MIN(DH_GRP_MAX, max);
		nbits = MAX(DH_GRP_MIN, nbits);
		nbits = MIN(DH_GRP_MAX, nbits);
		break;
	case SSH2_MSG_KEX_DH_GEX_REQUEST_OLD:
		debug("SSH2_MSG_KEX_DH_GEX_REQUEST_OLD received");
		onbits = nbits = packet_get_int();
		/* unused for old GEX */
		omin = min = DH_GRP_MIN;
		omax = max = DH_GRP_MAX;
		break;
	default:
		fatal("protocol error during kex, no DH_GEX_REQUEST: %d", type);
	}
	packet_check_eom();

	if (omax < omin || onbits < omin || omax < onbits)
		fatal("DH_GEX_REQUEST, bad parameters: %d !< %d !< %d",
		    omin, onbits, omax);

	/* Contact privileged parent */
	dh = PRIVSEP(choose_dh(min, nbits, max));
	if (dh == NULL)
		packet_disconnect("Protocol error: no matching DH grp found");

	debug("SSH2_MSG_KEX_DH_GEX_GROUP sent");
	packet_start(SSH2_MSG_KEX_DH_GEX_GROUP);
	packet_put_bignum2(dh->p);
	packet_put_bignum2(dh->g);
	packet_send();

	/* flush */
	packet_write_wait();

	/* Compute our exchange value in parallel with the client */
	dh_gen_key(dh, kex->we_need * 8);

	debug("expecting SSH2_MSG_KEX_DH_GEX_INIT");
	packet_read_expect(SSH2_MSG_KEX_DH_GEX_INIT);

	/* key, cert */
	if ((dh_client_pub = BN_new()) == NULL)
		fatal("dh_client_pub == NULL");
	packet_get_bignum2(dh_client_pub);
	packet_check_eom();

#ifdef DEBUG_KEXDH
	fprintf(stderr, "dh_client_pub= ");
	BN_print_fp(stderr, dh_client_pub);
	fprintf(stderr, "\n");
	debug("bits %d", BN_num_bits(dh_client_pub));
#endif

#ifdef DEBUG_KEXDH
	DHparams_print_fp(stderr, dh);
	fprintf(stderr, "pub= ");
	BN_print_fp(stderr, dh->pub_key);
	fprintf(stderr, "\n");
#endif
	if (!dh_pub_is_valid(dh, dh_client_pub))
		packet_disconnect("bad client public DH value");

	klen = DH_size(dh);
	kbuf = xmalloc(klen);
	if ((kout = DH_compute_key(kbuf, dh_client_pub, dh)) < 0)
		fatal("DH_compute_key: failed");
#ifdef DEBUG_KEXDH
	dump_digest("shared secret", kbuf, kout);
#endif
	if ((shared_secret = BN_new()) == NULL)
		fatal("kexgex_server: BN_new failed");
	if (BN_bin2bn(kbuf, kout, shared_secret) == NULL)
		fatal("kexgex_server: BN_bin2bn failed");
	memset(kbuf, 0, klen);
	xfree(kbuf);

	key_to_blob(server_host_key, &server_host_key_blob, &sbloblen);

	if (type == SSH2_MSG_KEX_DH_GEX_REQUEST_OLD)
		omin = min = omax = max = -1;

	/* calc H */
	kexgex_hash(
	    kex->evp_md,
	    kex->client_version_string,
	    kex->server_version_string,
	    buffer_ptr(&kex->peer), buffer_len(&kex->peer),
	    buffer_ptr(&kex->my), buffer_len(&kex->my),
	    server_host_key_blob, sbloblen,
	    omin, onbits, omax,
	    dh->p, dh->g,
	    dh_client_pub,
	    dh->pub_key,
	    shared_secret,
	    &hash, &hashlen
	);
	BN_clear_free(dh_client_pub);

	/* save session id := H */
	if (kex->session_id == NULL) {
		kex->session_id_len = hashlen;
		kex->session_id = xmalloc(kex->session_id_len);
		memcpy(kex->session_id, hash, kex->session_id_len);
	}

	/* sign H */
	PRIVSEP(key_sign(server_host_key, &signature, &slen, hash, hashlen));

	/* destroy_sensitive_data(); */

	/* send server hostkey, DH pubkey 'f' and singed H */
	debug("SSH2_MSG_KEX_DH_GEX_REPLY sent");
	packet_start(SSH2_MSG_KEX_DH_GEX_REPLY);
	packet_put_string(server_host_key_blob, sbloblen);
	packet_put_bignum2(dh->pub_key);	/* f */
	packet_put_string(signature, slen);
	packet_send();

	xfree(signature);
	xfree(server_host_key_blob);
	/* have keys, free DH */
	DH_free(dh);

	kex_derive_keys(kex, hash, hashlen, shared_secret);
	BN_clear_free(shared_secret);

	kex_finish(kex);
}
コード例 #28
0
ファイル: req.c プロジェクト: gyliu513/slurm
static int
_handle_suspend(int fd, stepd_step_rec_t *job, uid_t uid)
{
	static int launch_poe = -1;
	int rc = SLURM_SUCCESS;
	int errnum = 0;

	debug("_handle_suspend for step=%u.%u uid=%d",
	      job->jobid, job->stepid, (int) uid);
	if (!_slurm_authorized_user(uid)) {
		debug("job step suspend request from uid %ld for job %u.%u ",
		      (long)uid, job->jobid, job->stepid);
		rc = -1;
		errnum = EPERM;
		goto done;
	}

	if (job->cont_id == 0) {
		debug ("step %u.%u invalid container [cont_id:%"PRIu64"]",
			job->jobid, job->stepid, job->cont_id);
		rc = -1;
		errnum = ESLURMD_JOB_NOTRUNNING;
		goto done;
	}

	acct_gather_suspend_poll();
	if (launch_poe == -1) {
		char *launch_type = slurm_get_launch_type();
		if (!strcmp(launch_type, "launch/poe"))
			launch_poe = 1;
		else
			launch_poe = 0;
		xfree(launch_type);
	}

	/*
	 * Signal the container
	 */
	pthread_mutex_lock(&suspend_mutex);
	if (suspended) {
		rc = -1;
		errnum = ESLURMD_STEP_SUSPENDED;
		pthread_mutex_unlock(&suspend_mutex);
		goto done;
	} else {
		/* SIGTSTP is sent first to let MPI daemons stop their tasks,
		 * then wait 2 seconds, then send SIGSTOP to the spawned
		 * process's container to stop everything else.
		 *
		 * In some cases, 1 second has proven insufficient. Longer
		 * delays may help insure that all MPI tasks have been stopped
		 * (that depends upon the MPI implementaiton used), but will
		 * also permit longer time periods when more than one job can
		 * be running on each resource (not good). */
		if (launch_poe == 0) {
			/* IBM MPI seens to periodically hang upon receipt
			 * of SIGTSTP. */
			if (proctrack_g_signal(job->cont_id, SIGTSTP) < 0) {
				verbose("Error suspending %u.%u (SIGTSTP): %m",
					job->jobid, job->stepid);
			} else
				sleep(2);
		}

		if (proctrack_g_signal(job->cont_id, SIGSTOP) < 0) {
			verbose("Error suspending %u.%u (SIGSTOP): %m",
				job->jobid, job->stepid);
		} else {
			verbose("Suspended %u.%u", job->jobid, job->stepid);
		}
		suspended = true;
	}
	/* reset the cpu frequencies if cpu_freq option used */
	if (job->cpu_freq != NO_VAL)
		cpu_freq_reset(job);

	pthread_mutex_unlock(&suspend_mutex);

done:
	/* Send the return code and errno */
	safe_write(fd, &rc, sizeof(int));
	safe_write(fd, &errnum, sizeof(int));
	return SLURM_SUCCESS;
rwfail:
	return SLURM_FAILURE;
}
コード例 #29
0
ファイル: rtps_sfrr.c プロジェクト: GerardoPardo/tinq-core
static void sfr_fragment (RemWriter_t     *rwp,
			  CCREF           *refp,
			  DataFragSMsg    *fragp,
			  FragInfo_t      **finfo,
			  const KeyHash_t *hp,
			  Change_t        *cp,
			  int             ooo,
			  int             ignore)
{
	Change_t		*xcp, *ncp;
	FragInfo_t		*fip;
	Reader_t		*rp;
	const TypeSupport_t	*ts;
	unsigned		max_frags, size;
	int			all_key, error;
	HCI			hci;
	InstanceHandle		h;
	RejectCause_t		cause;
	DBW			walk;

	/* If this is the first fragment, create the fragments context. */
	fip = refp->fragments;
	if (!fip) {
		if (refp->relevant) {

			/* Replace change with empty one. */
			ncp = hc_change_new ();
			if (!ncp) {
				refp->state = CS_MISSING;
				return;
			}
			xcp = refp->u.c.change;
			ncp->c_kind = xcp->c_kind;
			ncp->c_writer = xcp->c_writer;
			ncp->c_time = xcp->c_time;
			ncp->c_seqnr = xcp->c_seqnr;
			hc_change_free (xcp);
			refp->u.c.change = ncp;
		}
		else {
			refp->state = CS_RECEIVED;
			goto done;
		}
		fip = *finfo;
		if (fip) {
			rcl_access (fip);
			fip->nrefs++;
			rcl_done (fip);
			refp->fragments = fip;
		}
		else {
			max_frags = (fragp->sample_size + fragp->frag_size - 1) / fragp->frag_size;
			if (fragp->frag_start + fragp->num_fragments - 1 > max_frags) {

			    no_frag_mem:

				refp->state = CS_MISSING;
				if (refp->u.c.change)
					hc_change_free (refp->u.c.change);
				return;
			}

			*finfo = fip = rfraginfo_create (refp, fragp, max_frags);
			if (!fip)
				goto no_frag_mem;
		}
	}

	/* If this is the first fragment and we already have a fragmentation
	   context, and the data needs to be ignored, we abort reception. */
	else if (refp->relevant && fragp->frag_start == 1 && ignore) {
		xcp = refp->u.c.change;
		refp->state = CS_RECEIVED;
		refp->relevant = 0;
		refp->u.range.first = refp->u.range.last = xcp->c_seqnr;
		hc_change_free (xcp);
		goto done_clean_fip;
	}

	/* Update key info if present. */
	if (hp) {
		fip->hash = *hp;
		fip->hp = &fip->hash;
	}

	/* Mark the fragment as correctly received. */
	mark_fragment (fip, fragp, cp);

	/* If more fragments pending, simply exit, waiting for the next. */
	if (fip->num_na)
		return;

	/* Data complete! Derive key info and get a new instance if possible. */
	/* If data type indicates multi-instance data, we need the actual keys
	   in order to lookup instances properly. */
	/*log_printf (RTPS_ID, 0, "sfr_fragment: complete!\r\n");*/
	rp = (Reader_t *) rwp->rw_reader->endpoint.endpoint;
	ts = rp->r_topic->type->type_support;
	if (!refp->relevant || !ts->ts_keys) {
		if (!hc_accepts (rp->r_cache, ooo)) {

			/* Don't see this as rejected -- since there is no ack
			   given, last fragment will simply be retransmitted!
			dcps_sample_rejected ((Reader_t *) ep->endpoint,
					      DDS_REJECTED_BY_SAMPLES_LIMIT, 0);*/
			if (!ooo)
				rwp->rw_blocked = 1;

		    ignore_last_fragment:

			fip->num_na = 1;
			fip->first_na = fragp->frag_start + fragp->num_fragments - 2;
			SET_REM (fip->bitmap, fip->first_na);
			return;
		}
		else
			goto no_keys;
	}

	/* Key somewhere in either marshalled data or marshalled key.
	   Derive key information if not yet done. */
	if (!fip->key) {
		if (fip->length) {
			walk.dbp = fip->data;
			walk.data = fip->data->data;
			walk.left = walk.length = fip->length;
		}
		all_key = cp->c_kind != ALIVE;
		size = ts->ts_mkeysize;
		if (!size || !ts->ts_fksize) {
			size = DDS_KeySizeFromMarshalled (walk, ts,
							all_key, NULL);
			if (!size)
				goto cleanup;
		}
		fip->keylen = size;
		if (ts->ts_mkeysize && ts->ts_fksize && size <= sizeof (KeyHash_t)) {
			if (fip->hp) {
				fip->key = fip->hash.hash;
				goto got_keys;
			}
			if (size < sizeof (KeyHash_t))
				memset (fip->hash.hash + size, 0,
						     sizeof (KeyHash_t) - size);
		}
		else {
			fip->key = xmalloc (size);
			if (!fip->key)
				goto ignore_last_fragment;
		}
		error = DDS_KeyFromMarshalled (fip->key, walk, ts, all_key);
		if (error) {
			if (fip->key != fip->hash.hash)
				xfree (fip->key);

			fip->key = NULL;
			goto cleanup;
		}
		if (!fip->hp) {
			error = DDS_HashFromKey (fip->hash.hash, fip->key, size, ts);
			if (error) {
				if (fip->key != fip->hash.hash)
					xfree (fip->key);

				fip->key = NULL;
				goto cleanup;
			}
			fip->hp = &fip->hash;
		}
	}

    got_keys:

	/* Key information is present in the fragment context now.
	   Derive a new or existing cache instance context. */
	hci = hc_lookup_hash (rp->r_cache,
			      fip->hp, fip->key, fip->keylen,
			      &h, 1, ooo, &cause);
	if (!hci) {

		/* Don't see this as rejected -- since there is no ack
		   given, last fragment will simply be retransmitted!
		dcps_sample_rejected ((Reader_t *) ep->endpoint,
				      (DDS_SampleRejectedStatusKind) cause,
				      h);*/
		if (!ooo)
			rwp->rw_blocked = 1;
		goto ignore_last_fragment;
	}
	refp->u.c.hci = hci;
       refp->u.c.change->c_handle = h;
	hc_inst_inform (rp->r_cache, hci);

    no_keys:

	/* Transform to a valid received sample, as if this was a normal DATA
	   submessage. */
	if (refp->relevant) {
		xcp = refp->u.c.change;
		xcp->c_db = fip->data;
		xcp->c_data = fip->data->data;
		xcp->c_length = fip->length;
		rcl_access (xcp);
		xcp->c_db->nrefs++;
		rcl_done (xcp);
	}

    done_clean_fip:

    	/* Cleanup fragmentation context. */
	if (fip->nrefs == 1)
		*finfo = NULL;
	rfraginfo_delete (refp);

    done:

	/* If received sample is first, add samples to history cache. */
	sfr_process_samples (rwp);
	return;

    cleanup:
	refp->state = CS_MISSING;
	xcp = refp->u.c.change;
	refp->relevant = 0;
	refp->fragments = NULL;
	refp->u.range.first = refp->u.range.last = xcp->c_seqnr;
	hc_change_free (xcp);
	rfraginfo_delete (refp);
}
コード例 #30
0
ファイル: iri.c プロジェクト: rockdaboot/mget
mget_iri_t *mget_iri_parse(const char *url, const char *encoding)
{
	mget_iri_t *iri;
	const char *default_port = NULL;
	char *p, *s, *authority, c;
	size_t slen, it;
	int url_allocated, maybe_scheme;

	if (!url)
		return NULL;

	/*
		URI         = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
		hier-part   = "//" authority path-abempty / path-absolute / path-rootless / path-empty
		scheme      =  ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
	 */
	while (isspace(*url)) url++;
	if (!*url) return NULL;

	// first unescape, than convert to UTF-8
	if (strchr(url, '%')) {
		char *unesc_url = strdup(url);

		mget_percent_unescape(unesc_url);

		if (mget_str_needs_encoding(unesc_url)) {
			if ((url = mget_str_to_utf8(unesc_url, encoding)))
				xfree(unesc_url);
			else
				url = unesc_url; // on error, use what we have
		} else
			url = unesc_url;

		url_allocated = 1;
	} else {
		url_allocated = 0;

		if (mget_str_needs_encoding(url)) {
			if ((s = mget_str_to_utf8(url, encoding))) {
				url = s;
				url_allocated = 1;
			}
		}
	}

	// just use one block of memory for all parsed URI parts
	slen = strlen(url);
	iri = xmalloc(sizeof(mget_iri_t) + slen * 2 + 2);
	memset(iri, 0, sizeof(mget_iri_t));
	strcpy(((char *)iri) + sizeof(mget_iri_t), url);
	iri->uri = ((char *)iri) + sizeof(mget_iri_t);
	s = ((char *)iri) + sizeof(mget_iri_t) + slen + 1;
	strcpy(s, url);
	if (url_allocated)
		xfree(url);

	p = s;
	if (isalpha(*p)) {
		maybe_scheme = 1;
		while (*s && !_iri_isgendelim(*s)) {
			if (maybe_scheme && !_iri_isscheme(*s))
				maybe_scheme = 0;
			s++;
		}
	} else
		maybe_scheme = 0;

	if (maybe_scheme && (*s == ':' && (s[1] == '/' || s[1] == 0))) {
		// found a scheme
		*s++ = 0;

		// find the scheme in our static list of supported schemes
		// for later comparisons we compare pointers (avoiding strcasecmp())
		iri->scheme = p;
		for (it = 0; mget_iri_schemes[it]; it++) {
			if (!mget_strcasecmp_ascii(mget_iri_schemes[it], p)) {
				iri->scheme = mget_iri_schemes[it];
				default_port = iri_ports[it];
				break;
			}
		}

		if (iri->scheme == p) {
			// convert scheme to lowercase
			mget_strtolower((char *)iri->scheme);
		}

	} else {
		iri->scheme = MGET_IRI_SCHEME_DEFAULT;
		default_port = iri_ports[0]; // port 80
		s = p; // rewind
	}

	// this is true for http, https, ftp, file
	if (s[0] == '/' && s[1] == '/')
		s += 2;

	// authority
	authority = s;
	while (*s && *s != '/' && *s != '?' && *s != '#')
		s++;
	c = *s;
	if (c) *s++ = 0;

	// left over: [path][?query][#fragment]
	if (c == '/') {
		iri->path = s;
		while (*s && *s != '?' && *s != '#')
			s++;
		c = *s;
		if (c) *s++ = 0;
	}

	if (c == '?') {
		iri->query = s;
		while (*s && *s != '#')
			s++;
		c = *s;
		if (c) *s++ = 0;
	}

	if (c == '#') {
		iri->fragment = s;
		s += strlen(s);
	}

	if (*s) {
		debug_printf("unparsed rest '%s'\n", s);
	}

	if (*authority) {
		s = authority;
		p = strchr(authority, '@');
		if (p) {
			iri->userinfo = s;
			*p = 0;
			s = p + 1;
		}
		if (*s == '[') {
			p = strrchr(s, ']');
			if (p) {
				iri->host = s + 1;
				*p = 0;
				s = p + 1;
			} else {
				// something is broken
				iri->host = s + 1;
				s += strlen(s);
			}
		} else {
			iri->host = s;
			while (*s && *s != ':')
				s++;
		}
		if (*s == ':') {
			if (s[1]) {
				if (!default_port || (strcmp(s + 1, default_port) && atoi(s + 1) != atoi(default_port)))
					iri->port = s + 1;
			}
		}
		*s = 0;
 	}

	iri->resolv_port = iri->port ? iri->port : default_port;

	// now unescape all components (not interested in display, userinfo, password)
	if (iri->host) {
		mget_strtolower((char *)iri->host);
		if ((p = (char *)mget_str_to_ascii(iri->host)) != iri->host) {
			iri->host = p;
			iri->host_allocated = 1;
		}
	}
	else {
		if (iri->scheme == MGET_IRI_SCHEME_HTTP || iri->scheme == MGET_IRI_SCHEME_HTTPS) {
			error_printf(_("Missing host/domain in URI '%s'\n"), iri->uri);
			mget_iri_free(&iri);
			return NULL;
		}
	}

/*
	debug_printf("scheme=%s\n",iri->scheme);
	debug_printf("host=%s\n",iri->host);
	debug_printf("path=%s\n",iri->path);
	debug_printf("query=%s\n",iri->query);
	debug_printf("fragment=%s\n",iri->fragment);
*/

	return iri;
}