Example #1
0
static int open_file( char *psz_filename, hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
{
    FILE *fh = fopen( psz_filename, "r" );
    if( !fh )
        return -1;
    FAIL_IF_ERROR( !x264_is_regular_file( fh ), "AVS input is incompatible with non-regular file `%s'\n", psz_filename );
    fclose( fh );

    avs_hnd_t *h = malloc( sizeof(avs_hnd_t) );
    if( !h )
        return -1;
    FAIL_IF_ERROR( x264_avs_load_library( h ), "failed to load avisynth\n" )
    h->env = h->func.avs_create_script_environment( AVS_INTERFACE_25 );
    FAIL_IF_ERROR( !h->env, "failed to initiate avisynth\n" )
    AVS_Value arg = avs_new_value_string( psz_filename );
    AVS_Value res;
    char *filename_ext = get_filename_extension( psz_filename );

    if( !strcasecmp( filename_ext, "avs" ) )
    {
        res = h->func.avs_invoke( h->env, "Import", arg, NULL );
        FAIL_IF_ERROR( avs_is_error( res ), "%s\n", avs_as_string( res ) )
        /* check if the user is using a multi-threaded script and apply distributor if necessary.
           adapted from avisynth's vfw interface */
        AVS_Value mt_test = h->func.avs_invoke( h->env, "GetMTMode", avs_new_value_bool( 0 ), NULL );
        int mt_mode = avs_is_int( mt_test ) ? avs_as_int( mt_test ) : 0;
        h->func.avs_release_value( mt_test );
        if( mt_mode > 0 && mt_mode < 5 )
        {
            AVS_Value temp = h->func.avs_invoke( h->env, "Distributor", res, NULL );
            h->func.avs_release_value( res );
            res = temp;
        }
    }
    else /* non script file */
    {
        /* cycle through known source filters to find one that works */
        const char *filter[AVS_MAX_SEQUENCE+1] = { 0 };
        avs_build_filter_sequence( filename_ext, filter );
        int i;
        for( i = 0; filter[i]; i++ )
        {
            x264_cli_log( "avs", X264_LOG_INFO, "trying %s... ", filter[i] );
            if( !h->func.avs_function_exists( h->env, filter[i] ) )
            {
                x264_cli_printf( X264_LOG_INFO, "not found\n" );
                continue;
            }
            if( !strncasecmp( filter[i], "FFmpegSource", 12 ) )
            {
                x264_cli_printf( X264_LOG_INFO, "indexing... " );
                fflush( stderr );
            }
            res = h->func.avs_invoke( h->env, filter[i], arg, NULL );
            if( !avs_is_error( res ) )
            {
                x264_cli_printf( X264_LOG_INFO, "succeeded\n" );
                break;
            }
            x264_cli_printf( X264_LOG_INFO, "failed\n" );
        }
        FAIL_IF_ERROR( !filter[i], "unable to find source filter to open `%s'\n", psz_filename )
    }
    FAIL_IF_ERROR( !avs_is_clip( res ), "`%s' didn't return a video clip\n", psz_filename )
    h->clip = h->func.avs_take_clip( res, h->env );
    const AVS_VideoInfo *vi = h->func.avs_get_video_info( h->clip );
    FAIL_IF_ERROR( !avs_has_video( vi ), "`%s' has no video data\n", psz_filename )
    /* if the clip is made of fields instead of frames, call weave to make them frames */
    if( avs_is_field_based( vi ) )
    {
        x264_cli_log( "avs", X264_LOG_WARNING, "detected fieldbased (separated) input, weaving to frames\n" );
        AVS_Value tmp = h->func.avs_invoke( h->env, "Weave", res, NULL );
        FAIL_IF_ERROR( avs_is_error( tmp ), "couldn't weave fields into frames\n" )
        res = update_clip( h, &vi, tmp, res );
        info->interlaced = 1;
        info->tff = avs_is_tff( vi );
    }
#if !HAVE_SWSCALE
    /* if swscale is not available, convert CSPs to yv12 */
    if( !avs_is_yv12( vi ) )
    {
        x264_cli_log( "avs", X264_LOG_WARNING, "converting input clip to YV12\n" );
        FAIL_IF_ERROR( vi->width&1 || vi->height&1, "input clip width or height not divisible by 2 (%dx%d)\n", vi->width, vi->height )
        const char *arg_name[2] = { NULL, "interlaced" };
        AVS_Value arg_arr[2] = { res, avs_new_value_bool( info->interlaced ) };
        AVS_Value res2 = h->func.avs_invoke( h->env, "ConvertToYV12", avs_new_value_array( arg_arr, 2 ), arg_name );
        FAIL_IF_ERROR( avs_is_error( res2 ), "couldn't convert input clip to YV12\n" )
        res = update_clip( h, &vi, res2, res );
    }
Example #2
0
int
dt_colorspaces_get_darktable_matrix(const char *makermodel, float *matrix)
{
  dt_profiled_colormatrix_t *preset = NULL;
  for(int k=0; k<dt_profiled_colormatrix_cnt; k++)
  {
    if(!strcasecmp(makermodel, dt_profiled_colormatrices[k].makermodel))
    {
      preset = dt_profiled_colormatrices + k;
      break;
    }
  }
  if(!preset) return -1;

  const float wxyz = preset->white[0]+ preset->white[1]+ preset->white[2];
  const float rxyz = preset->rXYZ[0] + preset->rXYZ[1] + preset->rXYZ[2];
  const float gxyz = preset->gXYZ[0] + preset->gXYZ[1] + preset->gXYZ[2];
  const float bxyz = preset->bXYZ[0] + preset->bXYZ[1] + preset->bXYZ[2];

  const float xn = preset->white[0]/wxyz;
  const float yn = preset->white[1]/wxyz;
  const float xr = preset->rXYZ[0]/rxyz;
  const float yr = preset->rXYZ[1]/rxyz;
  const float xg = preset->gXYZ[0]/gxyz;
  const float yg = preset->gXYZ[1]/gxyz;
  const float xb = preset->bXYZ[0]/bxyz;
  const float yb = preset->bXYZ[1]/bxyz;

  const float primaries[9] = {xr,         xg,         xb,
                              yr,         yg,         yb,
                              1.0f-xr-yr, 1.0f-xg-yg, 1.0f-xb-yb
                             };

  float result[9];
  if(mat3inv(result, primaries)) return -1;

  const float whitepoint[3] = {xn/yn, 1.0f, (1.0f-xn-yn)/yn};
  float coeff[3];

  // get inverse primary whitepoint
  mat3mulv(coeff, result, whitepoint);


  float tmp[9] = { coeff[0]*xr,           coeff[1]*xg,           coeff[2]*xb,
                   coeff[0]*yr,           coeff[1]*yg,           coeff[2]*yb,
                   coeff[0]*(1.0f-xr-yr), coeff[1]*(1.0f-xg-yg), coeff[2]*(1.0f-xb-yb)
                 };

  // input whitepoint[] in XYZ with Y normalized to 1.0f
  const float dn[3] = { preset->white[0]/(float)preset->white[1], 1.0f, preset->white[2]/(float)preset->white[1]};
  const float lam_rigg[9] = { 0.8951,  0.2664, -0.1614,
                              -0.7502,  1.7135,  0.0367,
                              0.0389, -0.0685,  1.0296
                            };
  const float d50[3] = { 0.9642, 1.0, 0.8249 };


  // adapt to d50
  float chad_inv[9];
  if(mat3inv(chad_inv, lam_rigg)) return -1;

  float cone_src_rgb[3], cone_dst_rgb[3];
  mat3mulv(cone_src_rgb, lam_rigg, dn);
  mat3mulv(cone_dst_rgb, lam_rigg, d50);

  const float cone[9] = { cone_dst_rgb[0]/cone_src_rgb[0], 0.0f, 0.0f,
                          0.0f, cone_dst_rgb[1]/cone_src_rgb[1], 0.0f,
                          0.0f, 0.0f, cone_dst_rgb[2]/cone_src_rgb[2]
                        };

  float tmp2[9];
  float bradford[9];
  mat3mul(tmp2, cone, lam_rigg);
  mat3mul(bradford, chad_inv, tmp2);

  mat3mul(matrix, bradford, tmp);
  return 0;
}
Example #3
0
/*
 * scontrol_update_node - update the slurm node configuration per the supplied
 *	arguments
 * IN argc - count of arguments
 * IN argv - list of arguments
 * RET 0 if no slurm error, errno otherwise. parsing error prints
 *			error message and returns 0
 */
extern int
scontrol_update_node (int argc, char *argv[])
{
	int i, j, rc = 0, update_cnt = 0;
	uint16_t state_val;
	update_node_msg_t node_msg;
	char *reason_str = NULL;
	char *tag, *val;
	int tag_len, val_len;

	slurm_init_update_node_msg(&node_msg);
	for (i=0; i<argc; i++) {
		tag = argv[i];
		val = strchr(argv[i], '=');
		if (val) {
			tag_len = val - argv[i];
			val++;
			val_len = strlen(val);
		} else {
			exit_code = 1;
			error("Invalid input: %s  Request aborted", argv[i]);
			return -1;
		}

		if (strncasecmp(tag, "NodeAddr", MAX(tag_len, 5)) == 0) {
			node_msg.node_addr = val;
			update_cnt++;
		} else if (strncasecmp(tag, "NodeHostName", MAX(tag_len, 5))
			   == 0) {
			node_msg.node_hostname = val;
			update_cnt++;
		} else if (strncasecmp(tag, "NodeName", MAX(tag_len, 1)) == 0) {
			node_msg.node_names = val;
		} else if (strncasecmp(tag, "Features", MAX(tag_len, 1)) == 0) {
			node_msg.features = val;
			update_cnt++;
		} else if (strncasecmp(tag, "Gres", MAX(tag_len, 1)) == 0) {
			node_msg.gres = val;
			update_cnt++;
		} else if (strncasecmp(tag, "Weight", MAX(tag_len,1)) == 0) {
			/* Logic borrowed from function _handle_uint32 */
			char *endptr;
			unsigned long num;
			errno = 0;
			num = strtoul(val, &endptr, 0);
			if ((endptr[0] == 'k') || (endptr[0] == 'K')) {
				num *= 1024;
				endptr++;
			}
			if ((num == 0 && errno == EINVAL)
        		            || (*endptr != '\0')) {
				if ((strcasecmp(val, "UNLIMITED") == 0) ||
				    (strcasecmp(val, "INFINITE")  == 0)) {
					num = (uint32_t) INFINITE;
				} else {
					error("Weight value (%s) is not a "
					      "valid number", val);
					break;
				}
			} else if (errno == ERANGE) {
				error("Weight value (%s) is out of range",
				      val);
				break;
			} else if (val[0] == '-') {
				error("Weight value (%s) is less than zero",
				      val);
				break;
			} else if (num > 0xfffffff0) {
				error("Weight value (%s) is greater than %u",
					val, 0xfffffff0);
				break;
			}
			node_msg.weight = num;
			update_cnt++;
		} else if (strncasecmp(tag, "Reason", MAX(tag_len, 1)) == 0) {
			int len = strlen(val);
			reason_str = xmalloc(len+1);
			if (*val == '"')
				strcpy(reason_str, val+1);
			else
				strcpy(reason_str, val);

			len = strlen(reason_str) - 1;
			if ((len >= 0) && (reason_str[len] == '"'))
				reason_str[len] = '\0';

			node_msg.reason = reason_str;
			if ((getlogin() == NULL) ||
			    (uid_from_string(getlogin(),
					     &node_msg.reason_uid) < 0)) {
				node_msg.reason_uid = getuid();
			}
			update_cnt++;
		}
		else if (strncasecmp(tag, "State", MAX(tag_len, 1)) == 0) {
			if (cluster_flags & CLUSTER_FLAG_CRAY_A) {
				fprintf (stderr, "%s can not be changed through"
					 " SLURM. Use native Cray tools such as"
					 " xtprocadmin(8)\n", argv[i]);
				fprintf (stderr, "Request aborted\n");
				exit_code = 1;
				goto done;
			}
			if (strncasecmp(val, "NoResp",
				        MAX(val_len, 3)) == 0) {
				node_msg.node_state = NODE_STATE_NO_RESPOND;
				update_cnt++;
			} else if (strncasecmp(val, "DRAIN",
				   MAX(val_len, 3)) == 0) {
				node_msg.node_state = NODE_STATE_DRAIN;
				update_cnt++;
			} else if (strncasecmp(val, "FAIL",
				   MAX(val_len, 3)) == 0) {
				node_msg.node_state = NODE_STATE_FAIL;
				update_cnt++;
			} else if (strncasecmp(val, "FUTURE",
				   MAX(val_len, 3)) == 0) {
				node_msg.node_state = NODE_STATE_FUTURE;
				update_cnt++;
			} else if (strncasecmp(val, "RESUME",
				   MAX(val_len, 3)) == 0) {
				node_msg.node_state = NODE_RESUME;
				update_cnt++;
			} else if (strncasecmp(val, "POWER_DOWN",
				   MAX(val_len, 7)) == 0) {
				node_msg.node_state = NODE_STATE_POWER_SAVE;
				update_cnt++;
			} else if (strncasecmp(val, "POWER_UP",
				   MAX(val_len, 7)) == 0) {
				node_msg.node_state = NODE_STATE_POWER_UP;
				update_cnt++;
			} else if (strncasecmp(val, "UNDRAIN",
				   MAX(val_len, 3)) == 0) {
				node_msg.node_state = NODE_STATE_UNDRAIN;
				update_cnt++;
			} else {
				state_val = (uint16_t) NO_VAL;
				for (j = 0; j < NODE_STATE_END; j++) {
					if (strncasecmp (node_state_string(j),
							 val,
							 MAX(val_len, 3)) == 0){
						state_val = (uint16_t) j;
						break;
					}
				}
				if (j == NODE_STATE_END) {
					exit_code = 1;
					fprintf(stderr, "Invalid input: %s\n",
						argv[i]);
					fprintf (stderr, "Request aborted\n");
					fprintf (stderr, "Valid states are: ");
					fprintf (stderr,
						 "NoResp DRAIN FAIL FUTURE RESUME "
						 "POWER_DOWN POWER_UP UNDRAIN");
					fprintf (stderr, "\n");
					fprintf (stderr,
						 "Not all states are valid "
						 "given a node's prior "
						 "state\n");
					goto done;
				}
				node_msg.node_state = state_val;
				update_cnt++;
			}
		} else {
			exit_code = 1;
			fprintf (stderr, "Update of this parameter is not "
				 "supported: %s\n", argv[i]);
			fprintf (stderr, "Request aborted\n");
			goto done;
		}
	}

	if (((node_msg.node_state == NODE_STATE_DOWN)  ||
	     (node_msg.node_state == NODE_STATE_DRAIN) ||
	     (node_msg.node_state == NODE_STATE_FAIL)) &&
	    ((node_msg.reason == NULL) || (strlen(node_msg.reason) == 0))) {
		fprintf(stderr, "You must specify a reason when DOWNING or "
			"DRAINING a node. Request denied\n");
		goto done;
	}

	if (update_cnt == 0) {
		exit_code = 1;
		fprintf (stderr, "No changes specified\n");
		return 0;
	}

	rc = slurm_update_node(&node_msg);

done:	xfree(reason_str);
	if (rc) {
		exit_code = 1;
		return slurm_get_errno ();
	} else
		return 0;
}
Example #4
0
int main(int argc, char** argv)
{
   unsigned int cmd = 0;
   unsigned int attr = ATTR_NONE;
   int ret = 0;
   int fd = 0;

   if (argc < 4)
   {
      fprintf(stderr,"usage: %s [get|set] filename [BASE_10_VALUE]\n",argv[0]);
      return -1;
   }
	
   fd = open(argv[2], 0);
   if (fd < 0)
   {
      fprintf(stderr,"can't open file: %s\n", argv[2]);
      return -1;
   }
   else
   {
      printf("opened file: %s\n", argv[2]);
   }

   if (strcasecmp(argv[1],"set") == 0)
   {
      attr = atoi(argv[3]);
      cmd = FAT_IOCTL_SET_ATTRIBUTES;
   }
   else if (strcasecmp(argv[1],"get") == 0)
   {
      cmd = FAT_IOCTL_GET_ATTRIBUTES;
   }
   else
   {
      fprintf(stderr,"unknown option %s\n",argv[1]);
      goto quit;
   }

   if ((ret = ioctl(fd,cmd,(unsigned long)&attr)) != 0)
   {
      fprintf(stderr,"ioctl: %s\n",strerror(errno));
   }

   if (ret > -1)
   {
      if (argv[1][0] == 's')
      {
	 printf("set file attributes to ");
      }
      else if (argv[1][0] == 'g')
      {
	 printf("file attributes are ");
      }
		
      hex_print((char*)&attr,1);

      printf("\n");
   }

 quit:

   close(fd);
	
   return ret;
}
Example #5
0
static void _mangoIndexStart (OracleEnv &env, MangoFetchContext &context,
                              const char *oper, const Array<char> &query_buf,
                              OCINumber *p_strt, OCINumber *p_stop,
                              int flags, const char *params)
{
    MangoShadowFetch &shadow_fetch = context.shadow_fetch.ref();
    MangoFastIndex   &fast_index   = context.fast_index.ref();

    if (strcasecmp(oper, "SUB") == 0)
    {
        if (context.substructure.parse(params))
        {
            context.substructure.loadQuery(query_buf);

            int right = bingoGetExactRightPart(env, p_strt, p_stop, flags);

            if (right == 1)
            {
                fast_index.prepareSubstructure(env);
                context.fetch_engine = &fast_index;
            }
            else // right == 0
            {
                shadow_fetch.prepareNonSubstructure(env);
                context.fetch_engine = &shadow_fetch;
            }
        }
        else if (context.tautomer.parseSub(params))
        {
            context.tautomer.loadQuery(query_buf);

            int right = bingoGetExactRightPart(env, p_strt, p_stop, flags);

            if (right == 1)
            {
                fast_index.prepareTautomerSubstructure(env);
                context.fetch_engine = &fast_index;
            }
            else // right == 0
            {
                shadow_fetch.prepareNonTautomerSubstructure(env);
                context.fetch_engine = &shadow_fetch;
            }
        }
        else
            throw BingoError("can't parse parameters: '%s'", params);
    }
    else if (strcasecmp(oper, "SMARTS") == 0)
    {
        context.substructure.loadSMARTS(query_buf);

        int right = bingoGetExactRightPart(env, p_strt, p_stop, flags);

        if (right == 1)
        {
            fast_index.prepareSubstructure(env);
            context.fetch_engine = &fast_index;
        }
        else // right == 0
        {
            shadow_fetch.prepareNonSubstructure(env);
            context.fetch_engine = &shadow_fetch;
        }
    }
    else if (strcasecmp(oper, "EXACT") == 0)
    {
        if (context.tautomer.parseExact(params))
        {
            context.tautomer.loadQuery(query_buf);

            int right = bingoGetExactRightPart(env, p_strt, p_stop, flags);

            shadow_fetch.prepareTautomer(env, right);
            context.fetch_engine = &shadow_fetch;
        }
        else if (context.exact.parse(params))
        {
            context.exact.loadQuery(query_buf);

            int right = bingoGetExactRightPart(env, p_strt, p_stop, flags);

            shadow_fetch.prepareExact(env, right);
            context.fetch_engine = &shadow_fetch;
        }
        else
            throw BingoError("can't parse parameters: '%s'", params);
    }
    else if (strcasecmp(oper, "SIM") == 0)
    {
        context.similarity.setMetrics(params);
        context.similarity.loadQuery(query_buf);

        float bottom = -0.1f;
        float top = 1.1f;

        if (p_strt == 0 && p_stop == 0)
            throw BingoError("no bounds for similarity search");

        if (p_strt != 0)
            bottom = OracleUtil::numberToFloat(env, p_strt);
        if (p_stop != 0)
            top = OracleUtil::numberToFloat(env, p_stop);

        if (flags & 64)
            throw BingoError("exact match not allowed");

        context.similarity.include_bottom = ((flags & 16) != 0);
        context.similarity.include_top = ((flags & 32) != 0);
        context.similarity.bottom = bottom;
        context.similarity.top = top;

        fast_index.prepareSimilarity(env);
        context.fetch_engine = &fast_index;
    }
    else if (strcasecmp(oper, "GROSS") == 0)
    {
        int right = bingoGetExactRightPart(env, p_strt, p_stop, flags);

        MangoGross &instance = context.gross;

        instance.parseQuery(query_buf);

        shadow_fetch.prepareGross(env, right);
        context.fetch_engine = &shadow_fetch;
    }
    else if (strcasecmp(oper, "MASS") == 0)
    {
        float bottom = 0;
        float top = 1e10;

        if (p_strt == 0 && p_stop == 0)
            throw BingoError("no bounds for molecular mass search");

        if (p_strt != 0)
            bottom = OracleUtil::numberToFloat(env, p_strt);
        if (p_stop != 0)
            top = OracleUtil::numberToFloat(env, p_stop);

        context.mass.bottom = bottom;
        context.mass.top = top;

        shadow_fetch.prepareMass(env);
        context.fetch_engine = &shadow_fetch;
    }
    else
        throw BingoError("unknown operator: %s", oper);
}
Example #6
0
static void* accept_request(void *arg)		//static
{
	int sock = (int)arg;
	char buf[SIZE];
	int len = sizeof(buf)/sizeof(*buf);
	char method[SIZE/10];
	char url[SIZE];
	char path[SIZE];
	int ret = -1;
	int i = 0;
	int j = 0;

	char *query_string = NULL;    //aim at val(can shu)
	int cgi = 0;
#ifdef _DEBUG_
//	do
//	{
//		ret = get_line(sock, buf, len);
//		printf("%s", buf);
//		fflush(stdout);
//	}while(ret > 0 && (strcmp(buf, "\n") != 0) );
#endif

	memset(buf, '\0', sizeof(buf));
	memset(method, '\0', sizeof(method));
	memset(url, '\0', sizeof(url));
	memset(path, '\0', sizeof(buf));

	//Request Line
	ret = get_line(sock, buf, len);
	if(ret <= 0)
	{
		echo_errno(sock);
		return (void*)1;
	}
	i = 0;	//method index
	j = 0;	//buf index
	while((i < (sizeof(method)/sizeof(*method) - 1)) && (j < sizeof(buf)/sizeof(*buf) - 1) && (!isspace(buf[j]) ) )
	{
		method[i] = buf[j];
		++i;
		++j;
	}
	method[i] = '\0';
	if((strcasecmp(method, "GET") != 0) && (strcasecmp(method, "POST")) )
	{
		//echo_errno(sock);
		return (void*)2;
	}

	//URL
	while(isspace(buf[j]))	//Remove Space
	{
		++j;
	}
	i = 0;
	while( ( i < sizeof(url)/sizeof(*url)-1 ) && (j < sizeof(buf)/sizeof(*buf)) && (!isspace(buf[j])) )
	{
		url[i] = buf[j];
		++i;
		++j;
	}
	url[i] = '\0';

	if( strcasecmp(method, "POST") == 0 )
	{
		cgi = 1;
		sprintf(path, "%s", url+1);
	}

	if( strcasecmp(method, "GET") == 0 )
	{
		query_string = url;
		while( *query_string != '\0' && *query_string != '?' )
		{
			query_string++;
		}
		if(*query_string == '?')
		{
			cgi = 1;
			*query_string = '\0';
			++query_string;
		}
	}

	if( strcasecmp(method, "GET") == 0 )
	{
		sprintf(path, "htdoc%s", url);
		if( path[strlen(path)-1] == '/' )
		{
			strcat(path, "index.html");
		}
	}


	struct stat st;
	if( stat(path, &st) < 0 )
	{
		//echo_errno();	//404	
		return (void*)3;
	}
	else	//case : DIR
	{
		if( S_ISDIR(st.st_mode) )
		{
			strcat(path, "index.html");
		}
		else if( (st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH) )      //bin(binary file)
		{
			cgi = 1;
		}
		else
		{}   //noting to do
	}
	
	printf("[email protected]!#%@^   %s   [email protected]%@^%\n", buf);
	if(cgi) // u+x file
	{
		printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!cgi\n");
		exe_cgi(sock, method, path, query_string);  //cgi mode
	}
	else  //.jpg   .html ...
	{
		printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!www\n");
		clear_header(sock);  //! important!
		echo_www(sock, path, st.st_size);
	}

	close(sock);
	return 0;

	
}
Example #7
0
static krb5_error_code
get_new_tickets(krb5_context context,
		krb5_principal principal,
		krb5_ccache ccache,
		krb5_deltat ticket_life,
		int interactive)
{
    krb5_error_code ret;
    krb5_get_init_creds_opt *opt;
    krb5_creds cred;
    char passwd[256];
    krb5_deltat start_time = 0;
    krb5_deltat renew = 0;
    const char *renewstr = NULL;
    krb5_enctype *enctype = NULL;
    krb5_ccache tempccache;
    krb5_init_creds_context icc;
    krb5_keytab kt = NULL;
    int need_prompt;
    int will_use_keytab =  (use_keytab || keytab_str);

    passwd[0] = '\0';

    if (password_file) {
	FILE *f;

	if (strcasecmp("STDIN", password_file) == 0)
	    f = stdin;
	else
	    f = fopen(password_file, "r");
	if (f == NULL)
	    krb5_errx(context, 1, "Failed to open the password file %s",
		      password_file);

	if (fgets(passwd, sizeof(passwd), f) == NULL)
	    krb5_errx(context, 1,
		      N_("Failed to read password from file %s", ""),
		      password_file);
	if (f != stdin)
	    fclose(f);
	passwd[strcspn(passwd, "\n")] = '\0';
    }

#if defined(__APPLE__) && !defined(__APPLE_TARGET_EMBEDDED__)
    if (passwd[0] == '\0' && !will_use_keytab && home_directory_flag) {
	const char *realm;
	OSStatus osret;
	UInt32 length;
	void *buffer;
	char *name;

	realm = krb5_principal_get_realm(context, principal);

	ret = krb5_unparse_name_flags(context, principal,
				      KRB5_PRINCIPAL_UNPARSE_NO_REALM, &name);
	if (ret)
	    goto nopassword;

	osret = SecKeychainFindGenericPassword(NULL, (UInt32)strlen(realm), realm,
					       (UInt32)strlen(name), name,
					       &length, &buffer, &passwordItem);
	free(name);
	if (osret != noErr)
	    goto nopassword;

	if (length < sizeof(passwd) - 1) {
	    memcpy(passwd, buffer, length);
	    passwd[length] = '\0';
	}
	SecKeychainItemFreeContent(NULL, buffer);
    nopassword:
	do { } while(0);
    }
#endif

    memset(&cred, 0, sizeof(cred));

    ret = krb5_get_init_creds_opt_alloc (context, &opt);
    if (ret)
	krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc");

    krb5_get_init_creds_opt_set_default_flags(context, "kinit",
	krb5_principal_get_realm(context, principal), opt);

    if(forwardable_flag != -1)
	krb5_get_init_creds_opt_set_forwardable (opt, forwardable_flag);

    if(proxiable_flag != -1)
	krb5_get_init_creds_opt_set_proxiable (opt, proxiable_flag);
    if(anonymous_flag)
	krb5_get_init_creds_opt_set_anonymous (opt, anonymous_flag);
    if (pac_flag != -1)
	krb5_get_init_creds_opt_set_pac_request(context, opt,
						pac_flag ? TRUE : FALSE);
    if (canonicalize_flag)
	krb5_get_init_creds_opt_set_canonicalize(context, opt, TRUE);
    if (pk_enterprise_flag || enterprise_flag || canonicalize_flag || windows_flag)
	krb5_get_init_creds_opt_set_win2k(context, opt, TRUE);
    if (pk_user_id || ent_user_id || anonymous_flag) {
	ret = krb5_get_init_creds_opt_set_pkinit(context, opt,
						 principal,
						 pk_user_id,
						 pk_x509_anchors,
						 NULL,
						 NULL,
						 pk_use_enckey ? 2 : 0 |
						 anonymous_flag ? 4 : 0,
						 krb5_prompter_posix,
						 NULL,
						 passwd);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_get_init_creds_opt_set_pkinit");
	if (ent_user_id)
	    krb5_get_init_creds_opt_set_pkinit_user_cert(context, opt, ent_user_id);
    }

    if (addrs_flag != -1)
	krb5_get_init_creds_opt_set_addressless(context, opt,
						addrs_flag ? FALSE : TRUE);

    if (renew_life == NULL && renewable_flag)
	renewstr = "1 month";
    if (renew_life)
	renewstr = renew_life;
    if (renewstr) {
	renew = parse_time (renewstr, "s");
	if (renew < 0)
	    errx (1, "unparsable time: %s", renewstr);

	krb5_get_init_creds_opt_set_renew_life (opt, renew);
    }

    if(ticket_life != 0)
	krb5_get_init_creds_opt_set_tkt_life (opt, ticket_life);

    if(start_str) {
	int tmp = parse_time (start_str, "s");
	if (tmp < 0)
	    errx (1, N_("unparsable time: %s", ""), start_str);

	start_time = tmp;
    }

    if(etype_str.num_strings) {
	int i;

	enctype = malloc(etype_str.num_strings * sizeof(*enctype));
	if(enctype == NULL)
	    errx(1, "out of memory");
	for(i = 0; i < etype_str.num_strings; i++) {
	    ret = krb5_string_to_enctype(context,
					 etype_str.strings[i],
					 &enctype[i]);
	    if(ret)
		krb5_err(context, 1, ret, "unrecognized enctype: %s",
			 etype_str.strings[i]);
	}
	krb5_get_init_creds_opt_set_etype_list(opt, enctype,
					       etype_str.num_strings);
    }

    ret = krb5_init_creds_init(context, principal,
			       krb5_prompter_posix, NULL,
			       start_time, opt, &icc);
    if (ret)
	krb5_err (context, 1, ret, "krb5_init_creds_init");

    if (server_str) {
	ret = krb5_init_creds_set_service(context, icc, server_str);
	if (ret)
	    krb5_err (context, 1, ret, "krb5_init_creds_set_service");
    }

    if (kdc_hostname)
	krb5_init_creds_set_kdc_hostname(context, icc, kdc_hostname);

    if (fast_armor_cache_string) {
	krb5_ccache fastid;
	
	ret = krb5_cc_resolve(context, fast_armor_cache_string, &fastid);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_cc_resolve(FAST cache)");
	
	ret = krb5_init_creds_set_fast_ccache(context, icc, fastid);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_init_creds_set_fast_ccache");
    }

    if(will_use_keytab) {
	if(keytab_str)
	    ret = krb5_kt_resolve(context, keytab_str, &kt);
	else
	    ret = krb5_kt_default(context, &kt);
	if (ret)
	    krb5_err (context, 1, ret, "resolving keytab");

	ret = krb5_init_creds_set_keytab(context, icc, kt);
	if (ret)
	    krb5_err (context, 1, ret, "krb5_init_creds_set_keytab");
    }

    need_prompt = !(pk_user_id || ent_user_id || anonymous_flag || use_keytab || keytab_str);

    if (interactive && passwd[0] == '\0' && need_prompt) {
	char *p, *prompt;

	krb5_unparse_name(context, principal, &p);
	asprintf (&prompt, N_("%s's Password: ", ""), p);
	free(p);

	if (UI_UTIL_read_pw_string(passwd, sizeof(passwd)-1, prompt, 0)){
	    memset(passwd, 0, sizeof(passwd));
	    errx(1, "failed to read password");
	}
	free (prompt);
    }

    if (passwd[0]) {
	ret = krb5_init_creds_set_password(context, icc, passwd);
	if (ret)
	    krb5_err(context, 1, ret, "krb5_init_creds_set_password");
    }

    ret = krb5_init_creds_get(context, icc);

#ifdef __APPLE__
    /*
     * Save password in Keychain
     */
    if (ret == 0 && keychain_flag && passwordItem == NULL) {
	krb5_error_code ret2;
	const char *realm;
	char *name;

	realm = krb5_principal_get_realm(context, principal);
	ret2 = krb5_unparse_name_flags(context, principal, KRB5_PRINCIPAL_UNPARSE_NO_REALM, &name);
	if (ret2 == 0) {
	    (void)SecKeychainAddGenericPassword(NULL,
						(UInt32)strlen(realm), realm,
						(UInt32)strlen(name), name,
						(UInt32)strlen(passwd), passwd,
						NULL);
	    free(name);
	}
    }
#endif

    memset(passwd, 0, sizeof(passwd));

    switch(ret){
    case 0:
	break;
    case KRB5_LIBOS_PWDINTR: /* don't print anything if it was just C-c:ed */
	exit(1);
    case KRB5KRB_AP_ERR_BAD_INTEGRITY:
    case KRB5KRB_AP_ERR_MODIFIED:
    case KRB5KDC_ERR_PREAUTH_FAILED:
    case KRB5_GET_IN_TKT_LOOP:
#ifdef __APPLE__
	if (passwordItem)
	    SecKeychainItemDelete(passwordItem);
#endif
	krb5_errx(context, 1, N_("Password incorrect", ""));
	break;
    case KRB5KRB_AP_ERR_V4_REPLY:
	krb5_errx(context, 1, N_("Looks like a Kerberos 4 reply", ""));
	break;
    case KRB5KDC_ERR_KEY_EXPIRED:
	krb5_errx(context, 1, N_("Password expired", ""));
	break;
    default:
	krb5_err(context, 1, ret, "krb5_get_init_creds");
    }

    ret = krb5_init_creds_get_creds(context, icc, &cred);
    if (ret)
	krb5_err(context, 1, ret, "krb5_init_creds_get_creds");

    krb5_process_last_request(context, opt, icc);

    ret = krb5_cc_new_unique(context, krb5_cc_get_type(context, ccache),
			     NULL, &tempccache);
    if (ret)
	krb5_err (context, 1, ret, "krb5_cc_new_unique");

    ret = krb5_init_creds_store(context, icc, tempccache);
    if (ret)
	krb5_err(context, 1, ret, "krb5_init_creds_store");

    ret = krb5_init_creds_store_config(context, icc, tempccache);
    if (ret)
	krb5_warn(context, ret, "krb5_init_creds_store_config");

    ret = krb5_init_creds_warn_user(context, icc);
    if (ret)
	krb5_warn(context, ret, "krb5_init_creds_warn_user");

    ret = krb5_cc_move(context, tempccache, ccache);
    if (ret) {
	(void)krb5_cc_destroy(context, tempccache);
	krb5_err (context, 1, ret, "krb5_cc_move");
    }

    if (switch_cache_flags)
	krb5_cc_switch(context, ccache);

    if (ok_as_delegate_flag || windows_flag || use_referrals_flag) {
	unsigned char d = 0;
	krb5_data data;

	if (ok_as_delegate_flag || windows_flag)
	    d |= 1;
	if (use_referrals_flag || windows_flag)
	    d |= 2;

	data.length = 1;
	data.data = &d;

	krb5_cc_set_config(context, ccache, NULL, "realm-config", &data);
    }

    if (enctype)
	free(enctype);

    krb5_init_creds_free(context, icc);
    krb5_get_init_creds_opt_free(context, opt);

    if (kt)
	krb5_kt_close(context, kt);

#ifdef __APPLE__
    if (passwordItem)
	CFRelease(passwordItem);
#endif

    return 0;
}
Example #8
0
int
main(int argc, char **argv)
{
	register int cnt, op, i;
	bpf_u_int32 localnet, netmask;
	register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
	pcap_handler printer;
	struct bpf_program fcode;
	RETSIGTYPE (*oldhandler)(int);
	u_char *pcap_userdata;
	char ebuf[PCAP_ERRBUF_SIZE];

	cnt = -1;
	device = NULL;
	infile = NULL;
	RFileName = NULL;
	WFileName = NULL;
	if ((cp = strrchr(argv[0], '/')) != NULL)
		program_name = cp + 1;
	else
		program_name = argv[0];

	if (abort_on_misalignment(ebuf) < 0)
		error("%s", ebuf);

	opterr = 0;
	while (
	    (op = getopt(argc, argv, "ac:defF:i:lnNOpqr:s:StT:vw:xY")) != EOF)
		switch (op) {

		case 'a':
			++aflag;
			break;

		case 'c':
			cnt = atoi(optarg);
			if (cnt <= 0)
				error("invalid packet count %s", optarg);
			break;

		case 'd':
			++dflag;
			break;

		case 'e':
			++eflag;
			break;

		case 'f':
			++fflag;
			break;

		case 'F':
			infile = optarg;
			break;

		case 'i':
			device = optarg;
			break;

		case 'l':
#ifdef HAVE_SETLINEBUF
			setlinebuf(stdout);
#else
			setvbuf(stdout, NULL, _IOLBF, 0);
#endif
			break;

		case 'n':
			++nflag;
			break;

		case 'N':
			++Nflag;
			break;

		case 'O':
			Oflag = 0;
			break;

		case 'p':
			++pflag;
			break;

		case 'q':
			++qflag;
			break;

		case 'r':
			RFileName = optarg;
			break;

		case 's':
			snaplen = atoi(optarg);
			if (snaplen <= 0)
				error("invalid snaplen %s", optarg);
			break;

		case 'S':
			++Sflag;
			break;

		case 't':
			--tflag;
			break;

		case 'T':
			if (strcasecmp(optarg, "vat") == 0)
				packettype = PT_VAT;
			else if (strcasecmp(optarg, "wb") == 0)
				packettype = PT_WB;
			else if (strcasecmp(optarg, "rpc") == 0)
				packettype = PT_RPC;
			else if (strcasecmp(optarg, "rtp") == 0)
				packettype = PT_RTP;
			else if (strcasecmp(optarg, "rtcp") == 0)
				packettype = PT_RTCP;
			else
				error("unknown packet type `%s'", optarg);
			break;

		case 'v':
			++vflag;
			break;

		case 'w':
			WFileName = optarg;
			break;
#ifdef YYDEBUG
		case 'Y':
			{
			/* Undocumented flag */
			extern int yydebug;
			yydebug = 1;
			}
			break;
#endif
		case 'x':
			++xflag;
			break;

		default:
			usage();
			/* NOTREACHED */
		}

	if (aflag && nflag)
		error("-a and -n options are incompatible");

	if (tflag > 0)
		thiszone = gmt2local(0);

	if (RFileName != NULL) {
		/*
		 * We don't need network access, so set it back to the user id.
		 * Also, this prevents the user from reading anyone's
		 * trace file.
		 */
		setuid(getuid());

		pd = pcap_open_offline(RFileName, ebuf);
		if (pd == NULL)
			error("%s", ebuf);
		localnet = 0;
		netmask = 0;
		if (fflag != 0)
			error("-f and -r options are incompatible");
	} else {
		if (device == NULL) {
			device = pcap_lookupdev(ebuf);
			if (device == NULL)
				error("%s", ebuf);
		}
		pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
		if (pd == NULL)
			error("%s", ebuf);
		i = pcap_snapshot(pd);
		if (snaplen < i) {
			warning("snaplen raised from %d to %d", snaplen, i);
			snaplen = i;
		}
		if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
			localnet = 0;
			netmask = 0;
			warning("%s", ebuf);
		}
		/*
		 * Let user own process after socket has been opened.
		 */
		setuid(getuid());
	}
	if (infile)
		cmdbuf = read_infile(infile);
	else
		cmdbuf = copy_argv(&argv[optind]);

	if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
		error("%s", pcap_geterr(pd));
	if (dflag) {
		bpf_dump(&fcode, dflag);
		exit(0);
	}
	init_addrtoname(localnet, netmask);

	(void)setsignal(SIGTERM, cleanup);
	(void)setsignal(SIGINT, cleanup);
	/* Cooperate with nohup(1) */
	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
		(void)setsignal(SIGHUP, oldhandler);

	if (pcap_setfilter(pd, &fcode) < 0)
		error("%s", pcap_geterr(pd));
	if (WFileName) {
		pcap_dumper_t *p = pcap_dump_open(pd, WFileName);
		if (p == NULL)
			error("%s", pcap_geterr(pd));
		printer = pcap_dump;
		pcap_userdata = (u_char *)p;
	} else {
		printer = lookup_printer(pcap_datalink(pd));
		pcap_userdata = 0;
	}
	if (RFileName == NULL) {
		(void)fprintf(stderr, "%s: listening on %s\n",
		    program_name, device);
		(void)fflush(stderr);
	}
	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
		    program_name, pcap_geterr(pd));
		exit(1);
	}
	pcap_close(pd);
	exit(0);
}
Example #9
0
static void parse_channels(tvi_handle_t *tvh)
{
    char** channels = tvh->tv_param->channels;

    mp_tmsg(MSGT_TV, MSGL_INFO, "TV channel names detected.\n");
    tv_channel_list = malloc(sizeof(tv_channels_t));
    tv_channel_list->index=1;
    tv_channel_list->next=NULL;
    tv_channel_list->prev=NULL;
    tv_channel_current = tv_channel_list;
    tv_channel_current->norm = tvh->norm;

    while (*channels) {
        char* tmp = *(channels++);
        char* sep = strchr(tmp,'-');
        int i;
        struct CHANLIST cl;

        if (!sep) continue; // Wrong syntax, but mplayer should not crash

        av_strlcpy(tv_channel_current->name, sep + 1,
                        sizeof(tv_channel_current->name));
        sep[0] = '\0';
        strncpy(tv_channel_current->number, tmp, 5);
        tv_channel_current->number[4]='\0';

        while ((sep=strchr(tv_channel_current->name, '_')))
            sep[0] = ' ';

        // if channel number is a number and larger than 1000 threat it as frequency
        // tmp still contain pointer to null-terminated string with channel number here
        if (atoi(tmp)>1000){
            tv_channel_current->freq=atoi(tmp);
        }else{
            tv_channel_current->freq = 0;
            for (i = 0; i < chanlists[tvh->chanlist].count; i++) {
                cl = tvh->chanlist_s[i];
                if (!strcasecmp(cl.name, tv_channel_current->number)) {
                    tv_channel_current->freq=cl.freq;
                    break;
                }
            }
        }
        if (tv_channel_current->freq == 0)
            mp_tmsg(MSGT_TV, MSGL_ERR, "Couldn't find frequency for channel %s (%s)\n",
                            tv_channel_current->number, tv_channel_current->name);
        else {
          sep = strchr(tv_channel_current->name, '-');
          if ( !sep ) sep = strchr(tv_channel_current->name, '+');

          if ( sep ) {
            i = atoi (sep+1);
            if ( sep[0] == '+' ) tv_channel_current->freq += i * 100;
            if ( sep[0] == '-' ) tv_channel_current->freq -= i * 100;
            sep[0] = '\0';
          }

          sep = strchr(tv_channel_current->name, '=');
          if ( sep ) {
            tv_channel_current->norm = norm_from_string(tvh, sep+1);
            sep[0] = '\0';
          }
        }

        /*mp_msg(MSGT_TV, MSGL_INFO, "-- Detected channel %s - %s (%5.3f)\n",
                        tv_channel_current->number, tv_channel_current->name,
                        (float)tv_channel_current->freq/1000);*/

        tv_channel_current->next = malloc(sizeof(tv_channels_t));
        tv_channel_current->next->index = tv_channel_current->index + 1;
        tv_channel_current->next->prev = tv_channel_current;
        tv_channel_current->next->next = NULL;
        tv_channel_current = tv_channel_current->next;
        tv_channel_current->norm = tvh->norm;
    }
    if (tv_channel_current->prev)
        tv_channel_current->prev->next = NULL;
    free(tv_channel_current);
}
Example #10
0
int Authenticate(HTTPSession *Session)
{
int result=0;
char *Token=NULL, *ptr;
int PAMAccount=FALSE;
//struct group *grent;

AuthenticationsTried=CopyStr(AuthenticationsTried,"");

if (! CheckServerAllowDenyLists(Session->UserName)) 
{
	LogToFile(Settings.LogPath,"AUTH: Authentication failed for UserName '%s'. User not allowed to log in",Session->UserName);
	return(FALSE);
}


//check for this as it changes behavior of other auth types
ptr=GetToken(Settings.AuthMethods,",",&Token,0);
while (ptr)
{
  if (strcasecmp(Token,"pam-account")==0) PAMAccount=TRUE;
  ptr=GetToken(ptr,",",&Token,0);
}

ptr=GetToken(Settings.AuthMethods,",",&Token,0);

while (ptr)
{
	if (Settings.Flags & FLAG_LOG_VERBOSE) LogToFile(Settings.LogPath,"AUTH: Try to authenticate '%s' via '%s'. Remaining authentication types: %s",Session->UserName, Token, ptr);

	if (strcasecmp(Token,"open")==0) result=TRUE;
	else if (strcasecmp(Token,"native")==0) result=AuthNativeFile(Session,FALSE, &Session->RealUser, &Session->HomeDir, &Session->UserSettings);
	else if (strcasecmp(Token,"digest")==0) result=AuthNativeFile(Session,TRUE, &Session->RealUser, &Session->HomeDir, &Session->UserSettings);
	else if (strcasecmp(Token,"passwd")==0) result=AuthPasswdFile(Session, &Session->RealUser, &Session->HomeDir);
	else if (strcasecmp(Token,"shadow")==0) result=AuthShadowFile(Session);
	else if (strcasecmp(Token,"cert")==0) result=CheckSSLAuthentication(Session, Session->UserName);
	else if (strcasecmp(Token,"certificate")==0) result=CheckSSLAuthentication(Session, Session->UserName);
	else if (strcasecmp(Token,"accesstoken")==0) result=AuthAccessToken(Session, Session->Password);
	else if (strcasecmp(Token,"cookie")==0) result=AccessTokenAuthCookie(Session);

	#ifdef HAVE_LIBPAM
	else if (strcasecmp(Token,"pam")==0) 
	{
		result=AuthPAM(Session);
		if (result==TRUE) PAMAccount=TRUE;
	}
	#endif
	else if (strcasecmp(Token,"none")==0) 
	{
		result=FALSE;
		break;
	}
	else if (strcasecmp(Token,"deny")==0) 
	{
		result=FALSE;
		break;
	}

	if (result==TRUE)
  {
    LogToFile(Settings.LogPath,"AUTH: Client Authenticated with %s for %[email protected]%s", Token, Session->UserName,Session->ClientIP);
		break;
  }

	AuthenticationsTried=MCatStr(AuthenticationsTried,Token," ",NULL);

	ptr=GetToken(ptr,",",&Token,0);
}


switch (result)
{
case TRUE:
AuthenticateLookupUserDetails(Session);

if (Session->RealUserUID==0)
{
	LogToFile(Settings.LogPath,"AUTH: No 'RealUser' for '%s'. Login Denied",Session->UserName);
	result=FALSE;
}
if (! StrLen(Session->HomeDir)) 
{
	LogToFile(Settings.LogPath,"AUTH: No 'HomeDir' set for '%s'. Login Denied",Session->UserName);
	result=FALSE;
}

//Use PAMCheckAccount to check if account is allowed to login even if authenticated
if (result && PAMAccount)
{
#ifdef HAVE_LIBPAM
  if (! AuthPAMCheckAccount(Session))
  {
    LogToFile(Settings.LogPath,"PAM Account invalid for '%s'. Login Denied",Session->UserName);
    result=FALSE;
  }
#endif
}
break;


case USER_UNKNOWN: 
	LogToFile(Settings.LogPath,"AUTH: Authentication failed for UserName '%s'. User Unknown. Tried methods: %s ",Session->UserName,AuthenticationsTried); 
break;

case FALSE: 
	LogToFile(Settings.LogPath,"AUTH: Authentication failed for UserName '%s'. Bad Password/Credentials. Tried methods: %s ",Session->UserName,AuthenticationsTried);
break;
}


DestroyString(Token);
return(result);
}
Example #11
0
int http_response_write_header(server *srv, connection *con) {
	buffer *b;
	size_t i;
	int have_date = 0;
	int have_server = 0;

	b = buffer_init();

	if (con->request.http_version == HTTP_VERSION_1_1) {
		buffer_copy_string_len(b, CONST_STR_LEN("HTTP/1.1 "));
	} else {
		buffer_copy_string_len(b, CONST_STR_LEN("HTTP/1.0 "));
	}
	buffer_append_int(b, con->http_status);
	buffer_append_string_len(b, CONST_STR_LEN(" "));
	buffer_append_string(b, get_http_status_name(con->http_status));

	/* disable keep-alive if requested */
	if (con->request_count > con->conf.max_keep_alive_requests || 0 == con->conf.max_keep_alive_idle) {
		con->keep_alive = 0;
	} else {
		con->keep_alive_idle = con->conf.max_keep_alive_idle;
	}

	if (con->request.http_version != HTTP_VERSION_1_1 || con->keep_alive == 0) {
		if (con->keep_alive) {
			response_header_overwrite(srv, con, CONST_STR_LEN("Connection"), CONST_STR_LEN("keep-alive"));
		} else {
			response_header_overwrite(srv, con, CONST_STR_LEN("Connection"), CONST_STR_LEN("close"));
		}
	}

	if (con->response.transfer_encoding & HTTP_TRANSFER_ENCODING_CHUNKED) {
		response_header_overwrite(srv, con, CONST_STR_LEN("Transfer-Encoding"), CONST_STR_LEN("chunked"));
	}


	/* add all headers */
	for (i = 0; i < con->response.headers->used; i++) {
		data_string *ds;

		ds = (data_string *)con->response.headers->data[i];

		if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key) &&
		    0 != strncasecmp(ds->key->ptr, CONST_STR_LEN("X-LIGHTTPD-")) &&
			0 != strncasecmp(ds->key->ptr, CONST_STR_LEN("X-Sendfile"))) {
			if (0 == strcasecmp(ds->key->ptr, "Date")) have_date = 1;
			if (0 == strcasecmp(ds->key->ptr, "Server")) have_server = 1;
			if (0 == strcasecmp(ds->key->ptr, "Content-Encoding") && 304 == con->http_status) continue;

			buffer_append_string_len(b, CONST_STR_LEN("\r\n"));
			buffer_append_string_buffer(b, ds->key);
			buffer_append_string_len(b, CONST_STR_LEN(": "));
#if 0
			/** 
			 * the value might contain newlines, encode them with at least one white-space
			 */
			buffer_append_string_encoded(b, CONST_BUF_LEN(ds->value), ENCODING_HTTP_HEADER);
#else
			buffer_append_string_buffer(b, ds->value);
#endif
		}
	}

	if (!have_date) {
		/* HTTP/1.1 requires a Date: header */
		buffer_append_string_len(b, CONST_STR_LEN("\r\nDate: "));

		/* cache the generated timestamp */
		if (srv->cur_ts != srv->last_generated_date_ts) {
			buffer_string_prepare_copy(srv->ts_date_str, 255);

			buffer_append_strftime(srv->ts_date_str, "%a, %d %b %Y %H:%M:%S GMT", gmtime(&(srv->cur_ts)));

			srv->last_generated_date_ts = srv->cur_ts;
		}

		buffer_append_string_buffer(b, srv->ts_date_str);
	}

	if (!have_server) {
		if (buffer_is_empty(con->conf.server_tag)) {
			buffer_append_string_len(b, CONST_STR_LEN("\r\nServer: " PACKAGE_DESC));
		} else if (!buffer_string_is_empty(con->conf.server_tag)) {
			buffer_append_string_len(b, CONST_STR_LEN("\r\nServer: "));
			buffer_append_string_encoded(b, CONST_BUF_LEN(con->conf.server_tag), ENCODING_HTTP_HEADER);
		}
	}

	buffer_append_string_len(b, CONST_STR_LEN("\r\n\r\n"));

	con->bytes_header = buffer_string_length(b);

	if (con->conf.log_response_header) {
		log_error_write(srv, __FILE__, __LINE__, "sSb", "Response-Header:", "\n", b);
	}

	chunkqueue_prepend_buffer(con->write_queue, b);
	buffer_free(b);

	return 0;
}
Example #12
0
int ParseReg( int i2cDev, const char *regStr, RegMap_t *regFound )
{
    char               *endPtr;
    int                 i;
    uint8_t             reg;
    BootLoaderInfo_t    bootInfo;
    RegMap_t           *regList = NULL;
    int                 numRegs = 0;

    static  char    regNumStr[ 10 ];

    // Fetch the AVR BootLoader info, so that we can detemine which type of
    // AVR we have.

    if ( !BootLoaderGetInfo( i2cDev, &bootInfo ))
    {
        LogError( "Unable to retrieve BootLoader information from i2c address 0x%02x\n", gI2cAddr );
        return FALSE;
    }

    for ( i = 0; i < ARRAY_LEN( gRegs ); i++ ) 
    {
        if ( bootInfo.partNumber == gRegs[ i ].signature )
        {
            regList = gRegs[ i ].regMap;
            numRegs = gRegs[ i ].numRegs;
        }
    }
    if ( regList == NULL )
    {
        LogError( "Unrecognized signature: 0x%04x\n", bootInfo.partNumber );
        return FALSE;
    }

    // Check to see if it's a register that we know about

    for ( i = 0; i < numRegs; i++ ) 
    {
        if ( strcasecmp( regStr, regList[ i ].regStr ) == 0 )
        {
            *regFound = regList[ i ];
            return TRUE;
        }
    }

    // Not someting we recognize, see if a number was entered.

    reg = (uint8_t)strtol( regStr, &endPtr, 0 );

    if ( *endPtr != '\0' )
    {
        LogError( "Unrecognized register, found '%s'\n", regStr );
        return FALSE;
    }

    snprintf( regNumStr, sizeof( regNumStr ), "0x%02x", reg );

    regFound->reg = reg;
    regFound->regStr = regNumStr;
    regFound->is16Bit = 0;

    return TRUE;


} // ParseReg
Example #13
0
int main( int argc, char **argv )
{
    char                shortOptsStr[ sizeof( gOption ) / sizeof( gOption[ 0 ] ) + 1 ];
    char               *shortOpts = shortOptsStr;
    struct option       *scanOpt;
    int                 opt;
    const char         *i2cDevName = "/dev/i2c-0";
    int                 i2cDev;
    int                 cmdIdx;

    LogInit( stdout );

    // Figure out the short options from our options structure

    for ( scanOpt = gOption; scanOpt->name != NULL; scanOpt++ ) 
    {
        if (( scanOpt->flag == NULL ) && ( scanOpt->val < OPT_FIRST_LONG_OPT ))
        {
            *shortOpts++ = (char)scanOpt->val;

            if ( scanOpt->has_arg != no_argument )
            {
                *shortOpts++ = ':';
            }
        }
    }
    *shortOpts++ = '\0';

    // Parse the command line options

    while (( opt = getopt_long( argc, argv, shortOptsStr, gOption, NULL )) != -1 )
    {
        switch ( opt )
        {
            case 0: 
            {
                // getopt_long returns 0 for entries where flag is non-NULL

                break;
            }

            case OPT_BASE_DECIMAL:
            case OPT_BASE_HEX:
            {
                gBase = opt;
                break;
            }

            case OPT_VERSION:
            {   
                printf( "i2c-io: SVN Revision: %d\n", SVN_REVISION );
                exit( 0 );
            }

            case '?':
            case OPT_HELP:
            default:
            {
                LogError( "opt:%d\n", opt );
                Usage();
                exit( 1 );
            }
        }
    }
    argc -= optind;
    argv += optind;

    // Verify that an i2c-address was specified

    if ( argc < 1 )
    {
        LogError( "Must specify an i2c address\n\n" );
        Usage();
        exit( 1 );
    }
    gI2cAddr = strtol( argv[ 0 ], NULL, 0 );
    if (( gI2cAddr <= 0 ) || ( gI2cAddr > 127 ))
    {
        LogError( "Expecting i2c address in the range of 1-127, Found: %d\n", gI2cAddr );
        Usage();
        exit( 1 );
    }

    // Verify that a command has been specified

    if ( argc < 2 )
    {
        LogError( "Must specify a command\n" );
        Usage();
        exit( 1 );
    }
    gCmdStr = argv[ 1 ];
    for ( cmdIdx = 0; cmdIdx < gNumCmds; cmdIdx++ ) 
    {
        if ( strcasecmp( gCmdStr, gCmdMap[ cmdIdx ].cmdStr ) == 0 )
        {
            gCmd = gCmdMap[ cmdIdx ].cmd;
            break;
        }
    }
    if ( gCmd == CMD_DEFAULT )
    {
        LogError( "Unrecognized command '%s'\n", gCmdStr );
        exit( 1 );
    }

    // Process command specific arguments

    if ( gCmd == CMD_INFO )
    {
        if ( argc != 2 )
        {
            LogError( "Unexpected extra parameters\n" );
            Usage();
            exit( 1 );
        }
    }
    else
    if (( gCmd == CMD_GET )
    ||  ( gCmd == CMD_GET_DIR ))
    {
        if ( argc < 3 )
        {
            LogError( "Expecting port.pin\n" );
            Usage();
            exit( 1 );
        }

        gPortPinStr = argv[ 2 ];
    }
    else
    if (( gCmd == CMD_SET )
    ||  ( gCmd == CMD_SET_DIR ))
    {
        if ( argc < 4 )
        {
            LogError( "port.pin followed by value\n" );
            Usage();
            exit( 1 );
        }
        gPortPinStr = argv[ 2 ];
        gValStr     = argv[ 3 ];
    }
    else
    if ( gCmd == CMD_READ_REG  )
    {
        if ( argc < 3 )
        {
            LogError( "Expecting register index\n" );
            Usage();
            exit( 1 );
        }
        gRegStr = argv[ 2 ];
    }
    else
    if ( gCmd == CMD_WRITE_REG  )
    {
        if ( argc < 4 )
        {
            LogError( "Expecting register index and value\n" );
            Usage();
            exit( 1 );
        }
        gRegStr = argv[ 2 ];
        gValStr = argv[ 3 ];
    }

    if ( gDebug )
    {
        Log( "i2cAddr:0x%02x Cmd: %s (%d)", gI2cAddr, gCmdStr, gCmd );
        if ( gPortPinStr != NULL )
        {
            Log( " Pin: %s", gPortPinStr );
        }
        if ( gValStr != NULL )
        {
            Log( " Val: %s", gValStr );
        }
        Log( "\n" );
    }

    // Try to open the i2c device

    if (( i2cDev = open( i2cDevName, O_RDWR )) < 0 )
    {
        LogError( "Error  opening '%s': %s\n", i2cDevName, strerror( errno ));
        exit( 1 );
    }

    // Indicate which slave we wish to speak to

    I2cSetSlaveAddress( i2cDev, gI2cAddr, I2C_USE_CRC );

    switch ( gCmd )
    {
        case CMD_INFO:
        {
            ProcessInfoCommand( i2cDev );
            break;
        }

        case CMD_GET:
        {
            ProcessGetCommand( i2cDev, gPortPinStr );
            break;
        }

        case CMD_SET:
        {
            ProcessSetCommand( i2cDev, gPortPinStr, gValStr );
            break;
        }

        case CMD_GET_DIR:
        {
            ProcessGetDirCommand( i2cDev, gPortPinStr );
            break;
        }

        case CMD_SET_DIR:
        {
            ProcessSetDirCommand( i2cDev, gPortPinStr, gValStr );
            break;
        }

        case CMD_READ_REG:
        {
            ProcessReadRegCommand( i2cDev, gRegStr );
            break;
        }

        case CMD_WRITE_REG:
        {
            ProcessWriteRegCommand( i2cDev, gRegStr, gValStr );
            break;
        }
    }

    close( i2cDev );

    return 0;

} // main
Example #14
0
int ProCurveAuthentication::processDeviceConfig(Device *device, ConfigLine *command, char *line, int lineSize)
{
	// Variables...
	authConfig *authPointer = 0;
	tacacsServerConfig *tacacsPointer = 0;
	radiusServerConfig *radiusPointer = 0;
	int tempInt = 0;
	int errorCode = 0;

	// tacacs...
	if (strcasecmp(command->part(0), "tacacs-server") == 0)
	{

		// key...
		if (strcasecmp(command->part(1), "key") == 0)
		{
			if (device->config->reportFormat == Config::Debug)
				printf("%sTACACS+ Key Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);

			tacacsKey.assign(command->part(2));
		}

		// timeout...
		else if (strcasecmp(command->part(1), "timeout") == 0)
		{
			if (device->config->reportFormat == Config::Debug)
				printf("%sTACACS+ Timeout Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);

			tacacsTimeout = atoi(command->part(2));
		}

		// host...
		else if (strcasecmp(command->part(1), "host") == 0)
		{
			if (device->config->reportFormat == Config::Debug)
				printf("%sTACACS+ Host Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);

			tacacsPointer = addTacacsServer();
			tacacsPointer->address.assign(command->part(2));
			if (strcasecmp(command->part(3), "key") == 0)
				tacacsPointer->key.assign(command->part(4));
			else
				tacacsPointer->key.assign(tacacsKey);
			tacacsPointer->timeout = tacacsTimeout;
			if (tacacsFirst == true)
				tacacsPointer->description.assign(i18n("Primary"));
			else
				tacacsPointer->description.assign(i18n("Backup"));
			tacacsFirst = false;
		}

		// NOT PROCESSED...
		else
			device->lineNotProcessed(line);
	}

	// radius...
	else if (strcasecmp(command->part(0), "radius-server") == 0)
	{

		// key...
		if (strcasecmp(command->part(1), "key") == 0)
		{
			if (device->config->reportFormat == Config::Debug)
				printf("%sRADIUS Key Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);

			radiusKey.assign(command->part(2));
		}

		// timeout...
		else if (strcasecmp(command->part(1), "timeout") == 0)
		{
			if (device->config->reportFormat == Config::Debug)
				printf("%sRADIUS Timeout Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);

			radiusTimeout = atoi(command->part(2));
		}

		// host...
		else if (strcasecmp(command->part(1), "host") == 0)
		{
			if (device->config->reportFormat == Config::Debug)
				printf("%sRADIUS Host Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);

			radiusPointer = addRadiusServer();
			radiusPointer->address.assign(command->part(2));
			radiusPointer->key.assign(radiusKey);
			tempInt = 3;
			while (tempInt < command->parts)
			{
				if (strcasecmp(command->part(3), "key") == 0)
				{
					tempInt++;
					radiusPointer->key.assign(command->part(tempInt));
				}
				tempInt++;
			}
			radiusPointer->timeout = radiusTimeout;
			if (radiusFirst == true)
				radiusPointer->description.assign(i18n("Primary"));
			else
				radiusPointer->description.assign(i18n("Backup"));
			radiusFirst = false;
		}

		// NOT PROCESSED...
		else
			device->lineNotProcessed(line);
	}

	// password manager...
	else if ((strcasecmp(command->part(0), "password") == 0) && (strcasecmp(command->part(1), "manager") == 0))
	{
		if (device->config->reportFormat == Config::Debug)
			printf("%sManager Password Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);
		managerPresent = true;
	}

	// password operator...
	else if ((strcasecmp(command->part(0), "password") == 0) && (strcasecmp(command->part(1), "operator") == 0))
	{
		if (device->config->reportFormat == Config::Debug)
			printf("%sOperator Password Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);
		operatorPresent = true;
	}

	// aaa authentication...
	else if ((strcasecmp(command->part(0), "aaa") == 0) && (strcasecmp(command->part(1), "authentication") == 0) && ((strcasecmp(command->part(3), "login") == 0) || (strcasecmp(command->part(3), "enable") == 0)))
	{
		if (device->config->reportFormat == Config::Debug)
			printf("%sAAA Authentication Line:%s %s\n", device->config->COL_GREEN, device->config->COL_RESET, line);

		authPointer = addMethod();
		authPointer->appliesTo.assign(command->part(2));
		authPointer->level.assign(command->part(3));
		if (strcasecmp(command->part(4), "local") == 0)
			authPointer->method = localAuth;
		else if (strcasecmp(command->part(4), "radius") == 0)
			authPointer->method = radiusAuth;
		else if (strcasecmp(command->part(4), "tacacs") == 0)
			authPointer->method = tacacsAuth;

		if (command->parts == 6)
		{
			authPointer = addMethod();
			authPointer->appliesTo.assign(command->part(2));
			authPointer->level.assign(command->part(3));
			if (strcasecmp(command->part(5), "local") == 0)
				authPointer->method = localAuth;
			else if (strcasecmp(command->part(5), "radius") == 0)
				authPointer->method = radiusAuth;
			else if (strcasecmp(command->part(5), "tacacs") == 0)
				authPointer->method = tacacsAuth;
		}
	}

	// NOT PROCESSED...
	else
		device->lineNotProcessed(line);

	return errorCode;
}
Example #15
0
int CreatIvtTable(void){

	char buffer[1024];
	FILE *rFile, *wFile;
	rFile = fopen("en09062011.news","r");
	wFile = fopen("Ivt_Idx","w");

	IvtSct *IHead;
	IHead = (IvtSct *) malloc(sizeof(IvtSct));
	IHead->arc = (Article *)malloc(sizeof(Article));
	strcpy(IHead->Word, "");
	IHead->pNext = NULL;
	IHead->arc->pNext = NULL;

	int ArticleNum = 0;
	if ( NULL == rFile ){
        printf( "Open failure" );
        return -1;
    }else{
    	while (fgets(buffer, 1024, rFile) != NULL){
    		int idx=0;
    		char http[4];
    		for(idx=0;idx<4;idx++)
    			http[idx] = buffer[idx];

    		http[idx] = '\0';


    		if((strcasecmp(http, "http")) == 0){
    			int i=0;
    			for (int i=0; i<5; i++ ){
    				fgets(buffer, 1024, rFile);
    			}
    			ArticleNum++;
    		}
    		else{
    			char word[25] = "";
    			int word_idx = 0;
	    		for (idx=0; buffer[idx] != '\0'; idx++){
	    			if (buffer[idx] >= 97 && buffer[idx] <= 122){
	    				word[word_idx++] = buffer[idx];
	    			}
    				else{
    					word[word_idx] = '\0';

    					//printf("%s\n", word);
    					if (strcmp(word, "") != 0)
    						AddIvtSct(word, IHead, ArticleNum);

    					word_idx = 0;
    					strcpy(word, "");
	       			}
	    		}
	    	}
    	}
    }
    IHead = IHead->pNext;
	while (IHead != NULL){
		fprintf(wFile,"%s\n%d\n",IHead->Word,IHead->feq);
		Article *temp = IHead->arc;
		while (temp != NULL){
			fprintf(wFile,"%d ",temp->No);
			temp = temp->pNext;
		}
		fprintf(wFile, "\n");
		IHead = IHead->pNext;
	}
    return 1;
}
Example #16
0
static int open_tv(tvi_handle_t *tvh)
{
    int i;
    const tvi_functions_t *funcs = tvh->functions;
    int tv_fmt_list[] = {
      IMGFMT_YV12,
      IMGFMT_I420,
      IMGFMT_UYVY,
      IMGFMT_YUY2,
      IMGFMT_RGB32,
      IMGFMT_RGB24,
      IMGFMT_RGB16,
      IMGFMT_RGB15
    };

    if (funcs->control(tvh->priv, TVI_CONTROL_IS_VIDEO, 0) != TVI_CONTROL_TRUE)
    {
	mp_tmsg(MSGT_TV, MSGL_ERR, "Error: No video input present!\n");
	return 0;
    }

    if (tvh->tv_param->outfmt == -1)
      for (i = 0; i < sizeof (tv_fmt_list) / sizeof (*tv_fmt_list); i++)
        {
          tvh->tv_param->outfmt = tv_fmt_list[i];
          if (funcs->control (tvh->priv, TVI_CONTROL_VID_SET_FORMAT,
                              &tvh->tv_param->outfmt) == TVI_CONTROL_TRUE)
            break;
        }
    else
    {
    switch(tvh->tv_param->outfmt)
    {
	case IMGFMT_YV12:
	case IMGFMT_I420:
	case IMGFMT_UYVY:
	case IMGFMT_YUY2:
	case IMGFMT_RGB32:
	case IMGFMT_RGB24:
	case IMGFMT_BGR32:
	case IMGFMT_BGR24:
	case IMGFMT_BGR16:
	case IMGFMT_BGR15:
	    break;
	default:
	    mp_tmsg(MSGT_TV, MSGL_ERR,
			"==================================================================\n"\
			" WARNING: UNTESTED OR UNKNOWN OUTPUT IMAGE FORMAT REQUESTED (0x%x)\n"\
			" This may cause buggy playback or program crash! Bug reports will\n"\
			" be ignored! You should try again with YV12 (which is the default\n"\
			" colorspace) and read the documentation!\n"\
			"==================================================================\n"
		,tvh->tv_param->outfmt);
    }
    funcs->control(tvh->priv, TVI_CONTROL_VID_SET_FORMAT, &tvh->tv_param->outfmt);
    }

    /* set some params got from cmdline */
    funcs->control(tvh->priv, TVI_CONTROL_SPC_SET_INPUT, &tvh->tv_param->input);

#if defined(CONFIG_TV_V4L2) || defined(CONFIG_TV_DSHOW)
    if (0
#ifdef CONFIG_TV_V4L2
    || (!strcmp(tvh->tv_param->driver, "v4l2") && tvh->tv_param->normid >= 0)
#endif
#ifdef CONFIG_TV_DSHOW
    || (!strcmp(tvh->tv_param->driver, "dshow") && tvh->tv_param->normid >= 0)
#endif
    )
	tv_set_norm_i(tvh, tvh->tv_param->normid);
    else
#endif
    tv_set_norm(tvh,tvh->tv_param->norm);

#ifdef CONFIG_TV_V4L1
    if ( tvh->tv_param->mjpeg )
    {
      /* set width to expected value */
      if (tvh->tv_param->width == -1)
        {
          tvh->tv_param->width = 704/tvh->tv_param->decimation;
        }
      if (tvh->tv_param->height == -1)
        {
	  if ( tvh->norm != TV_NORM_NTSC )
            tvh->tv_param->height = 576/tvh->tv_param->decimation;
	  else
            tvh->tv_param->height = 480/tvh->tv_param->decimation;
        }
      mp_tmsg(MSGT_TV, MSGL_INFO,
	       "  MJP: width %d height %d\n", tvh->tv_param->width, tvh->tv_param->height);
    }
#endif

    /* limits on w&h are norm-dependent -- JM */
    if (tvh->tv_param->width != -1 && tvh->tv_param->height != -1) {
        // first tell the driver both width and height, some drivers do not support setting them independently.
        int dim[2];
        dim[0] = tvh->tv_param->width; dim[1] = tvh->tv_param->height;
        funcs->control(tvh->priv, TVI_CONTROL_VID_SET_WIDTH_HEIGHT, dim);
    }
    /* set width */
    if (tvh->tv_param->width != -1)
    {
	if (funcs->control(tvh->priv, TVI_CONTROL_VID_CHK_WIDTH, &tvh->tv_param->width) == TVI_CONTROL_TRUE)
	    funcs->control(tvh->priv, TVI_CONTROL_VID_SET_WIDTH, &tvh->tv_param->width);
	else
	{
	    mp_tmsg(MSGT_TV, MSGL_ERR, "Unable to set requested width: %d\n", tvh->tv_param->width);
	    funcs->control(tvh->priv, TVI_CONTROL_VID_GET_WIDTH, &tvh->tv_param->width);
	}
    }

    /* set height */
    if (tvh->tv_param->height != -1)
    {
	if (funcs->control(tvh->priv, TVI_CONTROL_VID_CHK_HEIGHT, &tvh->tv_param->height) == TVI_CONTROL_TRUE)
	    funcs->control(tvh->priv, TVI_CONTROL_VID_SET_HEIGHT, &tvh->tv_param->height);
	else
	{
	    mp_tmsg(MSGT_TV, MSGL_ERR, "Unable to set requested height: %d\n", tvh->tv_param->height);
	    funcs->control(tvh->priv, TVI_CONTROL_VID_GET_HEIGHT, &tvh->tv_param->height);
	}
    }

    if (funcs->control(tvh->priv, TVI_CONTROL_IS_TUNER, 0) != TVI_CONTROL_TRUE)
    {
	mp_tmsg(MSGT_TV, MSGL_WARN, "Selected input hasn't got a tuner!\n");
	goto done;
    }

    /* select channel list */
    for (i = 0; chanlists[i].name != NULL; i++)
    {
	if (!strcasecmp(chanlists[i].name, tvh->tv_param->chanlist))
	{
	    tvh->chanlist = i;
	    tvh->chanlist_s = chanlists[i].list;
	    break;
	}
    }

    if (tvh->chanlist == -1)
	mp_tmsg(MSGT_TV, MSGL_WARN, "Unable to find selected channel list! (%s)\n",
	    tvh->tv_param->chanlist);
    else
	mp_tmsg(MSGT_TV, MSGL_V, "Selected channel list: %s (including %d channels)\n",
	    chanlists[tvh->chanlist].name, chanlists[tvh->chanlist].count);

    if (tvh->tv_param->freq && tvh->tv_param->channel)
    {
	mp_tmsg(MSGT_TV, MSGL_WARN, "You can't set frequency and channel simultaneously!\n");
	goto done;
    }

    /* Handle channel names */
    if (tvh->tv_param->channels) {
        parse_channels(tvh);
    } else
	    tv_channel_last_real = malloc(5);

    if (tv_channel_list) {
	int i;
	int channel = 0;
	if (tvh->tv_param->channel)
	 {
	   if (isdigit(*tvh->tv_param->channel))
		/* if tvh->tv_param->channel begins with a digit interpret it as a number */
		channel = atoi(tvh->tv_param->channel);
	   else
	      {
		/* if tvh->tv_param->channel does not begin with a digit
		   set the first channel that contains tvh->tv_param->channel in its name */

		tv_channel_current = tv_channel_list;
		while ( tv_channel_current ) {
			if ( strstr(tv_channel_current->name, tvh->tv_param->channel) )
			  break;
			tv_channel_current = tv_channel_current->next;
			}
		if ( !tv_channel_current ) tv_channel_current = tv_channel_list;
	      }
	 }
	else
		channel = 1;

	if ( channel ) {
	tv_channel_current = tv_channel_list;
	for (i = 1; i < channel; i++)
		if (tv_channel_current->next)
			tv_channel_current = tv_channel_current->next;
	}

	mp_tmsg(MSGT_TV, MSGL_INFO, "Selected channel: %s - %s (freq: %.3f)\n", tv_channel_current->number,
			tv_channel_current->name, (float)tv_channel_current->freq/1000);
	tv_set_norm_i(tvh, tv_channel_current->norm);
	tv_set_freq(tvh, (unsigned long)(((float)tv_channel_current->freq/1000)*16));
	tv_channel_last = tv_channel_current;
    } else {
    /* we need to set frequency */
    if (tvh->tv_param->freq)
    {
	unsigned long freq = atof(tvh->tv_param->freq)*16;

        /* set freq in MHz */
	funcs->control(tvh->priv, TVI_CONTROL_TUN_SET_FREQ, &freq);

	funcs->control(tvh->priv, TVI_CONTROL_TUN_GET_FREQ, &freq);
	mp_tmsg(MSGT_TV, MSGL_V, "Selected frequency: %lu (%.3f)\n",
	    freq, (float)freq/16);
    }

	    if (tvh->tv_param->channel) {
	struct CHANLIST cl;

	mp_tmsg(MSGT_TV, MSGL_V, "Requested channel: %s\n", tvh->tv_param->channel);
	for (i = 0; i < chanlists[tvh->chanlist].count; i++)
	{
	    cl = tvh->chanlist_s[i];
		    //  printf("count%d: name: %s, freq: %d\n",
		    //	i, cl.name, cl.freq);
	    if (!strcasecmp(cl.name, tvh->tv_param->channel))
	    {
			strcpy(tv_channel_last_real, cl.name);
		tvh->channel = i;
		mp_tmsg(MSGT_TV, MSGL_INFO, "Selected channel: %s (freq: %.3f)\n",
		    cl.name, (float)cl.freq/1000);
		tv_set_freq(tvh, (unsigned long)(((float)cl.freq/1000)*16));
		break;
	    }
	}
    }
    }

    /* grep frequency in chanlist */
    {
	unsigned long i2;
	int freq;

	tv_get_freq(tvh, &i2);

	freq = (int) (((float)(i2/16))*1000)+250;

	for (i = 0; i < chanlists[tvh->chanlist].count; i++)
	{
	    if (tvh->chanlist_s[i].freq == freq)
	    {
		tvh->channel = i+1;
		break;
	    }
	}
    }

done:
    /* also start device! */
	return 1;
}
Example #17
0
static void exe_cgi( int sock, const char *method, const char *path, const char *query_string )
{
	char buf[SIZE];
	int content_length = -1;

	//pipe named by child side
	int cgi_input[2];
	int cgi_output[2];
	char method_env[SIZE];
	char query_string_env[SIZE];
	char content_length_env[SIZE];
	char tmpc;
	
	memset(buf, '\0', sizeof(buf));				// ! ! ! ! !  M U S T     I N I T   A R R A Y ! ! !     
	memset(method_env, '\0', sizeof(method_env));
	memset(query_string_env, '\0', sizeof(query_string));
	memset(content_length_env, '\0', sizeof(content_length_env));



	if(strcasecmp(method, "GET") == 0 )
	{
		clear_header(sock);			//"GET" send val by url ,already get
	}

	int ret = 0;
	if(strcasecmp(method, "POST") == 0 )  //different
	{
		do
		{
			memset(buf, '\0', sizeof(buf));
			ret = get_line(sock, buf, sizeof(buf));
			if( strncasecmp(buf, "Content-Length: ", 16) == 0)
			{
				content_length = atoi(&buf[16]);
			}
		}while( (ret > 0) && strcmp(buf, "\n") != 0 );

		printf("content_length = %d\n", content_length);

		if( content_length == -1 )
		{
			echo_errno(sock);  
			return;
		}
	}
/////////////  (8.11)  /////////////////////////////
	
	sprintf(buf, "HTTP/1.0 200 OK\r\n\r\n");
	send(sock, buf, strlen(buf), 0);

	if( pipe(cgi_input) < 0 )
	{
		echo_errno(sock);
		return;
	}
	if( pipe(cgi_output) < 0 )
	{
		echo_errno(sock);
		return;
	}

	pid_t id = fork();
	if(id == 0)		//child
	{
		close(cgi_input[1]);
		close(cgi_output[0]);
  
		dup2(cgi_input[0], 0);
		dup2(cgi_output[1], 1);


		sprintf(method_env, "REQUEST_METHOD=%s", method);
		putenv(method_env);
		if( strcasecmp(method, "GET") == 0 )		//GET	
		{
			sprintf(query_string_env, "QUERY_STRING=%s", query_string);
			putenv(query_string_env);
		}
		else  //POST
		{
			sprintf(content_length_env, "CONTENT_LENGTH=%d", content_length);
			putenv(content_length_env);
		}
		execl(path, path, NULL);
		//run here , execl wrong
		exit(1);
	}
	else  //father
	{
		close(cgi_input[0]);
		close(cgi_output[1]);
		
	//	dup2(cgi_input[1], 1);
	//	dup2(cgi_output[0], 0);

		char c = '\0';
		int  i =0;

		if( strcasecmp(method, "POST") == 0 )
		{
			for(; i < content_length; ++i)  
			{
				recv(sock, &c, 1, 0);
				printf("%c", c);
				write(cgi_input[1], &c, 1);
			}
		}
		
		int ret = 0;
		while( read(cgi_output[0], &c, 1) > 0)
		{
			send(sock, &c, 1, 0);
		}

		waitpid(id, NULL, 0);
	}

}
Example #18
0
static void gs_cmd_set_open(sourceinfo_t *si, int parc, char *parv[])
{
	mygroup_t *mg;

	if (!parv[0] || !parv[1])
	{
		command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "OPEN");
		command_fail(si, fault_needmoreparams, _("Syntax: OPEN <!group> <ON|OFF>"));
		return;
	}

	if ((mg = mygroup_find(parv[0])) == NULL)
	{
		command_fail(si, fault_nosuch_target, _("The group \2%s\2 does not exist."), parv[0]);
		return;
	}

	if (!groupacs_sourceinfo_has_flag(mg, si, GA_FOUNDER))
	{
		command_fail(si, fault_noprivs, _("You are not authorized to execute this command."));
		return;
	}

	if (!strcasecmp(parv[1], "ON"))
	{
		if (!gs_config->enable_open_groups)
		{
			command_fail(si, fault_nochange, _("Setting groups as open has been administratively disabled."));
			return;
		}

		if (mg->flags & MG_OPEN)
		{
			command_fail(si, fault_nochange, _("\2%s\2 is already open to anyone joining."), entity(mg)->name);
			return;
		}

		mg->flags |= MG_OPEN;

		logcommand(si, CMDLOG_SET, "OPEN:ON: \2%s\2", entity(mg)->name);
		command_success_nodata(si, _("\2%s\2 is now open to anyone joining."), entity(mg)->name);
	}
	else if (!strcasecmp(parv[1], "OFF"))
	{
		if (!(mg->flags & MG_OPEN))
		{
			command_fail(si, fault_nochange, _("\2%s\2 is already not open to anyone joining."), entity(mg)->name);
			return;
		}

		mg->flags &= ~MG_OPEN;

		logcommand(si, CMDLOG_SET, "OPEN:OFF: \2%s\2", entity(mg)->name);
		command_success_nodata(si, _("\2%s\2 is no longer open to anyone joining."), entity(mg)->name);
	}
	else
	{
		command_fail(si, fault_badparams, STR_INVALID_PARAMS, "OPEN");
		command_fail(si, fault_badparams, _("Syntax: OPEN <!group> <ON|OFF>"));
	}
}
Example #19
0
// TODO: use orientation to correctly rotate the image.
// maybe this should be (partly) in common/imageio.[c|h]?
static void _lib_import_update_preview(GtkFileChooser *file_chooser, gpointer data)
{
  GtkWidget *preview;
  char *filename;
  GdkPixbuf *pixbuf = NULL;
  gboolean have_preview = FALSE;

  preview = GTK_WIDGET(data);
  filename = gtk_file_chooser_get_preview_filename(file_chooser);

  if(!g_file_test(filename, G_FILE_TEST_IS_REGULAR)) goto no_preview_fallback;
  // don't create dng thumbnails to avoid crashes in libtiff when these are hdr:
  char *c = filename + strlen(filename);
  while(c > filename && *c != '.') c--;
  if(!strcasecmp(c, ".dng")) goto no_preview_fallback;

  pixbuf = gdk_pixbuf_new_from_file_at_size(filename, 128, 128, NULL);
  have_preview = (pixbuf != NULL);
  if(!have_preview)
  {
    // raw image thumbnail
    int ret;
    libraw_data_t *raw = libraw_init(0);
    libraw_processed_image_t *image = NULL;
    ret = libraw_open_file(raw, filename);
    if(ret) goto libraw_fail;
    ret = libraw_unpack_thumb(raw);
    if(ret) goto libraw_fail;
    ret = libraw_adjust_sizes_info_only(raw);
    if(ret) goto libraw_fail;

    image = libraw_dcraw_make_mem_thumb(raw, &ret);
    if(!image || ret) goto libraw_fail;
//     const int orientation = raw->sizes.flip;

    GdkPixbuf *tmp;
    GdkPixbufLoader *loader = gdk_pixbuf_loader_new();
    have_preview = gdk_pixbuf_loader_write(loader, image->data, image->data_size, NULL);
    tmp = gdk_pixbuf_loader_get_pixbuf(loader);
    gdk_pixbuf_loader_close(loader, NULL);
    float ratio;
    if(image->type == LIBRAW_IMAGE_JPEG)
    {
      // jpeg
      dt_imageio_jpeg_t jpg;
      if(dt_imageio_jpeg_decompress_header(image->data, image->data_size, &jpg)) goto libraw_fail;
      ratio = 1.0*jpg.height/jpg.width;
    }
    else
    {
      // bmp -- totally untested
      ratio = 1.0*image->height/image->width;
    }
    int width = 128, height = 128*ratio;
    pixbuf = gdk_pixbuf_scale_simple(tmp, width, height, GDK_INTERP_BILINEAR);

    if(loader)
      g_object_unref(loader);

    // clean up raw stuff.
    libraw_recycle(raw);
    libraw_close(raw);
    free(image);
    if(0)
    {
libraw_fail:
      // fprintf(stderr,"[imageio] %s: %s\n", filename, libraw_strerror(ret));
      libraw_close(raw);
      have_preview = FALSE;
    }
  }
  if(!have_preview)
  {
no_preview_fallback:
    pixbuf = gdk_pixbuf_new_from_inline(-1, dt_logo_128x128, FALSE, NULL);
    have_preview = TRUE;
  }
  if(have_preview)
    gtk_image_set_from_pixbuf(GTK_IMAGE(preview), pixbuf);
  if(pixbuf)
    g_object_unref(pixbuf);
  g_free(filename);

  gtk_file_chooser_set_preview_widget_active(file_chooser, have_preview);
}
Example #20
0
int parse_codec_cfg(const char *cfgfile)
{
    codecs_t *codec = NULL; // current codec
    codecs_t **codecsp = NULL;// points to audio_codecs or to video_codecs
    char *endptr;   // strtoul()...
    int *nr_codecsp;
    int codec_type;     /* TYPE_VIDEO/TYPE_AUDIO */
    int tmp, i;

    // in case we call it a second time
    codecs_uninit_free();

    nr_vcodecs = 0;
    nr_acodecs = 0;

    if(cfgfile==NULL) {
#ifdef CODECS2HTML
        return 0;
#else
        video_codecs = builtin_video_codecs;
        audio_codecs = builtin_audio_codecs;
        nr_vcodecs = sizeof(builtin_video_codecs)/sizeof(codecs_t);
        nr_acodecs = sizeof(builtin_audio_codecs)/sizeof(codecs_t);
        return 1;
#endif
    }

    mp_msg(MSGT_CODECCFG, MSGL_V, "Reading optional codecs config file %s: ", cfgfile);

    if ((fp = fopen(cfgfile, "r")) == NULL) {
        mp_msg(MSGT_CODECCFG, MSGL_V, "%s\n", strerror(errno));
        return 0;
    }

    if ((line = malloc(MAX_LINE_LEN + 1)) == NULL) {
        mp_msg(MSGT_CODECCFG,MSGL_FATAL,MSGTR_CantGetMemoryForLine, strerror(errno));
        return 0;
    }
    read_nextline = 1;

    /*
     * this only catches release lines at the start of
     * codecs.conf, before audiocodecs and videocodecs.
     */
    while ((tmp = get_token(1, 1)) == RET_EOL)
        /* NOTHING */;
    if (tmp == RET_EOF)
        goto out;
    if (!strcmp(token[0], "release")) {
        if (get_token(1, 2) < 0)
            goto err_out_parse_error;
        tmp = atoi(token[0]);
        if (tmp < CODEC_CFG_MIN)
            goto err_out_release_num;
        codecs_conf_release = tmp;
        while ((tmp = get_token(1, 1)) == RET_EOL)
            /* NOTHING */;
        if (tmp == RET_EOF)
            goto out;
    } else
        goto err_out_release_num;

    /*
     * check if the next block starts with 'audiocodec' or
     * with 'videocodec'
     */
    if (!strcmp(token[0], "audiocodec") || !strcmp(token[0], "videocodec"))
        goto loop_enter;
    goto err_out_parse_error;

    while ((tmp = get_token(1, 1)) != RET_EOF) {
        if (tmp == RET_EOL)
            continue;
        if (!strcmp(token[0], "audiocodec") ||
            !strcmp(token[0], "videocodec")) {
            if (!validate_codec(codec, codec_type))
                goto err_out_not_valid;
        loop_enter:
            if (*token[0] == 'v') {
                codec_type = TYPE_VIDEO;
                nr_codecsp = &nr_vcodecs;
                codecsp = &video_codecs;
            } else if (*token[0] == 'a') {
                codec_type = TYPE_AUDIO;
                nr_codecsp = &nr_acodecs;
                codecsp = &audio_codecs;
#ifdef DEBUG
            } else {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,"picsba\n");
                goto err_out;
#endif
            }
            if (!(*codecsp = realloc(*codecsp,
                                     sizeof(codecs_t) * (*nr_codecsp + 2)))) {
                mp_msg(MSGT_CODECCFG,MSGL_FATAL,MSGTR_CantReallocCodecsp, strerror(errno));
                goto err_out;
            }
            codec=*codecsp + *nr_codecsp;
            ++*nr_codecsp;
            memset(codec,0,sizeof(codecs_t));
            memset(codec->fourcc, 0xff, sizeof(codec->fourcc));
            memset(codec->outfmt, 0xff, sizeof(codec->outfmt));
            memset(codec->infmt, 0xff, sizeof(codec->infmt));

            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            for (i = 0; i < *nr_codecsp - 1; i++) {
                if(( (*codecsp)[i].name!=NULL) &&
                   (!strcmp(token[0], (*codecsp)[i].name)) ) {
                    mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CodecNameNotUnique, token[0]);
                    goto err_out_print_linenum;
                }
            }
            if (!(codec->name = strdup(token[0]))) {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupName, strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "info")) {
            if (codec->info || get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->info = strdup(token[0]))) {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupInfo, strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "comment")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            add_comment(token[0], &codec->comment);
        } else if (!strcmp(token[0], "fourcc")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_fourcc(token[0], token[1],
                               codec->fourcc,
                               codec->fourccmap))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "format")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_format(token[0], token[1],
                               codec->fourcc,codec->fourccmap))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "driver")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->drv = strdup(token[0]))) {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupDriver, strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "dll")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->dll = strdup(token[0]))) {
                mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CantStrdupDLL, strerror(errno));
                goto err_out;
            }
        } else if (!strcmp(token[0], "guid")) {
            if (get_token(11, 11) < 0)
                goto err_out_parse_error;
            codec->guid.f1=strtoul(token[0],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            codec->guid.f2=strtoul(token[1],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            codec->guid.f3=strtoul(token[2],&endptr,0);
            if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                *endptr != '\0')
                goto err_out_parse_error;
            for (i = 0; i < 8; i++) {
                codec->guid.f4[i]=strtoul(token[i + 3],&endptr,0);
                if ((*endptr != ',' || *(endptr + 1) != '\0') &&
                    *endptr != '\0')
                    goto err_out_parse_error;
            }
        } else if (!strcmp(token[0], "out")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_inout(token[0], token[1], codec->outfmt,
                              codec->outflags))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "in")) {
            if (get_token(1, 2) < 0)
                goto err_out_parse_error;
            if (!add_to_inout(token[0], token[1], codec->infmt,
                              codec->inflags))
                goto err_out_print_linenum;
        } else if (!strcmp(token[0], "flags")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!strcmp(token[0], "seekable"))
                codec->flags |= CODECS_FLAG_SEEKABLE;
            else
            if (!strcmp(token[0], "align16"))
                codec->flags |= CODECS_FLAG_ALIGN16;
            else
            if (!strcmp(token[0], "dummy"))
                codec->flags |= CODECS_FLAG_DUMMY;
            else
                goto err_out_parse_error;
        } else if (!strcmp(token[0], "status")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!strcasecmp(token[0], "working"))
                codec->status = CODECS_STATUS_WORKING;
            else if (!strcasecmp(token[0], "crashing"))
                codec->status = CODECS_STATUS_NOT_WORKING;
            else if (!strcasecmp(token[0], "untested"))
                codec->status = CODECS_STATUS_UNTESTED;
            else if (!strcasecmp(token[0], "buggy"))
                codec->status = CODECS_STATUS_PROBLEMS;
            else
                goto err_out_parse_error;
        } else if (!strcmp(token[0], "cpuflags")) {
            if (get_token(1, 1) < 0)
                goto err_out_parse_error;
            if (!(codec->cpuflags = get_cpuflags(token[0])))
                goto err_out_parse_error;
        } else
            goto err_out_parse_error;
    }
    if (!validate_codec(codec, codec_type))
        goto err_out_not_valid;
    mp_msg(MSGT_CODECCFG,MSGL_INFO,MSGTR_AudioVideoCodecTotals, nr_acodecs, nr_vcodecs);
    if(video_codecs) video_codecs[nr_vcodecs].name = NULL;
    if(audio_codecs) audio_codecs[nr_acodecs].name = NULL;
out:
    free(line);
    line=NULL;
    fclose(fp);
    return 1;

err_out_parse_error:
    mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_ParseError);
err_out_print_linenum:
    PRINT_LINENUM;
err_out:
    codecs_uninit_free();

    free(line);
    line=NULL;
    line_num = 0;
    fclose(fp);
    return 0;
err_out_not_valid:
    mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_CodecDefinitionIncorrect);
    goto err_out_print_linenum;
err_out_release_num:
    mp_msg(MSGT_CODECCFG,MSGL_ERR,MSGTR_OutdatedCodecsConf);
    goto err_out_print_linenum;
}
Example #21
0
// parser based on HTML widget parser
//
const char *KBookmarkManager::parse( BookmarkTokenizer *ht, KBookmark *parent,
	const char *_end )
{
	KBookmark *bm = parent;
	QString text;
	const char *str;

	parent->setType( KBookmark::Folder );

	while ( ht->hasMoreTokens() )
	{
		str = ht->nextToken();

		if (str[0] == TAG_ESCAPE )
		{
			str++;

			if ( _end[0] != 0 && strcasecmp( str, _end ) == 0 )
			{
				return str;
			}
			else if ( strncasecmp( str, "<dl>", 4 ) == 0 )
			{
				parse( ht, bm, "</dl>" );
			}
			else if ( strncasecmp( str, "<dt>", 4 ) == 0 )
			{
				bm = new KBookmark;
				parent->getChildren().append( bm );
			}
			else if ( strncasecmp( str, "<a ", 3 ) == 0 )
			{
				const char *p = str + 3;

				while ( *p != '>' )
				{
					if ( strncasecmp( p, "href=", 5 ) == 0 )
					{
						p += 5;

						text = "";
						bool quoted = false;
						while ( ( *p != ' ' && *p != '>' ) || quoted )
						{
							if ( *p == '\"' )
								quoted = !quoted;
							else
								text += *p;
							p++;
						}

						bm->setURL( text );
			
						if ( *p == ' ' )
							p++;
					}
					else
					{
						char *p2 = strchr( (char*) p, ' ' );
						if ( p2 == 0L )
							p2 = strchr( (char*) p, '>');
						else
							p2++;
						p = p2;
					}
				}

				text = "";
			}
			else if ( strncasecmp( str, "<H3", 3 ) == 0 )
			{
				text = "";
			}
			else if ( strncasecmp( str, "</H3>", 5 ) == 0 ||
						strncasecmp( str, "</a>", 4 ) == 0 )
			{
				bm->setText( text );
			}
		}
		else if ( str[0] )
		{
			text += str;
		}
	}

	return NULL;
}
Example #22
0
/* Use all available means to detect file language
 */
const char *ohcount_detect_language(SourceFile *sourcefile) {
  const char *language = NULL;
  char *p, *pe;
  int length;

  // Attempt to detect using Emacs mode line (/^-\*-\s*mode[\s:]*\w/i).
  char line[81] = { '\0' }, buf[81];
  p = ohcount_sourcefile_get_contents(sourcefile);
  pe = p;
  char *eof = p + ohcount_sourcefile_get_contents_size(sourcefile);
  while (pe < eof) {
    // Get the contents of the first line.
    while (pe < eof && *pe != '\r' && *pe != '\n') pe++;
    length = (pe - p <= sizeof(line)) ? pe - p : sizeof(line);
    strncpy(line, p, length);
    line[length] = '\0';
    if (*line == '#' && *(line + 1) == '!') {
      // First line was sh-bang; loop to get contents of second line.
      while (*pe == '\r' || *pe == '\n') pe++;
      p = pe;
    } else break;
  }
  p = strstr(line, "-*-");
  if (p) {
    p += 3;
    while (*p == ' ' || *p == '\t') p++;
    // detect "mode" (any capitalization)
    if (strncasecmp(p, "mode", 4) == 0) {
      p += 4;
      while (*p == ' ' || *p == '\t' || *p == ':') p++;
    }
    pe = p;
    while (!isspace(*pe) && *pe != ';' && pe != strstr(pe, "-*-")) pe++;
    length = (pe - p <= sizeof(buf)) ? pe - p : sizeof(buf);
    strncpy(buf, p, length);
    buf[length] = '\0';

		// Special case for "c" or "C" emacs mode header: always means C, not C++
		if (strcasecmp(buf, "c") == 0) {
				return LANG_C;
		}

    // First try it with the language name.
    struct LanguageMap *rl = ohcount_hash_language_from_name(buf, length);
    if (rl) language = rl->name;
    if(!language) {
      // Then try it with the extension table.
      struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
      if (re) language = re->value;
    }
    if (!language) {
      // Try the lower-case version of this modeline.
      for (pe = buf; pe < buf+length; pe++) *pe = tolower(*pe);
      // First try it with the language name.
      rl = ohcount_hash_language_from_name(buf, length);
      if (rl) language = rl->name;
    }
    if (!language) {
      // Then try it with the extension table.
      struct ExtensionMap *re = ohcount_hash_language_from_ext(buf, length);
      if (re) language = re->value;
    }
  }

  // Attempt to detect based on file extension.
  if(!language) {
      length = strlen(sourcefile->ext);
      struct ExtensionMap *re = ohcount_hash_language_from_ext(sourcefile->ext,
                                                               length);
      if (re) language = re->value;
    if (!language) {
      // Try the lower-case version of this extension.
      char lowerext[length + 1];
      strncpy(lowerext, sourcefile->ext, length);
      lowerext[length] = '\0';
      for (p = lowerext; p < lowerext + length; p++) *p = tolower(*p);
      struct ExtensionMap *re = ohcount_hash_language_from_ext(lowerext, length);
      if (re) language = re->value;
    }
  }

  // Attempt to detect based on filename.
  if(!language) {
    length = strlen(sourcefile->filename);
    struct FilenameMap *rf =
      ohcount_hash_language_from_filename(sourcefile->filename, length);
    if (rf) language = rf->value;
  }

  // Attempt to detect based on Unix 'file' command.
  if(!language) {
    language = detect_language_magic(sourcefile);
  }

  if (language) {
    if (ISAMBIGUOUS(language)) {
      // Call the appropriate function for disambiguation.
      length = strlen(DISAMBIGUATEWHAT(language));
      struct DisambiguateFuncsMap *rd =
        ohcount_hash_disambiguate_func_from_id(DISAMBIGUATEWHAT(language),
                                               length);
      if (rd) language = rd->value(sourcefile);
    } else language = ISBINARY(language) ? NULL : language;
  }
  return language;
}
Example #23
0
/* 根据延时Sample的结果,创建阅读性比较好的分析报告 */
sds createLatencyReport(void) {
    sds report = sdsempty();
    int advise_better_vm = 0;       /* Better virtual machines. */
    int advise_slowlog_enabled = 0; /* Enable slowlog. */
    int advise_slowlog_tuning = 0;  /* Reconfigure slowlog. */
    int advise_slowlog_inspect = 0; /* Check your slowlog. */
    int advise_disk_contention = 0; /* Try to lower disk contention. */
    int advise_scheduler = 0;       /* Intrinsic latency. */
    int advise_data_writeback = 0;  /* data=writeback. */
    int advise_no_appendfsync = 0;  /* don't fsync during rewrites. */
    int advise_local_disk = 0;      /* Avoid remote disks. */
    int advise_ssd = 0;             /* Use an SSD drive. */
    int advise_write_load_info = 0; /* Print info about AOF and write load. */
    int advise_hz = 0;              /* Use higher HZ. */
    int advise_large_objects = 0;   /* Deletion of large objects. */
    int advise_relax_fsync_policy = 0; /* appendfsync always is slow. */
    int advices = 0;

    /* Return ASAP if the latency engine is disabled and it looks like it
     * was never enabled so far. */
    if (dictSize(server.latency_events) == 0 &&
        server.latency_monitor_threshold == 0)
    {
        report = sdscat(report,"I'm sorry, Dave, I can't do that. Latency monitoring is disabled in this Redis instance. You may use \"CONFIG SET latency-monitor-threshold <milliseconds>.\" in order to enable it. If we weren't in a deep space mission I'd suggest to take a look at http://redis.io/topics/latency-monitor.\n");
        return report;
    }

    /* Show all the events stats and add for each event some event-related
     * comment depending on the values. */
    dictIterator *di;
    dictEntry *de;
    int eventnum = 0;

    di = dictGetIterator(server.latency_events);
    while((de = dictNext(di)) != NULL) {
        char *event = dictGetKey(de);
        struct latencyTimeSeries *ts = dictGetVal(de);
        struct latencyStats ls;

        if (ts == NULL) continue;
        eventnum++;
        if (eventnum == 1) {
            report = sdscat(report,"Dave, I have observed latency spikes in this Redis instance. You don't mind talking about it, do you Dave?\n\n");
        }
        analyzeLatencyForEvent(event,&ls);
		
		//根据结果构造报告字符串
        report = sdscatprintf(report,
            "%d. %s: %d latency spikes (average %lums, mean deviation %lums, period %.2f sec). Worst all time event %lums.",
            eventnum, event,
            ls.samples,
            (unsigned long) ls.avg,
            (unsigned long) ls.mad,
            (double) ls.period/ls.samples,
            (unsigned long) ts->max);

        /* Fork */
        if (!strcasecmp(event,"fork")) {
            char *fork_quality;
            if (server.stat_fork_rate < 10) {
                fork_quality = "terrible";
                advise_better_vm = 1;
                advices++;
            } else if (server.stat_fork_rate < 25) {
                fork_quality = "poor";
                advise_better_vm = 1;
                advices++;
            } else if (server.stat_fork_rate < 100) {
                fork_quality = "good";
            } else {
                fork_quality = "excellent";
            }
            report = sdscatprintf(report,
                " Fork rate is %.2f GB/sec (%s).", server.stat_fork_rate,
                fork_quality);
        }

        /* Potentially commands. */
        if (!strcasecmp(event,"command")) {
            if (server.slowlog_log_slower_than == 0) {
                advise_slowlog_enabled = 1;
                advices++;
            } else if (server.slowlog_log_slower_than/1000 >
                       server.latency_monitor_threshold)
            {
                advise_slowlog_tuning = 1;
                advices++;
            }
            advise_slowlog_inspect = 1;
            advise_large_objects = 1;
            advices += 2;
        }

        /* fast-command. */
        if (!strcasecmp(event,"fast-command")) {
            advise_scheduler = 1;
            advices++;
        }

        /* AOF and I/O. */
        if (!strcasecmp(event,"aof-write-pending-fsync")) {
            advise_local_disk = 1;
            advise_disk_contention = 1;
            advise_ssd = 1;
            advise_data_writeback = 1;
            advices += 4;
        }

        if (!strcasecmp(event,"aof-write-active-child")) {
            advise_no_appendfsync = 1;
            advise_data_writeback = 1;
            advise_ssd = 1;
            advices += 3;
        }

        if (!strcasecmp(event,"aof-write-alone")) {
            advise_local_disk = 1;
            advise_data_writeback = 1;
            advise_ssd = 1;
            advices += 3;
        }

        if (!strcasecmp(event,"aof-fsync-always")) {
            advise_relax_fsync_policy = 1;
            advices++;
        }

        if (!strcasecmp(event,"aof-fstat") ||
            !strcasecmp(event,"rdb-unlik-temp-file")) {
            advise_disk_contention = 1;
            advise_local_disk = 1;
            advices += 2;
        }

        if (!strcasecmp(event,"aof-rewrite-diff-write") ||
            !strcasecmp(event,"aof-rename")) {
            advise_write_load_info = 1;
            advise_data_writeback = 1;
            advise_ssd = 1;
            advise_local_disk = 1;
            advices += 4;
        }

        /* Expire cycle. */
        if (!strcasecmp(event,"expire-cycle")) {
            advise_hz = 1;
            advise_large_objects = 1;
            advices += 2;
        }

        /* Eviction cycle. */
        if (!strcasecmp(event,"eviction-cycle")) {
            advise_large_objects = 1;
            advices++;
        }

        report = sdscatlen(report,"\n",1);
    }
    dictReleaseIterator(di);

    if (eventnum == 0) {
        report = sdscat(report,"Dave, no latency spike was observed during the lifetime of this Redis instance, not in the slightest bit. I honestly think you ought to sit down calmly, take a stress pill, and think things over.\n");
    } else if (advices == 0) {
        report = sdscat(report,"\nWhile there are latency events logged, I'm not able to suggest any easy fix. Please use the Redis community to get some help, providing this report in your help request.\n");
    } else {
        /* Add all the suggestions accumulated so far. */

        /* Better VM. */
        report = sdscat(report,"\nI have a few advices for you:\n\n");
        if (advise_better_vm) {
            report = sdscat(report,"- If you are using a virtual machine, consider upgrading it with a faster one using an hypervisior that provides less latency during fork() calls. Xen is known to have poor fork() performance. Even in the context of the same VM provider, certain kinds of instances can execute fork faster than others.\n");
        }

        /* Slow log. */
        if (advise_slowlog_enabled) {
            report = sdscatprintf(report,"- There are latency issues with potentially slow commands you are using. Try to enable the Slow Log Redis feature using the command 'CONFIG SET slowlog-log-slower-than %llu'. If the Slow log is disabled Redis is not able to log slow commands execution for you.\n", (unsigned long long)server.latency_monitor_threshold*1000);
        }

        if (advise_slowlog_tuning) {
            report = sdscatprintf(report,"- Your current Slow Log configuration only logs events that are slower than your configured latency monitor threshold. Please use 'CONFIG SET slowlog-log-slower-than %llu'.\n", (unsigned long long)server.latency_monitor_threshold*1000);
        }

        if (advise_slowlog_inspect) {
            report = sdscat(report,"- Check your Slow Log to understand what are the commands you are running which are too slow to execute. Please check http://redis.io/commands/slowlog for more information.\n");
        }

        /* Intrinsic latency. */
        if (advise_scheduler) {
            report = sdscat(report,"- The system is slow to execute Redis code paths not containing system calls. This usually means the system does not provide Redis CPU time to run for long periods. You should try to:\n"
            "  1) Lower the system load.\n"
            "  2) Use a computer / VM just for Redis if you are running other softawre in the same system.\n"
            "  3) Check if you have a \"noisy neighbour\" problem.\n"
            "  4) Check with 'redis-cli --intrinsic-latency 100' what is the intrinsic latency in your system.\n"
            "  5) Check if the problem is allocator-related by recompiling Redis with MALLOC=libc, if you are using Jemalloc. However this may create fragmentation problems.\n");
        }

        /* AOF / Disk latency. */
        if (advise_local_disk) {
            report = sdscat(report,"- It is strongly advised to use local disks for persistence, especially if you are using AOF. Remote disks provided by platform-as-a-service providers are known to be slow.\n");
        }

        if (advise_ssd) {
            report = sdscat(report,"- SSD disks are able to reduce fsync latency, and total time needed for snapshotting and AOF log rewriting (resulting in smaller memory usage and smaller final AOF rewrite buffer flushes). With extremely high write load SSD disks can be a good option. However Redis should perform reasonably with high load using normal disks. Use this advice as a last resort.\n");
        }

        if (advise_data_writeback) {
            report = sdscat(report,"- Mounting ext3/4 filesystems with data=writeback can provide a performance boost compared to data=ordered, however this mode of operation provides less guarantees, and sometimes it can happen that after a hard crash the AOF file will have an half-written command at the end and will require to be repaired before Redis restarts.\n");
        }

        if (advise_disk_contention) {
            report = sdscat(report,"- Try to lower the disk contention. This is often caused by other disk intensive processes running in the same computer (including other Redis instances).\n");
        }

        if (advise_no_appendfsync) {
            report = sdscat(report,"- Assuming from the point of view of data safety this is viable in your environment, you could try to enable the 'no-appendfsync-on-rewrite' option, so that fsync will not be performed while there is a child rewriting the AOF file or producing an RDB file (the moment where there is high disk contention).\n");
        }

        if (advise_relax_fsync_policy && server.aof_fsync == AOF_FSYNC_ALWAYS) {
            report = sdscat(report,"- Your fsync policy is set to 'always'. It is very hard to get good performances with such a setup, if possible try to relax the fsync policy to 'onesec'.\n");
        }

        if (advise_write_load_info) {
            report = sdscat(report,"- Latency during the AOF atomic rename operation or when the final difference is flushed to the AOF file at the end of the rewrite, sometimes is caused by very high write load, causing the AOF buffer to get very large. If possible try to send less commands to accomplish the same work, or use Lua scripts to group multiple operations into a single EVALSHA call.\n");
        }

        if (advise_hz && server.hz < 100) {
            report = sdscat(report,"- In order to make the Redis keys expiring process more incremental, try to set the 'hz' configuration parameter to 100 using 'CONFIG SET hz 100'.\n");
        }

        if (advise_large_objects) {
            report = sdscat(report,"- Deleting, expiring or evicting (because of maxmemory policy) large objects is a blocking operation. If you have very large objects that are often deleted, expired, or evicted, try to fragment those objects into multiple smaller objects.\n");
        }
    }

    return report;
}
Example #24
0
File: main.c Project: mdhender/jr
int jr_service_request(int fdServer, int fdClient, FILE *stream) {
    /* variables for connection I/O */
    char cgiargs[BUFSIZE]; /* cgi argument list */
    char filename[BUFSIZE];/* path derived from uri */
    char method[BUFSIZE];  /* request method */
    char uri[BUFSIZE];     /* request uri */
    
    /* get the HTTP request line */
    char buf[BUFSIZE];     /* message buffer */
    char version[BUFSIZE]; /* request method */
    fgets(buf, BUFSIZE, stream);
    printf("%s", buf);
    sscanf(buf, "%s %s %s\n", method, uri, version);
    
    /* tiny only supports the GET method */
    if (strcasecmp(method, "GET") != 0) {
        jr_send_client_generic_error(stream, method, 501, "Not Implemented", "Tiny does not implement this method");
        fclose(stream);
        close(fdClient);
        return 0;
    }
    
    /* read (and ignore) the HTTP headers */
    fgets(buf, BUFSIZE, stream);
    printf("%s", buf);
    
    while (strcmp(buf, "\r\n")) {
        fgets(buf, BUFSIZE, stream);
        printf("%s", buf);
    }
    
    /* parse the uri [crufty] */
    int is_static;         /* static request? */
    if (strstr(uri, "cgi-bin") != 0) { /* static content */
        is_static = 1;
        strcpy(cgiargs, "");
        strcpy(filename, ".");
        strcat(filename, uri);
        
        if (uri[strlen(uri) - 1] == '/') {
            strcat(filename, "index.html");
        }
    } else { /* dynamic content */
        is_static = 0;
        char *p = index(uri, '?');
        
        if (p) {
            strcpy(cgiargs, p + 1);
            *p = '\0';
        } else {
            strcpy(cgiargs, "");
        }
        
        strcpy(filename, ".");
        strcat(filename, uri);
    }
    
    /* make sure the file exists */
    struct stat sbuf;
    if (stat(filename, &sbuf) < 0) {
        jr_send_client_generic_error(stream, filename, 404, "Not found", "Tiny couldn't find this file");
        return 0;
    }
    
    if (is_static) {
        /* serve static content */
        const char *filetype;
        if (strstr(filename, ".html")) {
            filetype = "text/html";
        } else if (strstr(filename, ".gif")) {
            filetype = "image/gif";
        } else if (strstr(filename, ".jpg")) {
            filetype = "image/jpg";
        } else {
            filetype = "text/plain";
        }
        
        jr_serve_file(stream, filename, filetype, &sbuf);
    } else {
        /* serve dynamic content */
        jr_send_client_generic_error(stream, filename, 403, "Forbidden", "You are not allow to access this item");
        return 0;
    }
    
    return 0;
}
Example #25
0
int
http_send_request( URL_t *url, off_t pos ) {
	HTTP_header_t *http_hdr;
	URL_t *server_url;
	char str[256];
	int fd = -1;
	int ret;
	int proxy = 0;		// Boolean

	http_hdr = http_new_header();

	if( !strcasecmp(url->protocol, "http_proxy") ) {
		proxy = 1;
		server_url = url_new( (url->file)+1 );
		http_set_uri( http_hdr, server_url->url );
	} else {
		server_url = url;
		http_set_uri( http_hdr, server_url->file );
	}
	if (server_url->port && server_url->port != 80)
	    snprintf(str, 256, "Host: %s:%d", server_url->hostname, server_url->port );
	else
	    snprintf(str, 256, "Host: %s", server_url->hostname );
	http_set_field( http_hdr, str);
	if (network_useragent)
	{
	    snprintf(str, 256, "User-Agent: %s", network_useragent);
	    http_set_field(http_hdr, str);
	}
	else
	    http_set_field( http_hdr, "User-Agent: MPlayer/"VERSION);

	http_set_field(http_hdr, "Icy-MetaData: 1");

	if(pos>0) { 
	// Extend http_send_request with possibility to do partial content retrieval
	    snprintf(str, 256, "Range: bytes=%"PRId64"-", (int64_t)pos);
	    http_set_field(http_hdr, str);
	}
	    
	if (network_cookies_enabled) cookies_set( http_hdr, server_url->hostname, server_url->url );
	
	http_set_field( http_hdr, "Connection: close");
	http_add_basic_authentication( http_hdr, url->username, url->password );
	if( http_build_request( http_hdr )==NULL ) {
		goto err_out;
	}

	if( proxy ) {
		if( url->port==0 ) url->port = 8080;			// Default port for the proxy server
		fd = connect2Server( url->hostname, url->port,1 );
		url_free( server_url );
		server_url = NULL;
	} else {
		if( server_url->port==0 ) server_url->port = 80;	// Default port for the web server
		fd = connect2Server( server_url->hostname, server_url->port,1 );
	}
	if( fd<0 ) {
		goto err_out;
	}
	mp_msg(MSGT_NETWORK,MSGL_DBG2,"Request: [%s]\n", http_hdr->buffer );
	
	ret = send( fd, http_hdr->buffer, http_hdr->buffer_size, 0 );
	if( ret!=(int)http_hdr->buffer_size ) {
		mp_msg(MSGT_NETWORK,MSGL_ERR,MSGTR_MPDEMUX_NW_ErrSendingHTTPRequest);
		goto err_out;
	}
	
	http_free( http_hdr );

	return fd;
err_out:
	if (fd > 0) closesocket(fd);
	http_free(http_hdr);
	if (proxy && server_url)
		url_free(server_url);
	return -1;
}
Example #26
0
/* this is for incoming calls callweaver sccp_request */
static int sccp_pbx_call(struct cw_channel *ast, char *dest, int timeout) {
	sccp_line_t	 * l;
	sccp_device_t  * d;
	sccp_session_t * s;
	sccp_channel_t * c;
	char * ringermode = NULL;
	pthread_attr_t attr;
	pthread_t t;

	c = CS_CW_CHANNEL_PVT(ast);

	if (!c) {
		cw_log(LOG_WARNING, "SCCP: CallWeaver request to call %s channel: %s, but we don't have this channel!\n", dest, ast->name);
		return -1;
	}

	l = c->line;
	d = l->device;
	s = d->session;

	if (!l || !d || !s) {
		cw_log(LOG_WARNING, "SCCP: weird error. The channel %d has no line or device or session\n", (c ? c->callid : 0) );
		return -1;
	}

	sccp_log(1)(VERBOSE_PREFIX_3 "%s: CallWeaver request to call %s\n", d->id, ast->name);

	cw_mutex_lock(&d->lock);

	if (d->dnd) {
		if (d->dndmode == SCCP_DNDMODE_REJECT) {
			cw_mutex_unlock(&d->lock);
			cw_setstate(ast, CW_STATE_BUSY);
			cw_queue_control(ast, CW_CONTROL_BUSY);
			sccp_log(1)(VERBOSE_PREFIX_3 "%s: DND is on. Call %s rejected\n", d->id, ast->name);
			return 0;
		} else if (d->dndmode == SCCP_DNDMODE_SILENT) {
			/* disable the ringer and autoanswer options */
			c->ringermode = SKINNY_STATION_SILENTRING;
			c->autoanswer_type = SCCP_AUTOANSWER_NONE;
			sccp_log(1)(VERBOSE_PREFIX_3 "%s: DND (silent) is on. Set the ringer = silent and autoanswer = off for %s\n", d->id, ast->name);
		}
	}

	/* if incoming call limit is reached send BUSY */
	cw_mutex_lock(&l->lock);
	if ( l->channelCount > l->incominglimit ) { /* >= just to be sure :-) */
		sccp_log(1)(VERBOSE_PREFIX_3 "Incoming calls limit (%d) reached on SCCP/%s... sending busy\n", l->incominglimit, l->name);
		cw_mutex_unlock(&l->lock);
		cw_mutex_unlock(&d->lock);
		cw_setstate(ast, CW_STATE_BUSY);
		cw_queue_control(ast, CW_CONTROL_BUSY);
		return 0;
	}
	cw_mutex_unlock(&l->lock);

	/* autoanswer check */
	if (c->autoanswer_type) {
		if (d->channelCount > 1) {
			sccp_log(1)(VERBOSE_PREFIX_3 "%s: Autoanswer requested, but the device is in use\n", d->id);
			c->autoanswer_type = SCCP_AUTOANSWER_NONE;
			if (c->autoanswer_cause) {
				switch (c->autoanswer_cause) {
					case CW_CAUSE_CONGESTION:
						cw_queue_control(ast, CW_CONTROL_CONGESTION);
						break;
					default:
						cw_queue_control(ast, CW_CONTROL_BUSY);
						break;
				}
				cw_mutex_unlock(&d->lock);
				return 0;
			}
		} else {
			sccp_log(1)(VERBOSE_PREFIX_3 "%s: Autoanswer requested and activated %s\n", d->id, (c->autoanswer_type == SCCP_AUTOANSWER_1W) ? "with MIC OFF" : "with MIC ON");
		}
	}
	cw_mutex_unlock(&d->lock);

  /* Set the channel callingParty Name and Number */
	sccp_channel_set_callingparty(c, ast->cid.cid_name, ast->cid.cid_num);

  /* Set the channel calledParty Name and Number 7910 compatibility*/
	sccp_channel_set_calledparty(c, l->cid_name, l->cid_num);

	if (!c->ringermode) {
		c->ringermode = SKINNY_STATION_OUTSIDERING;
		ringermode = pbx_builtin_getvar_helper(ast, "ALERT_INFO");
	}

	if ( ringermode && !cw_strlen_zero(ringermode) ) {
		sccp_log(1)(VERBOSE_PREFIX_3 "%s: Found ALERT_INFO=%s\n", d->id, ringermode);
		if (strcasecmp(ringermode, "inside") == 0)
			c->ringermode = SKINNY_STATION_INSIDERING;
		else if (strcasecmp(ringermode, "feature") == 0)
			c->ringermode = SKINNY_STATION_FEATURERING;
		else if (strcasecmp(ringermode, "silent") == 0)
			c->ringermode = SKINNY_STATION_SILENTRING;
		else if (strcasecmp(ringermode, "urgent") == 0)
			c->ringermode = SKINNY_STATION_URGENTRING;
	}

	/* release the callweaver lock */
	cw_mutex_unlock(&ast->lock);
	if ( sccp_channel_get_active(d) ) {
		sccp_indicate_lock(c, SCCP_CHANNELSTATE_CALLWAITING);
		cw_queue_control(ast, CW_CONTROL_RINGING);
	} else {
		sccp_indicate_lock(c, SCCP_CHANNELSTATE_RINGIN);
		cw_queue_control(ast, CW_CONTROL_RINGING);
		if (c->autoanswer_type) {
			sccp_log(1)(VERBOSE_PREFIX_3 "%s: Running the autoanswer thread on %s\n", d->id, ast->name);
			pthread_attr_init(&attr);
			pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
			if (cw_pthread_create(&t, &attr, sccp_pbx_call_autoanswer_thread, &c->callid)) {
				cw_log(LOG_WARNING, "%s: Unable to create switch thread for channel (%s-%d) %s\n", d->id, l->name, c->callid, strerror(errno));
			}
		}
	}
	return 0;
}
Example #27
0
/* If `name' has a correct extension, try to list its contents and search for
   the first file with a proper extension; if found, extract it.  If this
   succeeds, return the name of the temporary file; if the archive file is
   valid but `write_mode' is non-zero, return a zero-length string; in all
   the other cases, return NULL.  */
static char *try_uncompress_archive(const char *name, int write_mode,
                                    const char *program,
                                    const char *listopts,
                                    const char *extractopts,
                                    const char *extension,
                                    const char *search)
{
#ifdef __riscos
    return NULL;
#else
    char *tmp_name = NULL;
    int l = strlen(name), nameoffset, found = 0, len;
    int exit_status;
    char *argv[8];
    FILE *fd;
    char tmp[1024];

    /* Do we have correct extension?  */
    len = strlen(extension);
    if (l <= len || strcasecmp(name + l - len, extension) != 0)
        return NULL;

    /* First run listing and search for first recognizeable extension.  */
    argv[0] = lib_stralloc(program);
    argv[1] = lib_stralloc(listopts);
    argv[2] = archdep_filename_parameter(name);
    argv[3] = NULL;

    ZDEBUG(("try_uncompress_archive: spawning `%s %s %s'",
            program, listopts, name));
    exit_status = archdep_spawn(program, argv, &tmp_name, NULL);

    lib_free(argv[0]);
    lib_free(argv[1]);
    lib_free(argv[2]);

    /* No luck?  */
    if (exit_status != 0) {
        ZDEBUG(("try_uncompress_archive: `%s %s' failed.", program,
                listopts));
        ioutil_remove(tmp_name);
        lib_free(tmp_name);
        return NULL;
    }

    ZDEBUG(("try_uncompress_archive: `%s %s' successful.", program,
            listopts));

    fd = fopen(tmp_name, MODE_READ);
    if (!fd) {
        ZDEBUG(("try_uncompress_archive: cannot read `%s %s' output.",
                program, tmp_name));
        ioutil_remove(tmp_name);
        lib_free(tmp_name);
        return NULL;
    }

    ZDEBUG(("try_uncompress_archive: searching for the first valid file."));

    /* Search for `search' first (if any) to see the offset where
       filename begins, then search for first recognizeable file.  */
    nameoffset = search ? -1 : 0;
    len = search ? strlen(search) : 0;
    while (!feof(fd) && !found) {
        fgets(tmp, 1024, fd);
        l = strlen(tmp);
        while (l > 0) {
            tmp[--l] = 0;
            if (nameoffset < 0 && l >= len &&
                    !strcasecmp(tmp + l - len, search) != 0) {
                nameoffset = l - 4;
            }
            if (nameoffset >= 0 && is_valid_extension(tmp, l, nameoffset)) {
                ZDEBUG(("try_uncompress_archive: found `%s'.",
                        tmp + nameoffset));
                found = 1;
                break;
            }
        }
    }

    fclose(fd);
    ioutil_remove(tmp_name);
    if (!found) {
        ZDEBUG(("try_uncompress_archive: no valid file found."));
        lib_free(tmp_name);
        return NULL;
    }

    /* This would be a valid ZIP file, but we cannot handle ZIP files in
       write mode.  Return a null temporary file name to report this.  */
    if (write_mode) {
        ZDEBUG(("try_uncompress_archive: cannot open file in write mode."));
        lib_free(tmp_name);
        return "";
    }

    /* And then file inside zip.  If we have a zipcode extract all of them
       to the same file. */
    argv[0] = lib_stralloc(program);
    argv[1] = lib_stralloc(extractopts);
    argv[2] = archdep_filename_parameter(name);
    if (is_zipcode_name(tmp + nameoffset)) {
        argv[3] = lib_stralloc(tmp + nameoffset);
        argv[4] = lib_stralloc(tmp + nameoffset);
        argv[5] = lib_stralloc(tmp + nameoffset);
        argv[6] = lib_stralloc(tmp + nameoffset);
        argv[7] = NULL;
        argv[3][0] = '1';
        argv[4][0] = '2';
        argv[5][0] = '3';
        argv[6][0] = '4';
    } else {
        argv[3] = archdep_quote_parameter(tmp + nameoffset);
        argv[4] = NULL;
    }

    ZDEBUG(("try_uncompress_archive: spawning `%s %s %s %s'.",
            program, extractopts, name, tmp + nameoffset));
    exit_status = archdep_spawn(program, argv, &tmp_name, NULL);

    lib_free(argv[0]);
    lib_free(argv[1]);
    lib_free(argv[2]);
    lib_free(argv[3]);
    if (is_zipcode_name(tmp + nameoffset)) {
        lib_free(argv[4]);
        lib_free(argv[5]);
        lib_free(argv[6]);
    }

    if (exit_status != 0) {
        ZDEBUG(("try_uncompress_archive: `%s %s' failed.",
                program, extractopts));
        ioutil_remove(tmp_name);
        lib_free(tmp_name);
        return NULL;
    }

    ZDEBUG(("try_uncompress_archive: `%s %s' successful.", program,
            tmp_name));
    return tmp_name;
#endif
}
Example #28
0
/* To parse the lock or config file.
   For example, parse_config("file", "delay", "hda1", char **value) will:
   	1. return 2 if match with '*'. Ex: "delay:*"
   	2. return 1 if match the whole token. Ex: "delay:hda1"
   	3. return 3 if match partial token. Ex: "delay:hda"
   	4. return 0 if not match
   	5. return -1 if the format is wrong
   The maximum length of value is 64.
   	
   */
int parse_config(const char *file, const char *name, const char *target, char *value)
{
	FILE *f;
	char *ptr1, *ptr2, *ptr3=NULL, *ptr4=NULL, *brk_str;
	char line[100]; 
	char *sep=": \t\n";

	if(!file || !name || !target) {
		return -1;
	}

	f = fopen(file, "rt");
	if(!f) {
		return 0;
	}
	while(fgets(line, 100, f)) {
		if((ptr1 = strtok_r(line, sep, &brk_str))) {
			if(ptr1[0] == '#')
				continue;
			if((ptr2 = strtok_r(NULL, sep, &brk_str)))
				if((ptr3 = strtok_r(NULL, sep, &brk_str)))
					ptr4 = strtok_r(NULL, sep, &brk_str);
			if(ptr4) {
				fclose(f);
				return -1;
			}
			if(!strcasecmp(ptr1, name) && ptr2) {
// Decide if the value is necessary. For example, the value of "redirect:sda1:rw,/tmp/aaa" is "rw,/tmp/aaa"
				if((value && !ptr3) || (!value && ptr3)) {
					continue;
					//fclose(f); // by cfyeh
					//return -1; // by cfyeh
				}
				if(ptr3) {
// The maximum length of value is 64.
					if(strlen(ptr3) > 63) {
						fclose(f);
						return -1;
					}
					//strcpy(value, ptr3); // by cfyeh
				}
// Match the whole token
// Exp: parse_config("file", "delay", "hda1", char *value) found "delay:hda1"
				if(!strcasecmp(ptr2, target)) {
					// for ignore:sata:2 or ignore:usb:1
					if(ptr3)
					{
						if(!strcasecmp(ptr3, value)) {
							fclose(f);
							return 1;
						}
						if(!strcasecmp(ptr3, "*")) {
							fclose(f);
							return 2;
						}
						if(!strncasecmp(ptr3, value, strlen(ptr3))) {
							fclose(f);
							return 3;
						}
						continue;
					}
					fclose(f);
					return 1;
				}
// Match the whole token with '*'
// Exp: parse_config("file", "delay", "hda1", char *value) found "delay:*"
				if(!strcasecmp(ptr2, "*")) {
					fclose(f);
					return 2;
				}
// Match partial token
// Exp: parse_config("file", "delay", "hda1", char *value) found "delay:hda"
				if(!strncasecmp(ptr2, target, strlen(ptr2))) {
					fclose(f);
					return 3;
				}
			}
		}
	}

	fclose(f);
	return 0;
}
Example #29
0
int main(int argc, char **argv)
{
   FILE *fp;
   char *vertag;
   int version;
   int revision;
   char fname[MAX_FNAME];
   char buf[80];
   time_t t;
   struct tm *tp;

   if ((argc > 3) || (argc < 2))
   {
      printf("Usage: %s <Project> [<Version>]\n", argv[0]);
      return(5);
   }

   vertag = "";
   version =  1;
   revision = 0;

   /* Determine the name of the revision file */
   strncpy(fname, argv[1], MAX_FNAME-7);
   fname[MAX_FNAME-7] = 0;
   strcat(fname, "_rev.h");

   /* See if the file already exists. */
   fp = fopen(fname, "r");
   if (fp != NULL)
   {
      /* It exists, get the version and revision out of it */
      while(fgets(buf, 80, fp) != NULL)
      {
         int ln;
         ln = strlen(buf)-1;
         if (buf[ln] == '\n') buf[ln] = 0;

         if (!memcmp(buf, "#define ", 8))
         {
            char *p;
            p = buf+8;
            while(*p == ' ' || *p == '\t') p++;
            if (!memcmp(p, "VERS ", 5))
            {
               p += 4;
               while(*p == ' ' || *p == '\t') p++;
               /* Now we need to get past the name of the executable */
               ln = strlen(argv[1]);
               if (strlen(p) > ln)
               {
                  char c;
                  c = p[ln];
                  p[ln] = 0;
                  if (strcasecmp(p, argv[1]))
                  {
                     /* We don't have a match, we need to go for the */
                     /* space which separates the name               */
                     p[ln] = c;
                     while (*p && *p != ' ') p++;
                  }
                  else
                  {
                     /* Well, it matches, shift past the name */
                     p += ln + 1;
                  }
                  /* Now we should be pointing past the name (and a single space) */
                  /* at any aux version tag information that they might have      */
                  /* we want to go from the END of the string and eliminate any   */
                  /* numeric digits that are there.                               */
                  ln = strlen(p);
                  if ((ln > 1) && (p[ln-1] == '"')) ln--;
                  while((ln > 1) && (p[ln-1] >= '0') && (p[ln-1] <= '9')) ln--;
                  if ((ln > 1) && (p[ln-1] == '.'))
                  {
		      ln--;
	              while((ln > 1) && (p[ln-1] >= '0') && (p[ln-1] <= '9')) ln--;
                  }
                  p[ln] = 0;
                  while (*p == ' ' || *p == '\t') p++;
                  vertag = strdup(p);
               }
            }
            else if (!memcmp(p, "VERSION ", 8))
            {
               version = atoi(p+7);
            }
            else if (!memcmp(p, "REVISION ", 9)) revision = atoi(p+8);
         }
      }

      fclose(fp);
   }

   revision++;

   /* Figure out what version number we will be using */
   if (argc > 2)
   {
      int oldver = version;
      version = atoi(argv[2]);
      if (version != oldver)
         revision = 0;
   }

   fp = fopen(fname, "w");
   if (fp == NULL)
   {
      perror(fname);
      return(20);
   }

   time(&t);
   tp = localtime(&t);

   (void)tp->tm_mday;
   (void)tp->tm_year;
   (void)tp->tm_mon;

   sprintf(buf, "%d.%d.%d", tp->tm_mday, tp->tm_mon+1, tp->tm_year);

   /* Figure out what is the number to */

   fprintf(fp, "#define VERSION        %d\n",
                                       version);
   fprintf(fp, "#define REVISION       %3d\n",
                                       revision);
   fprintf(fp, "#define DATE    \"%s\"\n",
                                  buf);
   fprintf(fp, "#define VERS    \"%s %s%d.%d\"\n",
                                 argv[1], vertag, version, revision);
   fprintf(fp, "#define VSTRING \"%s %s%d.%d (%s)\"\n",
                                 argv[1], vertag, version, revision, buf);
   fprintf(fp, "#define VERSTAG \"\\0$%s: %s %s%d.%d (%s)\"\n",
                                 "VER", argv[1], vertag, version, revision, buf);
   fclose(fp);

   return(0);
}
Example #30
0
static SalStreamDescription * sdp_to_stream_description(SalMediaDescription *md, belle_sdp_media_description_t *media_desc) {
	SalStreamDescription *stream;
	belle_sdp_connection_t* cnx;
	belle_sdp_media_t* media;
	belle_sdp_attribute_t* attribute;
	const char* value;
	const char *mtype,*proto;

	stream=&md->streams[md->nb_streams];
	media=belle_sdp_media_description_get_media ( media_desc );

	proto = belle_sdp_media_get_protocol ( media );
	stream->proto=SalProtoOther;
	if ( proto ) {
		if (strcasecmp(proto, "RTP/AVP") == 0) {
			stream->proto = SalProtoRtpAvp;
		} else if (strcasecmp(proto, "RTP/SAVP") == 0) {
			stream->proto = SalProtoRtpSavp;
		} else if (strcasecmp(proto, "RTP/AVPF") == 0) {
			stream->proto = SalProtoRtpAvpf;
		} else if (strcasecmp(proto, "RTP/SAVPF") == 0) {
			stream->proto = SalProtoRtpSavpf;
		} else if (strcasecmp(proto, "UDP/TLS/RTP/SAVP") == 0) {
			stream->proto = SalProtoUdpTlsRtpSavp;
		} else if (strcasecmp(proto, "UDP/TLS/RTP/SAVPF") == 0) {
			stream->proto = SalProtoUdpTlsRtpSavpf;
		} else {
			strncpy(stream->proto_other,proto,sizeof(stream->proto_other)-1);
		}
	}
	if ( ( cnx=belle_sdp_media_description_get_connection ( media_desc ) ) && belle_sdp_connection_get_address ( cnx ) ) {
		strncpy ( stream->rtp_addr,belle_sdp_connection_get_address ( cnx ), sizeof ( stream->rtp_addr ) -1 );
		stream->ttl=belle_sdp_connection_get_ttl(cnx);
	}

	stream->rtp_port=belle_sdp_media_get_media_port ( media );

	mtype = belle_sdp_media_get_media_type ( media );
	if ( strcasecmp ( "audio", mtype ) == 0 ) {
		stream->type=SalAudio;
	} else if ( strcasecmp ( "video", mtype ) == 0 ) {
		stream->type=SalVideo;
	} else {
		stream->type=SalOther;
		strncpy ( stream->typeother,mtype,sizeof ( stream->typeother )-1 );
	}

	if ( belle_sdp_media_description_get_bandwidth ( media_desc,"AS" ) >0 ) {
		stream->bandwidth=belle_sdp_media_description_get_bandwidth ( media_desc,"AS" );
	}

	if ( belle_sdp_media_description_get_attribute ( media_desc,"sendrecv" ) ) {
		stream->dir=SalStreamSendRecv;
	} else if ( belle_sdp_media_description_get_attribute ( media_desc,"sendonly" ) ) {
		stream->dir=SalStreamSendOnly;
	} else if ( belle_sdp_media_description_get_attribute ( media_desc,"recvonly" ) ) {
		stream->dir=SalStreamRecvOnly;
	} else if ( belle_sdp_media_description_get_attribute ( media_desc,"inactive" ) ) {
		stream->dir=SalStreamInactive;
	} else {
		stream->dir=md->dir; /*takes default value if not present*/
	}

	/* Get media payload types */
	sdp_parse_payload_types(media_desc, stream);

	/* Get media specific RTCP attribute */
	stream->rtcp_port = stream->rtp_port + 1;
	snprintf(stream->rtcp_addr, sizeof(stream->rtcp_addr), "%s", stream->rtp_addr);
	attribute=belle_sdp_media_description_get_attribute(media_desc,"rtcp");
	if (attribute && (value=belle_sdp_attribute_get_value(attribute))!=NULL){
		char tmp[256];
		int nb = sscanf(value, "%d IN IP4 %s", &stream->rtcp_port, tmp);
		if (nb == 1) {
			/* SDP rtcp attribute only contains the port */
		} else if (nb == 2) {
			strncpy(stream->rtcp_addr, tmp, sizeof(stream->rtcp_addr)-1);
		} else {
			ms_warning("sdp has a strange a=rtcp line (%s) nb=%i", value, nb);
		}
	}

	/* Read DTLS specific attributes : check is some are found in the stream description otherwise copy the session description one(which are at least set to Invalid) */
	if (((stream->proto == SalProtoUdpTlsRtpSavpf) || (stream->proto == SalProtoUdpTlsRtpSavp))) {
		attribute=belle_sdp_media_description_get_attribute(media_desc,"setup");
		if (attribute && (value=belle_sdp_attribute_get_value(attribute))!=NULL){
			if (strncmp(value, "actpass", 7) == 0) {
				stream->dtls_role = SalDtlsRoleUnset;
			} else if (strncmp(value, "active", 6) == 0) {
				stream->dtls_role = SalDtlsRoleIsClient;
			} else if (strncmp(value, "passive", 7) == 0) {
				stream->dtls_role = SalDtlsRoleIsServer;
			}
		}
		if (stream->dtls_role != SalDtlsRoleInvalid && (attribute=belle_sdp_media_description_get_attribute(media_desc,"fingerprint"))) {
			strncpy(stream->dtls_fingerprint, belle_sdp_attribute_get_value(attribute),sizeof(stream->dtls_fingerprint));
		}
	}

	/* Read crypto lines if any */
	if ((stream->proto == SalProtoRtpSavpf) || (stream->proto == SalProtoRtpSavp)) {
		sdp_parse_media_crypto_parameters(media_desc, stream);
	}

	/* Get ICE candidate attributes if any */
	sdp_parse_media_ice_parameters(media_desc, stream);

	/* Get RTCP-FB attributes if any */
	if ((stream->proto == SalProtoRtpAvpf) || (stream->proto == SalProtoRtpSavpf)) {
		enable_avpf_for_stream(stream);
		sdp_parse_rtcp_fb_parameters(media_desc, stream);
	}

	/* Get RTCP-XR attributes if any */
	stream->rtcp_xr = md->rtcp_xr;	// Use session parameters if no stream parameters are defined
	sdp_parse_media_rtcp_xr_parameters(media_desc, &stream->rtcp_xr);

	md->nb_streams++;
	return stream;
}