Exemple #1
0
void outgoing_message::send(czmqpp::socket& socket) const
{
    czmqpp::message message;

    // [ DESTINATION ] (optional - ROUTER sockets strip this)
    if (!dest_.empty())
        message.append(dest_);

    // [ COMMAND ]
    append_str(message, command_);

    // [ ID ]
    auto raw_id = to_chunk(to_little_endian(id_));
    BITCOIN_ASSERT(raw_id.size() == sizeof(id_));
    message.append(raw_id);

    // [ DATA ]
    message.append(data_);

    // Send.
    message.send(socket);
}
//--------------------------------------------------------------------------
int idaapi rpc_debmod_t::dbg_update_lowcnds(const lowcnd_t *lowcnds, int nlowcnds)
{
  ea_t ea = 0;
  bytevec_t req = prepare_rpc_packet(RPC_UPDATE_LOWCNDS);
  append_dd(req, nlowcnds);
  const lowcnd_t *lc = lowcnds;
  for ( int i=0; i < nlowcnds; i++, lc++ )
  {
    append_ea64(req, lc->ea-ea); ea = lc->ea;
    append_str(req, lc->cndbody);
    if ( !lc->cndbody.empty() )
    {
      append_dd(req, lc->type);
      if ( lc->type != BPT_SOFT )
        append_dd(req, lc->size);
      append_db(req, lc->orgbytes.size());
      append_memory(req, lc->orgbytes.begin(), lc->orgbytes.size());
      append_ea64(req, lc->cmd.ea);
      if ( lc->cmd.ea != BADADDR )
        append_memory(req, &lc->cmd, sizeof(lc->cmd));
    }
  }
  return process_long(req);
}
Exemple #3
0
/*ARGSUSED*/
error_t
cvt_to_metal(menu_t *mp, char *osroot, char *menu_root)
{
	const char *fcn = "cvt_to_metal()";

	line_t *lp;
	entry_t *ent;
	size_t len, zfslen;

	char *delim = ",";
	char *newstr;
	char *osdev;

	char *title = NULL;
	char *findroot = NULL;
	char *bootfs = NULL;
	char *kernel = NULL;
	char *module = NULL;

	char *barchive_path = DIRECT_BOOT_ARCHIVE;
	char *kern_path = NULL;

	int curdef, newdef;
	int emit_bflag = 1;
	int ret = BAM_ERROR;

	assert(osroot);

	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osroot, ""));

	/*
	 * First just check to verify osroot is a sane directory.
	 */
	if ((osdev = get_special(osroot)) == NULL) {
		bam_error(CANT_FIND_SPECIAL, osroot);
		return (BAM_ERROR);
	}

	free(osdev);

	/*
	 * Found the GRUB signature on the target partitions, so now get the
	 * default GRUB boot entry number from the menu.lst file
	 */
	curdef = atoi(mp->curdefault->arg);

	/* look for the first line of the matching boot entry */
	for (ent = mp->entries; ((ent != NULL) && (ent->entryNum != curdef));
	    ent = ent->next)
		;

	/* couldn't find it, so error out */
	if (ent == NULL) {
		bam_error(CANT_FIND_DEFAULT, curdef);
		goto abort;
	}

	/*
	 * Now process the entry itself.
	 */
	for (lp = ent->start; lp != NULL; lp = lp->next) {
		/*
		 * Process important lines from menu.lst boot entry.
		 */
		if (lp->flags == BAM_TITLE) {
			title = alloca(strlen(lp->arg) + 1);
			(void) strcpy(title, lp->arg);
		} else if (strcmp(lp->cmd, "findroot") == 0) {
			findroot = alloca(strlen(lp->arg) + 1);
			(void) strcpy(findroot, lp->arg);
		} else if (strcmp(lp->cmd, "bootfs") == 0) {
			bootfs = alloca(strlen(lp->arg) + 1);
			(void) strcpy(bootfs, lp->arg);
		} else if (strcmp(lp->cmd, menu_cmds[MODULE_DOLLAR_CMD]) == 0) {
			if (strstr(lp->arg, "boot_archive") == NULL) {
				module = alloca(strlen(lp->arg) + 1);
				(void) strcpy(module, lp->arg);
				cvt_hyper_module(module, &kern_path);
			} else {
				barchive_path = alloca(strlen(lp->arg) + 1);
				(void) strcpy(barchive_path, lp->arg);
			}
		} else if ((strcmp(lp->cmd,
		    menu_cmds[KERNEL_DOLLAR_CMD]) == 0) &&
		    (cvt_hyper_kernel(lp->arg) < 0)) {
			ret = BAM_NOCHANGE;
			goto abort;
		}

		if (lp == ent->end)
			break;
	}

	/*
	 * If findroot, module or kern_path are NULL, the boot entry is
	 * malformed.
	 */
	if (findroot == NULL) {
		bam_error(FINDROOT_NOT_FOUND, curdef);
		goto abort;
	}

	if (module == NULL) {
		bam_error(MODULE_NOT_PARSEABLE, curdef);
		goto abort;
	}

	if (kern_path == NULL) {
		bam_error(KERNEL_NOT_FOUND, curdef);
		goto abort;
	}

	/*
	 * Assemble new kernel and module arguments from parsed values.
	 *
	 * First, change the kernel directory from the hypervisor version to
	 * that needed for a metal kernel.
	 */
	newstr = modify_path(kern_path, HYPER_KERNEL_DIR, METAL_KERNEL_DIR);
	free(kern_path);
	kern_path = newstr;

	/* allocate initial space for the kernel path */
	len = strlen(kern_path) + 1;
	zfslen = (zfs_boot ? (WHITESPC(1) + strlen(ZFS_BOOT)) : 0);

	if ((kernel = malloc(len + zfslen)) == NULL) {
		free(kern_path);
		bam_error(NO_MEM, len + zfslen);
		bam_exit(1);
	}

	(void) snprintf(kernel, len, "%s", kern_path);
	free(kern_path);

	if (zfs_boot) {
		char *zfsstr = alloca(zfslen + 1);

		(void) snprintf(zfsstr, zfslen + 1, " %s", ZFS_BOOT);
		(void) strcat(kernel, zfsstr);
		emit_bflag = 0;
	}

	/*
	 * Process the bootenv.rc file to look for boot options that would be
	 * the same as what the hypervisor had manually set, as we need not set
	 * those explicitly.
	 *
	 * If there's no bootenv.rc, it's not an issue.
	 */
	parse_bootenvrc(osroot);

	/*
	 * Don't emit a console setting if it's the same as what would be
	 * set by bootenv.rc.
	 */
	if ((console_dev != NULL) && (bootenv_rc_console == NULL ||
	    (strcmp(console_dev, bootenv_rc_console) != 0))) {
		if (emit_bflag) {
			newstr = append_str(kernel, BFLAG, " ");
			free(kernel);
			kernel = append_str(newstr, "console=", " ");
			free(newstr);
			newstr = append_str(kernel, console_dev, "");
			free(kernel);
			kernel = newstr;
			emit_bflag = 0;
		} else {
			newstr = append_str(kernel, "console=", ",");
			free(kernel);
			kernel = append_str(newstr, console_dev, "");
			free(newstr);
		}
	}

	/*
	 * We have to do some strange processing here because the hypervisor's
	 * serial ports default to "9600,8,n,1,-" if "comX=auto" is specified,
	 * or to "auto" if nothing is specified.
	 *
	 * This could result in a serial mode setting string being added when
	 * it would otherwise not be needed, but it's better to play it safe.
	 */
	if (emit_bflag) {
		newstr = append_str(kernel, BFLAG, " ");
		free(kernel);
		kernel = newstr;
		delim = " ";
		emit_bflag = 0;
	}

	if ((serial_config[0] != NULL) && (bootenv_rc_serial[0] == NULL ||
	    (strcmp(serial_config[0], bootenv_rc_serial[0]) != 0))) {
		newstr = append_str(kernel, "ttya-mode='", delim);
		free(kernel);

		/*
		 * Pass the serial configuration as the delimiter to
		 * append_str() as it will be inserted between the current
		 * string and the string we're appending, in this case the
		 * closing single quote.
		 */
		kernel = append_str(newstr, "'", serial_config[0]);
		free(newstr);
		delim = ",";
	}

	if ((serial_config[1] != NULL) && (bootenv_rc_serial[1] == NULL ||
	    (strcmp(serial_config[1], bootenv_rc_serial[1]) != 0))) {
		newstr = append_str(kernel, "ttyb-mode='", delim);
		free(kernel);

		/*
		 * Pass the serial configuration as the delimiter to
		 * append_str() as it will be inserted between the current
		 * string and the string we're appending, in this case the
		 * closing single quote.
		 */
		kernel = append_str(newstr, "'", serial_config[1]);
		free(newstr);
		delim = ",";
	}

	/* shut off warning messages from the entry line parser */
	if (ent->flags & BAM_ENTRY_BOOTADM)
		ent->flags &= ~BAM_ENTRY_BOOTADM;

	BAM_DPRINTF((D_CVT_CMD_KERN_DOLLAR, fcn, kernel));
	BAM_DPRINTF((D_CVT_CMD_MOD_DOLLAR, fcn, module));

	if ((newdef = add_boot_entry(mp, title, findroot, kernel, NULL,
	    barchive_path, bootfs)) == BAM_ERROR) {
		free(kernel);
		return (newdef);
	}

	/*
	 * Now try to delete the current default entry from the menu and add
	 * the new hypervisor entry with the parameters we've setup.
	 */
	if (delete_boot_entry(mp, curdef, DBE_QUIET) == BAM_SUCCESS)
		newdef--;
	else
		bam_print(NEW_BOOT_ENTRY, title);

	free(kernel);

	/*
	 * If we successfully created the new entry, set the default boot
	 * entry to that entry and let the caller know the new menu should
	 * be written out.
	 */
	return (set_global(mp, menu_cmds[DEFAULT_CMD], newdef));

abort:
	if (ret != BAM_NOCHANGE)
		bam_error(METAL_ABORT, osroot);

	return (ret);
}
Exemple #4
0
int build_args(const char *str, int *argc, char ***argv)
{
    bool quote, backslash, endword;
    const char *p;
    bool empty;

    quote = false;
    empty = true;
    backslash = false;
    endword = true;
    *argc = 0;
    *argv = NULL;

    for (p = str; *p != '\0'; ++p) {
        if (*p == '\\') {
            if (backslash) {
                if (endword) {
                    new_arg(argc, argv);
                    endword = false;
                }
                append_str('\\', &(*argv)[*argc - 1]);
                empty = false;
                backslash = false;
            } else {
                backslash = true;
            }
        } else if (*p == '\"') {
            if (backslash) {
                if (endword) {
                    new_arg(argc, argv);
                    endword = false;
                }
                append_str('\"', &(*argv)[*argc - 1]);
                empty = false;
                backslash = false;
            } else {
                endword = true;

                if (quote) {
                    if (empty) {
                        new_arg(argc, argv);
                        append_str('\0', &(*argv)[*argc - 1]);
                    }

                    quote = false;
                } else {
                    quote = true;
                    empty = true;
                }
            }
        } else if (isspace(*p)) {
            if (backslash) {
                if (endword) {
                    new_arg(argc, argv);
                    endword = false;
                }

                append_str(*p, &(*argv)[*argc - 1]);
                empty = false;
                backslash = false;
            } else {
                if (quote) {
                    if (endword) {
                        new_arg(argc, argv);
                        endword = false;
                    }
                    append_str(*p, &(*argv)[*argc - 1]);
                    empty = false;
                } else {
                    endword = true;
                }
            }
        } else {
            if (endword) {
                new_arg(argc, argv);
                endword = false;
            }
            append_str(*p, &(*argv)[*argc - 1]);
            empty = false;
        }
    }

    return 0;
}
Exemple #5
0
/* Build a local request based on a previous request; main
 * customers of this function are local ACK and local CANCEL
 */
char *build_local(struct cell *Trans,unsigned int branch,
	unsigned int *len, char *method, int method_len, str *to
#ifdef CANCEL_REASON_SUPPORT
	, struct cancel_reason* reason
#endif /* CANCEL_REASON_SUPPORT */
	)
{
	char                *cancel_buf, *p, *via;
	unsigned int         via_len;
	struct hdr_field    *hdr;
	char branch_buf[MAX_BRANCH_PARAM_LEN];
	int branch_len;
	str branch_str;
	str via_id;
	struct hostport hp;
#ifdef CANCEL_REASON_SUPPORT
	int reason_len, code_len;
	struct hdr_field *reas1, *reas_last;
#endif /* CANCEL_REASON_SUPPORT */

	/* init */
	via_id.s=0;
	via_id.len=0;

	/* method, separators, version: "CANCEL sip:[email protected] SIP/2.0" */
	*len=SIP_VERSION_LEN + method_len + 2 /* spaces */ + CRLF_LEN;
	*len+=Trans->uac[branch].uri.len;

	/*via*/
	if (!t_calc_branch(Trans,  branch,
		branch_buf, &branch_len ))
		goto error;
	branch_str.s=branch_buf;
	branch_str.len=branch_len;
	set_hostport(&hp, (is_local(Trans))?0:(Trans->uas.request));
#ifdef USE_TCP
	if (!is_local(Trans) && ((Trans->uas.request->rcv.proto==PROTO_TCP)
#ifdef USE_TLS
				|| (Trans->uas.request->rcv.proto==PROTO_TLS)
#endif /* USE_TLS */
		)){
		if ((via_id.s=id_builder(Trans->uas.request,
									(unsigned int*)&via_id.len))==0){
			LM_ERR("id builder failed\n");
			/* try to continue without id */
		}
	}
#endif /* USE_TCP */
	via=via_builder(&via_len, NULL, &Trans->uac[branch].request.dst,
		&branch_str, via_id.s?&via_id:0 , &hp );

	/* via_id.s not needed anylonger => free it */
	if (via_id.s) {
		pkg_free(via_id.s);
		via_id.s=0;
		via_id.len=0;
	}

	if (!via) {
		LM_ERR("no via header got from builder\n");
		goto error;
	}
	*len+= via_len;
	/*headers*/
	*len+=Trans->from.len+Trans->callid.len+to->len+
		+Trans->cseq_n.len+1+method_len+CRLF_LEN+MAXFWD_HEADER_LEN;


	/* copy'n'paste Route headers */
	if (!is_local(Trans)) {
		for ( hdr=Trans->uas.request->headers ; hdr ; hdr=hdr->next )
			if (hdr->type==HDR_ROUTE_T)
				*len+=hdr->len;
	}

	/* User Agent */
	if (server_signature) {
		*len += user_agent_hdr.len + CRLF_LEN;
	}
	/* Content Length, EoM */
	*len+=CONTENT_LENGTH_LEN+1 + CRLF_LEN;
#ifdef CANCEL_REASON_SUPPORT
	reason_len = 0;
	reas1 = 0;
	reas_last = 0;
	/* compute reason size (if no reason or disabled => reason_len == 0)*/
	if (reason && reason->cause != CANCEL_REAS_UNKNOWN){
		if (likely(reason->cause > 0 &&
					cfg_get(tm, tm_cfg, local_cancel_reason))){
			/* Reason: SIP;cause=<reason->cause>[;text=<reason->u.text.s>] */
			reason_len = REASON_PREFIX_LEN + USHORT2SBUF_MAX_LEN +
				(reason->u.text.s?
					REASON_TEXT_LEN + 1 + reason->u.text.len + 1 : 0) +
				CRLF_LEN;
		} else if (likely(reason->cause == CANCEL_REAS_PACKED_HDRS &&
					!(Trans->flags & T_NO_E2E_CANCEL_REASON))) {
			reason_len = reason->u.packed_hdrs.len;
		} else if (reason->cause == CANCEL_REAS_RCVD_CANCEL &&
					reason->u.e2e_cancel &&
					!(Trans->flags & T_NO_E2E_CANCEL_REASON)) {
			/* parse the entire cancel, to get all the Reason headers */
			if(parse_headers(reason->u.e2e_cancel, HDR_EOH_F, 0)<0) {
				LM_WARN("failed to parse headers\n");
			}
			for(hdr=get_hdr(reason->u.e2e_cancel, HDR_REASON_T), reas1=hdr;
					hdr; hdr=next_sibling_hdr(hdr)) {
				/* hdr->len includes CRLF */
				reason_len += hdr->len;
				reas_last=hdr;
			}
		} else if (unlikely(reason->cause < CANCEL_REAS_MIN))
			LM_BUG("unhandled reason cause %d\n", reason->cause);
	}
	*len+= reason_len;
#endif /* CANCEL_REASON_SUPPORT */
	*len+= CRLF_LEN; /* end of msg. */

	cancel_buf=shm_malloc( *len+1 );
	if (!cancel_buf) {
		LM_ERR("cannot allocate memory\n");
		goto error01;
	}
	p = cancel_buf;

	append_str( p, method, method_len );
	append_str( p, " ", 1 );
	append_str( p, Trans->uac[branch].uri.s, Trans->uac[branch].uri.len);
	append_str( p, " " SIP_VERSION CRLF, 1+SIP_VERSION_LEN+CRLF_LEN );

	/* insert our via */
	append_str(p,via,via_len);

	/*other headers*/
	append_str( p, Trans->from.s, Trans->from.len );
	append_str( p, Trans->callid.s, Trans->callid.len );
	append_str( p, to->s, to->len );

	append_str( p, Trans->cseq_n.s, Trans->cseq_n.len );
	append_str( p, " ", 1 );
	append_str( p, method, method_len );
	append_str( p, CRLF, CRLF_LEN );
	append_str( p, MAXFWD_HEADER, MAXFWD_HEADER_LEN );

	if (!is_local(Trans))  {
		for ( hdr=Trans->uas.request->headers ; hdr ; hdr=hdr->next )
			if(hdr->type==HDR_ROUTE_T) {
				append_str(p, hdr->name.s, hdr->len );
			}
	}

	/* User Agent header */
	if (server_signature) {
		append_str(p, user_agent_hdr.s, user_agent_hdr.len );
		append_str(p, CRLF, CRLF_LEN );
	}
	/* Content Length */
	append_str(p, CONTENT_LENGTH "0" CRLF, CONTENT_LENGTH_LEN + 1 + CRLF_LEN);
#ifdef CANCEL_REASON_SUPPORT
	/* add reason if needed */
	if (reason_len) {
		if (likely(reason->cause > 0)) {
			append_str(p, REASON_PREFIX, REASON_PREFIX_LEN);
			code_len=ushort2sbuf(reason->cause, p,
									*len-(int)(p-cancel_buf));
			if (unlikely(code_len==0))
				LM_BUG("not enough space to write reason code");
			p+=code_len;
			if (reason->u.text.s){
				append_str(p, REASON_TEXT, REASON_TEXT_LEN);
				*p='"'; p++;
				append_str(p, reason->u.text.s, reason->u.text.len);
				*p='"'; p++;
			}
			append_str(p, CRLF, CRLF_LEN);
		} else if (likely(reason->cause == CANCEL_REAS_PACKED_HDRS)) {
			append_str(p, reason->u.packed_hdrs.s, reason->u.packed_hdrs.len);
		} else if (reason->cause == CANCEL_REAS_RCVD_CANCEL) {
			for(hdr=reas1; hdr; hdr=next_sibling_hdr(hdr)) {
				/* hdr->len includes CRLF */
				append_str(p, hdr->name.s, hdr->len);
				if (likely(hdr==reas_last))
					break;
			}
		}
	}
#endif /* CANCEL_REASON_SUPPORT */
	append_str(p, CRLF, CRLF_LEN); /* msg. end */
	*p=0;

	pkg_free(via);
	return cancel_buf;
error01:
	pkg_free(via);
error:
	return NULL;
}
Exemple #6
0
/*
 * The function creates an ACK to 200 OK. Route set will be created
 * and parsed and the dst parameter will contain the destination to which
 * the request should be send. The function is used by tm when it
 * generates local ACK to 200 OK (on behalf of applications using uac)
 */
char *build_dlg_ack(struct sip_msg* rpl, struct cell *Trans,
					unsigned int branch, str *hdrs, str *body,
					unsigned int *len, struct dest_info* dst)
{
	char *req_buf, *p, *via;
	unsigned int via_len;
	char branch_buf[MAX_BRANCH_PARAM_LEN];
	int branch_len;
	str branch_str;
	struct hostport hp;
	struct rte* list;
	str contact, ruri, *cont;
	str next_hop;
	str body_len;
	str _to, *to = &_to;
#ifdef USE_DNS_FAILOVER
	struct dns_srv_handle dns_h;
#endif
#ifdef WITH_AS_SUPPORT
	/* With AS support, TM allows for external modules to generate building of
	 * the ACK; in this case, the ACK's retransmission buffer is built once
	 * and kept in memory (to help when retransmitted 2xx are received and ACK
	 * must be resent).
	 * Allocation of the string raw buffer that holds the ACK is piggy-backed
	 * with allocation of the retransmission buffer (since both have the same
	 * life-cycle): both the string buffer and retransm. buffer are placed
	 * into the same allocated chunk of memory (retr. buffer first, string
	 * buffer follows).In this case, the 'len' param is used as in-out
	 * parameter: 'in' to give the extra space needed by the retr. buffer,
	 * 'out' to return the lenght of the allocated string buffer.
	 */
	unsigned offset = *len;
#endif

	if (parse_headers(rpl, HDR_EOH_F, 0) == -1 || !rpl->to) {
		LM_ERR("Error while parsing headers.\n");
		return 0;
	} else {
		_to.s = rpl->to->name.s;
		_to.len = rpl->to->len;
	}

	if (get_contact_uri(rpl, &contact) < 0) {
		return 0;
	}

	if (eval_uac_routing(rpl, &Trans->uac[branch].request, &contact,
			&list, &ruri, &next_hop) < 0) {
		LM_ERR("failed to evaluate routing elements.\n");
		return 0;
	}
	LM_DBG("ACK RURI: `%.*s', NH: `%.*s'.\n", STR_FMT(&ruri),
			STR_FMT(&next_hop));

	if ((contact.s != ruri.s) || (contact.len != ruri.len)) {
		/* contact != ruri means that the next
		 * hop is a strict router, cont will be non-zero
		 * and print_routeset will append it at the end
		 * of the route set
		 */
		cont = &contact;
	} else {
		/* Next hop is a loose router, nothing to append */
		cont = 0;
	}

	/* method, separators, version: "ACK sip:[email protected] SIP/2.0" */
	*len = SIP_VERSION_LEN + ACK_LEN + 2 /* spaces */ + CRLF_LEN;
	*len += ruri.len;

	/* dst */
	switch(cfg_get(tm, tm_cfg, local_ack_mode)){
		case 1:
			/* send the local 200 ack to the same dst as the corresp. invite*/
			*dst=Trans->uac[branch].request.dst;
			break;
		case 2:
			/* send the local 200 ack to the same dst as the 200 reply source*/
			init_dst_from_rcv(dst, &rpl->rcv);
			dst->send_flags=rpl->fwd_send_flags;
			break;
		case 0:
		default:
			/* rfc conformant behaviour: use the next_hop determined from the
			 * contact and the route set */
#ifdef USE_DNS_FAILOVER
		if (cfg_get(core, core_cfg, use_dns_failover)){
			dns_srv_handle_init(&dns_h);
			if ((uri2dst(&dns_h , dst, rpl, &next_hop, PROTO_NONE)==0) ||
					(dst->send_sock==0)){
				dns_srv_handle_put(&dns_h);
				LM_ERR("no socket found\n");
				goto error;
			}
			dns_srv_handle_put(&dns_h); /* not needed any more */
		}else{
			if ((uri2dst(0 , dst, rpl, &next_hop, PROTO_NONE)==0) ||
					(dst->send_sock==0)){
				LM_ERR("no socket found\n");
				goto error;
			}
		}
#else /* USE_DNS_FAILOVER */
		if ( (uri2dst( dst, rpl, &next_hop, PROTO_NONE)==0) ||
				(dst->send_sock==0)){
			LM_ERR("no socket found\n");
			goto error;
		}
#endif /* USE_DNS_FAILOVER */
		break;
	}

	/* via */
	if (!t_calc_branch(Trans,  branch, branch_buf, &branch_len)) goto error;
	branch_str.s = branch_buf;
	branch_str.len = branch_len;
	set_hostport(&hp, 0);
	via = via_builder(&via_len, NULL, dst, &branch_str, 0, &hp);
	if (!via) {
		LM_ERR("No via header got from builder\n");
		goto error;
	}
	*len+= via_len;

	/* headers */
	*len += Trans->from.len + Trans->callid.len + to->len + Trans->cseq_n.len + 1 + ACK_LEN + CRLF_LEN;

	/* copy'n'paste Route headers */

	*len += calc_routeset_len(list, cont);

	/* User Agent */
	if (server_signature) *len += user_agent_hdr.len + CRLF_LEN;
	/* extra headers */
	if (hdrs)
		*len += hdrs->len;
	/* body */
	if (body) {
		body_len.s = int2str(body->len, &body_len.len);
		*len += body->len;
	} else {
		body_len.len = 0;
		body_len.s = NULL; /*4gcc*/
		*len += 1; /* for the (Cont-Len:) `0' */
	}
	/* Content Length, EoM */
	*len += CONTENT_LENGTH_LEN + body_len.len + CRLF_LEN + CRLF_LEN;

#if WITH_AS_SUPPORT
	req_buf = shm_malloc(offset + *len + 1);
	req_buf += offset;
#else
	req_buf = shm_malloc(*len + 1);
#endif
	if (!req_buf) {
		LM_ERR("Cannot allocate memory (%u+1)\n", *len);
		goto error01;
	}
	p = req_buf;

	append_str( p, ACK, ACK_LEN );
	append_str( p, " ", 1 );
	append_str(p, ruri.s, ruri.len);
	append_str( p, " " SIP_VERSION CRLF, 1 + SIP_VERSION_LEN + CRLF_LEN);

	/* insert our via */
	append_str(p, via, via_len);

	/*other headers*/
	append_str(p, Trans->from.s, Trans->from.len);
	append_str(p, Trans->callid.s, Trans->callid.len);
	append_str(p, to->s, to->len);

	append_str(p, Trans->cseq_n.s, Trans->cseq_n.len);
	append_str( p, " ", 1 );
	append_str( p, ACK, ACK_LEN);
	append_str(p, CRLF, CRLF_LEN);

	/* Routeset */
	p = print_rs(p, list, cont);

	/* User Agent header */
	if (server_signature) {
		append_str(p, user_agent_hdr.s, user_agent_hdr.len);
		append_str(p, CRLF, CRLF_LEN);
	}

	/* extra headers */
	if (hdrs)
		append_str(p, hdrs->s, hdrs->len);

	/* Content Length, EoH, (body) */
	if (body) {
		append_str(p, CONTENT_LENGTH, CONTENT_LENGTH_LEN);
		append_str(p, body_len.s, body_len.len);
		append_str(p, /*end crr. header*/CRLF /*EoH*/CRLF, CRLF_LEN +
				CRLF_LEN);
		append_str(p, body->s, body->len);
	} else {
		append_str(p, CONTENT_LENGTH "0" CRLF CRLF,
				CONTENT_LENGTH_LEN + 1 + CRLF_LEN + CRLF_LEN);
	}

	/* EoM */
	*p = 0;

	pkg_free(via);
	free_rte_list(list);
	return req_buf;

error01:
	pkg_free(via);
error:
	free_rte_list(list);
	return 0;
}
Exemple #7
0
/*
 ** zCode is a string that is the action associated with a rule.  Expand
 ** the symbols in this string so that they refer to elements of the parser
 ** stack.
 ** (Return a new string stored in space obtained from malloc?)
 */
PRIVATE void translate_code(struct lmno *lmnop, struct rule *rp)
{
	char *cp, *xp;
	bool lhsused = false;	// True if the LHS element has been used
	char used[MAXRHS];		// True for each RHS element which is used
	
	for(int i = 0; i < rp->nrhs; i++)
		used[i] = 0;
	
	append_str(0,0,0,0);
	for(cp=rp->code; *cp; cp++)
	{
		if(isalpha(*cp) && (cp==rp->code || (!isalnum(cp[-1]) && cp[-1]!='_')))
		{
			char saved;
			for(xp= &cp[1]; isalnum(*xp) || *xp=='_'; xp++) { } // find ident
			saved = *xp;
			*xp = 0;
			if(rp->lhsalias && strcmp(cp,rp->lhsalias)==0)
			{
				append_str("yygotominor.yy%d",0,rp->lhs->dtnum,0);
				cp = xp;
				lhsused = true;
			}
			else
			{
				for(int i = 0; i < rp->nrhs; i++)
				{
					if(rp->rhsalias[i] && strcmp(cp,rp->rhsalias[i])==0)
					{
						// If the argument is "@X" then substituted
						// the token number of X, not the value of X
						if(cp!=rp->code && cp[-1]=='@')
						{
							append_str("yymsp[%d].major",-1,i-rp->nrhs+1,0);
						}
						else
						{
							append_str("yymsp[%d].minor.yy%d",0,
									   i-rp->nrhs+1,rp->rhs[i]->dtnum);
						}
						cp = xp;
						used[i] = 1;
						break;
					}
				}
			}
			*xp = saved;
		}
		append_str(cp, 1, 0, 0);
	} // End loop
	
	// Check to make sure the LHS has been used
	if(rp->lhsalias && !lhsused)
	{
		ErrorMsg(lmnop->filename,rp->ruleline,
				 "Label \"%s\" for \"%s(%s)\" is never used.",
				 rp->lhsalias,rp->lhs->name,rp->lhsalias);
		lmnop->errorcnt++;
	}
	
	// Generate destructor code for RHS symbols which are not used in the
	// reduction code
	for(int i = 0; i < rp->nrhs; i++)
	{
		if(rp->rhsalias[i] && !used[i])
		{
			ErrorMsg(lmnop->filename, rp->ruleline,
					 "Label %s for \"%s(%s)\" is never used.",
					 rp->rhsalias[i], rp->rhs[i]->name, rp->rhsalias[i]);
			lmnop->errorcnt++;
		}
		else if(rp->rhsalias[i]==0)
		{
			if(has_destructor(rp->rhs[i],lmnop))
			{
				append_str("	destructor(%d, &yymsp[%d].minor);\n", 0,
						   rp->rhs[i]->index, i - rp->nrhs + 1);
			}
			else
			{
				/* No destructor defined for this term */
			}
		}
	}
	cp = append_str(0,0,0,0);
	rp->code = Strsafe(cp);
}
Exemple #8
0
static void translateinfstringex_test(void)
{
    HINF hinf;
    HRESULT hr;
    char buffer[MAX_PATH];
    DWORD size = MAX_PATH;

    hr = pOpenINFEngine(inf_file, NULL, 0, &hinf, NULL);
    if (hr == E_UNEXPECTED)
    {
        win_skip("Skipping tests on win9x because of brokenness\n");
        return;
    }

    create_inf_file();
    
    /* need to see if there are any flags */

    /* try a NULL filename */
    hr = pOpenINFEngine(NULL, "Options.NTx86", 0, &hinf, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try an empty filename */
    hr = pOpenINFEngine("", "Options.NTx86", 0, &hinf, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) /* NT+ */ ||
       hr == HRESULT_FROM_WIN32(E_UNEXPECTED) /* 9x */,
        "Expected HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND or E_UNEXPECTED), got %08x\n", hr);

    /* try a NULL hinf */
    hr = pOpenINFEngine(inf_file, "Options.NTx86", 0, NULL, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* open the INF without the Install section specified */
    hr = pOpenINFEngine(inf_file, NULL, 0, &hinf, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    /* try a NULL hinf */
    hr = pTranslateInfStringEx(NULL, inf_file, "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try a NULL filename */
    hr = pTranslateInfStringEx(hinf, NULL, "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try an empty filename */
    memset(buffer, 'a', 25);
    buffer[24] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, "", "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    todo_wine
    {
        ok(!strcmp(buffer, TEST_STRING2), "Expected %s, got %s\n", TEST_STRING2, buffer);
        ok(size == 25, "Expected size 25, got %d\n", size);
    }

    /* try a NULL translate section */
    hr = pTranslateInfStringEx(hinf, inf_file, NULL, "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try an empty translate section */
    hr = pTranslateInfStringEx(hinf, inf_file, "", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == SPAPI_E_LINE_NOT_FOUND, "Expected SPAPI_E_LINE_NOT_FOUND, got %08x\n", hr);

    /* try a NULL translate key */
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", NULL,
                              buffer, size, &size, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* try an empty translate key */
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "",
                              buffer, size, &size, NULL);
    ok(hr == SPAPI_E_LINE_NOT_FOUND, "Expected SPAPI_E_LINE_NOT_FOUND, got %08x\n", hr);

    /* successfully translate the string */
    memset(buffer, 'a', 25);
    buffer[24] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    todo_wine
    {
        ok(!strcmp(buffer, TEST_STRING2), "Expected %s, got %s\n", TEST_STRING2, buffer);
        ok(size == 25, "Expected size 25, got %d\n", size);
    }

    /* try a NULL hinf */
    hr = pCloseINFEngine(NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %08x\n", hr);

    /* successfully close the hinf */
    hr = pCloseINFEngine(hinf);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    /* open the inf with the install section */
    hr = pOpenINFEngine(inf_file, "section", 0, &hinf, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    /* translate the string with the install section specified */
    memset(buffer, 'a', APP_PATH_LEN);
    buffer[APP_PATH_LEN - 1] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "InstallDir",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(!strcmp(buffer, APP_PATH), "Expected %s, got %s\n", APP_PATH, buffer);
    ok(size == APP_PATH_LEN, "Expected size %d, got %d\n", APP_PATH_LEN, size);

    /* Single quote test (Note size includes null on return from call) */
    memset(buffer, 'a', APP_PATH_LEN);
    buffer[APP_PATH_LEN - 1] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "Result1",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(!lstrcmpiA(buffer, PROG_FILES_ROOT),
           "Expected %s, got %s\n", PROG_FILES_ROOT, buffer);
    ok(size == strlen(PROG_FILES_ROOT)+1, "Expected size %d, got %d\n",
           lstrlenA(PROG_FILES_ROOT)+1, size);

    memset(buffer, 'a', APP_PATH_LEN);
    buffer[APP_PATH_LEN - 1] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "Result2",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(!lstrcmpiA(buffer, PROG_FILES_ROOT),
           "Expected %s, got %s\n", PROG_FILES_ROOT, buffer);
    ok(size == strlen(PROG_FILES_ROOT)+1, "Expected size %d, got %d\n",
           lstrlenA(PROG_FILES_ROOT)+1, size);

    {
        char drive[MAX_PATH];
        lstrcpyA(drive, PROG_FILES_ROOT);
        drive[3] = 0x00; /* Just keep the system drive plus '\' */

        memset(buffer, 'a', APP_PATH_LEN);
        buffer[APP_PATH_LEN - 1] = '\0';
        size = MAX_PATH;
        hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "Result3",
                                  buffer, size, &size, NULL);
        ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
        ok(!lstrcmpiA(buffer, drive),
               "Expected %s, got %s\n", drive, buffer);
        ok(size == strlen(drive)+1, "Expected size %d, got %d\n",
               lstrlenA(drive)+1, size);
    }

    /* close the INF again */
    hr = pCloseINFEngine(hinf);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    DeleteFileA(inf_file);

    /* Create another .inf file which is just here to trigger a wine bug */
    {
        char data[1024];
        char *ptr = data;
        DWORD dwNumberOfBytesWritten;
        HANDLE hf = CreateFileA(inf_file, GENERIC_WRITE, 0, NULL,
                           CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

        append_str(&ptr, "[Version]\n");
        append_str(&ptr, "Signature=\"$Chicago$\"\n");
        append_str(&ptr, "[section]\n");
        append_str(&ptr, "NotACustomDestination=Version\n");
        append_str(&ptr, "CustomDestination=CustInstDestSection\n");
        append_str(&ptr, "[CustInstDestSection]\n");
        append_str(&ptr, "49010=DestA,1\n");
        append_str(&ptr, "49020=DestB\n");
        append_str(&ptr, "49030=DestC\n");
        append_str(&ptr, "49040=DestD\n");
        append_str(&ptr, "[Options.NTx86]\n");
        append_str(&ptr, "Result2=%%49030%%\n");
        append_str(&ptr, "[DestA]\n");
        append_str(&ptr, "HKLM,\"Software\\Garbage\",\"ProgramFilesDir\",,'%%24%%'\n");
        /* The point of this test is to have HKCU just before the quoted HKLM */
        append_str(&ptr, "[DestB]\n");
        append_str(&ptr, "HKCU,\"Software\\Garbage\",\"ProgramFilesDir\",,'%%24%%'\n");
        append_str(&ptr, "[DestC]\n");
        append_str(&ptr, "'HKLM','Software\\Microsoft\\Windows\\CurrentVersion',");
        append_str(&ptr, "'ProgramFilesDir',,\"%%24%%\"\n");
        append_str(&ptr, "[DestD]\n");
        append_str(&ptr, "HKLM,\"Software\\Garbage\",\"ProgramFilesDir\",,'%%24%%'\n");

        WriteFile(hf, data, ptr - data, &dwNumberOfBytesWritten, NULL);
        CloseHandle(hf);
    }

    /* open the inf with the install section */
    hr = pOpenINFEngine(inf_file, "section", 0, &hinf, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    /* Single quote test (Note size includes null on return from call) */
    memset(buffer, 'a', APP_PATH_LEN);
    buffer[APP_PATH_LEN - 1] = '\0';
    size = MAX_PATH;
    hr = pTranslateInfStringEx(hinf, inf_file, "Options.NTx86", "Result2",
                              buffer, size, &size, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);
    ok(!lstrcmpiA(buffer, PROG_FILES_ROOT),
           "Expected %s, got %s\n", PROG_FILES_ROOT, buffer);
    ok(size == strlen(PROG_FILES_ROOT)+1, "Expected size %d, got %d\n",
           lstrlenA(PROG_FILES_ROOT)+1, size);

    /* close the INF again */
    hr = pCloseINFEngine(hinf);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    DeleteFileA(inf_file);
}
Exemple #9
0
int send_sms_as_sip( struct incame_sms *sms )
{
	str  sip_addr;
	str  sip_body;
	str  sip_from;
	int  is_pattern;
	int  k;
	char *p;

	/* first we have to parse the body to try to get out
	   the sip destination address;
	   The sms body can to be in the following two formats:
	   1. The entire or part of the sent header still exists - we will
	      pars it and consider the start of the sip message the first
	      character that doesn't match the header!
	   2. The sms body is totally different of the send sms -> search for a
	      sip address inside; everything before it is ignored, only the
	      part following the address being send as sip
	*/
	sip_addr.len = 0;
	sip_body.len = 0;
	p = sms->ascii;

	/* is our logo (or a part of it) still there? */
	if (*p==SMS_HDR_BF_ADDR[0]) {
		is_pattern = 1;
		/* try to match SMS_HDR_BF_ADDR */
		k=0;
		while( is_pattern && p<sms->ascii+sms->userdatalength
		&& k<SMS_HDR_BF_ADDR_LEN)
			if (*(p++)!=SMS_HDR_BF_ADDR[k++])
				is_pattern = 0;
		if (!is_pattern) {
			/* first header part is broken -> let's give it a chance
			   and parse for the first word delimiter */
			while(p<sms->ascii+sms->userdatalength && no_sip_addr_begin(*p))
				p++;
			p++;
			if (p+9>=sms->ascii+sms->userdatalength) {
				LM_ERR("unable to find sip_address start in sms body [%s]!\n",
						sms->ascii);
				goto error;
			}
			
		}
		/* lets get the address */
		if (p[0]!='s' || p[1]!='i' || p[2]!='p' || p[3]!=':') {
			LM_ERR("wrong sip address format in sms body [%s]!\n",sms->ascii);
			goto error;
		}
		sip_addr.s = p;
		/* goes to the end of the address */
		while(p<sms->ascii+sms->userdatalength && is_in_sip_addr(*p) )
			p++;
		if (p>=sms->ascii+sms->userdatalength) {
			LM_ERR("failed to find sip address end in sms body [%s]!\n",
					sms->ascii);
		}
		sip_addr.len = p-sip_addr.s;
		LM_DBG("sip address found [%.*s]\n",
			sip_addr.len,sip_addr.s);
		/* try to match SMS_HDR_AF_ADDR */
		k=0;
		while( is_pattern && p<sms->ascii+sms->userdatalength
		&& k<SMS_HDR_AF_ADDR_LEN)
			if (*(p++)!=SMS_HDR_AF_ADDR[k++])
				is_pattern = 0;
	} else {
		/* no trace of the pattern sent along with the orig sms*/
		do {
			if ((p[0]=='s'||p[0]=='S') && (p[1]=='i'||p[1]=='I')
			&& (p[2]=='p'||p[2]=='P') && p[3]==':') {
				/* we got the address beginning */
				sip_addr.s = p;
				/* goes to the end of the address */
				while(p<sms->ascii+sms->userdatalength && is_in_sip_addr(*p) )
					p++;
				if (p==sms->ascii+sms->userdatalength) {
					LM_ERR("failed to find sip address end in sms body [%s]!\n",
							sms->ascii);
					goto error;
				}
				sip_addr.len = p-sip_addr.s;
			} else {
				/* parse to the next word */
				/*LM_DBG("*** Skipping word len=%d\n",sms->userdatalength);*/
				while(p<sms->ascii+sms->userdatalength&&no_sip_addr_begin(*p)){
					p++;
				}
				p++;
				if (p+9>=sms->ascii+sms->userdatalength) {
				LM_ERR("unable to find sip address start in sms body [%s]!\n",
						sms->ascii);
					goto error;
				}
				/*LM_DBG("*** Done\n");*/
			}
		}while (!sip_addr.len);
	}

	/* the rest of the sms (if any ;-)) is the body! */
	sip_body.s = p;
	sip_body.len = sms->ascii + sms->userdatalength - p;
	/* let's trim out all \n an \r from beginning */
	while ( sip_body.len && sip_body.s
	&& (sip_body.s[0]=='\n' || sip_body.s[0]=='\r') ) {
		sip_body.s++;
		sip_body.len--;
	}
	if (sip_body.len==0) {
		LM_WARN("empty body for sms [%s]", sms->ascii);
		goto error;
	}
	LM_DBG("extracted body is: [%.*s]\n",sip_body.len, sip_body.s);

	/* finally, let's send it as sip message */
	sip_from.s = sms->sender;
	sip_from.len = strlen(sms->sender);
	/* patch the body with date and time */
	if (sms->userdatalength + CRLF_LEN + 1 /*'('*/ + DATE_LEN
	+ 1 /*','*/ + TIME_LEN + 1 /*')'*/< sizeof(sms->ascii)) {
		p = sip_body.s + sip_body.len;
		append_str( p, CRLF, CRLF_LEN);
		*(p++) = '(';
		append_str( p, sms->date, DATE_LEN);
		*(p++) = ',';
		append_str( p, sms->time, TIME_LEN);
		*(p++) = ')';
		sip_body.len += CRLF_LEN + DATE_LEN + TIME_LEN + 3;
	}
	return send_sip_msg_request(&sip_addr, &sip_from, &sip_body);

error:
	return -1;
}
Exemple #10
0
/* Dumps a planned specialization into a string. */
char * MVM_spesh_dump_planned(MVMThreadContext *tc, MVMSpeshPlanned *p) {
    DumpStr ds;
    ds.alloc  = 8192;
    ds.buffer = MVM_malloc(ds.alloc);
    ds.pos    = 0;

    /* Dump kind of specialization and target. */
    switch (p->kind) {
        case MVM_SPESH_PLANNED_CERTAIN:
            append(&ds, "Certain");
            break;
        case MVM_SPESH_PLANNED_OBSERVED_TYPES:
            append(&ds, "Observed type");
            break;
        case MVM_SPESH_PLANNED_DERIVED_TYPES:
            append(&ds, "Derived type");
            break;
    }
    append(&ds, " specialization of '");
    append_str(tc, &ds, p->sf->body.name);
    append(&ds, "' (cuid: ");
    append_str(tc, &ds, p->sf->body.cuuid);
    append(&ds, ", file: ");
    dump_fileinfo(tc, &ds, p->sf);
    append(&ds, ")\n\n");

    /* Dump the callsite of the specialization. */
    if (p->cs_stats->cs) {
        append(&ds, "The specialization is for the callsite:\n");
        dump_callsite(tc, &ds, p->cs_stats->cs);
    }
    else {
        append(&ds, "The specialization is for when there is no interned callsite.\n");
    }

    /* Dump reasoning. */
    switch (p->kind) {
        case MVM_SPESH_PLANNED_CERTAIN:
            if (p->cs_stats->hits >= MVM_spesh_threshold(tc, p->sf))
                appendf(&ds,
                    "It was planned due to the callsite receiving %u hits.\n",
                    p->cs_stats->hits);
            else if (p->cs_stats->osr_hits >= MVM_SPESH_PLAN_CS_MIN_OSR)
                appendf(&ds,
                    "It was planned due to the callsite receiving %u OSR hits.\n",
                    p->cs_stats->osr_hits);
            else
                append(&ds, "It was planned for unknown reasons.\n");
            if (!p->sf->body.specializable)
                append(&ds, "The body contains no specializable instructions.\n");
            break;
        case MVM_SPESH_PLANNED_OBSERVED_TYPES: {
            MVMCallsite *cs = p->cs_stats->cs;
            MVMuint32 hit_percent = p->cs_stats->hits
               ? (100 * p->type_stats[0]->hits) / p->cs_stats->hits
               : 0;
            MVMuint32 osr_hit_percent = p->cs_stats->osr_hits
               ? (100 * p->type_stats[0]->osr_hits) / p->cs_stats->osr_hits
               : 0;
            append(&ds, "It was planned for the type tuple:\n");
            dump_stats_type_tuple(tc, &ds, cs, p->type_tuple, "    ");
            if (osr_hit_percent >= MVM_SPESH_PLAN_TT_OBS_PERCENT_OSR)
                appendf(&ds, "Which received %u OSR hits (%u%% of the %u callsite OSR hits).\n",
                    p->type_stats[0]->osr_hits, osr_hit_percent, p->cs_stats->osr_hits);
            else if (hit_percent >= MVM_SPESH_PLAN_TT_OBS_PERCENT)
                appendf(&ds, "Which received %u hits (%u%% of the %u callsite hits).\n",
                    p->type_stats[0]->hits, hit_percent, p->cs_stats->hits);
            else
                append(&ds, "For unknown reasons.\n");
            break;
        }
        case MVM_SPESH_PLANNED_DERIVED_TYPES:
            break;
    }

    appendf(&ds, "\nThe maximum stack depth is %d.\n\n", p->max_depth);
    append_null(&ds);
    return ds.buffer;
}
Exemple #11
0
/* Dump a spesh graph into string form, for debugging purposes. */
char * MVM_spesh_dump(MVMThreadContext *tc, MVMSpeshGraph *g) {
    MVMSpeshBB *cur_bb;
    SpeshGraphSizeStats stats;
    InlineIndexStack inline_stack;
    DumpStr ds;

    stats.total_size = 0;
    stats.inlined_size = 0;
    inline_stack.cur_depth = -1;

    /* Allocate buffer. */
    ds.alloc  = 8192;
    ds.buffer = MVM_malloc(ds.alloc);
    ds.pos    = 0;

    /* Dump name and CUID. */
    append(&ds, "Spesh of '");
    append_str(tc, &ds, g->sf->body.name);
    append(&ds, "' (cuid: ");
    append_str(tc, &ds, g->sf->body.cuuid);
    append(&ds, ", file: ");
    dump_fileinfo(tc, &ds, g->sf);
    append(&ds, ")\n");
    if (g->cs)
        dump_callsite(tc, &ds, g->cs);
    if (!g->cs)
        append(&ds, "\n");

    /* Go over all the basic blocks and dump them. */
    cur_bb = g->entry;
    while (cur_bb) {
        dump_bb(tc, &ds, g, cur_bb, &stats, &inline_stack);
        cur_bb = cur_bb->linear_next;
    }

    /* Dump facts. */
    if (g->facts) {
        append(&ds, "\nFacts:\n");
        dump_facts(tc, &ds, g);
    }

    /* Dump spesh slots. */
    if (g->num_spesh_slots) {
        MVMuint32 i;
        append(&ds, "\nSpesh slots:\n");
        for (i = 0; i < g->num_spesh_slots; i++) {
            MVMCollectable *value = g->spesh_slots[i];
            if (value == NULL)
                appendf(&ds, "    %d = NULL\n", i);
            else if (value->flags & MVM_CF_STABLE)
                appendf(&ds, "    %d = STable (%s)\n", i,
                    MVM_6model_get_stable_debug_name(tc, (MVMSTable *)value));
            else if (value->flags & MVM_CF_TYPE_OBJECT)
                appendf(&ds, "    %d = Type Object (%s)\n", i,
                    MVM_6model_get_debug_name(tc, (MVMObject *)value));
            else {
                MVMObject *obj = (MVMObject *)value;
                MVMuint32 repr_id = REPR(obj)->ID;
                appendf(&ds, "    %d = Instance (%s)", i,
                    MVM_6model_get_debug_name(tc, obj));
                if (repr_id == MVM_REPR_ID_MVMStaticFrame || repr_id == MVM_REPR_ID_MVMCode) {
                    MVMStaticFrameBody *body;
                    char *name_str;
                    char *cuuid_str;
                    if (repr_id == MVM_REPR_ID_MVMCode) {
                        MVMCodeBody *code_body = (MVMCodeBody *)OBJECT_BODY(obj);
                        obj = (MVMObject *)code_body->sf;
                    }
                    body = (MVMStaticFrameBody *)OBJECT_BODY(obj);
                    name_str  = MVM_string_utf8_encode_C_string(tc, body->name);
                    cuuid_str = MVM_string_utf8_encode_C_string(tc, body->cuuid);
                    appendf(&ds, " - '%s' (%s)", name_str, cuuid_str);
                    MVM_free(name_str);
                    MVM_free(cuuid_str);
                }
                appendf(&ds, "\n");
            }
        }
    }

    /* Dump materialization deopt into. */
    dump_deopt_pea(tc, &ds, g);

    append(&ds, "\n");

    /* Print out frame size */
    if (stats.inlined_size)
        appendf(&ds, "Frame size: %u bytes (%u from inlined frames)\n", stats.total_size, stats.inlined_size);
    else
        appendf(&ds, "Frame size: %u bytes\n", stats.total_size);

    append_null(&ds);
    return ds.buffer;
}
Exemple #12
0
/* quick: use cursor && don't search for "more info" */
static int do_look(boolean quick)
{
    char out_str[BUFSZ];
    char firstmatch[BUFSZ];
    int i, ans = 0, objplur = 0;
    int found;		/* count of matching syms found */
    coord cc;		/* screen pos of unknown glyph */
    boolean save_verbose;	/* saved value of flags.verbose */
    boolean from_screen;	/* question from the screen */
    struct nh_desc_buf descbuf;
    struct obj *otmp;

    if (quick) {
	from_screen = TRUE;	/* yes, we want to use the cursor */
    } else {
	i = ynq("Specify unknown object by cursor?");
	if (i == 'q') return 0;
	from_screen = (i == 'y');
    }

    if (from_screen) {
	cc.x = u.ux;
	cc.y = u.uy;
    } else {
	getlin("Specify what? (type the word)", out_str);
	if (out_str[0] == '\0' || out_str[0] == '\033')
	    return 0;

	/* the ability to specify symbols is gone: it is simply impossible to
	 * know how the window port is displaying things (tiles?) and even if
	 * charaters are used it may not be possible to type them (utf8)
	 */
	
	checkfile(out_str, NULL, TRUE, TRUE);
	return 0;
    }
    /* Save the verbose flag, we change it later. */
    save_verbose = flags.verbose;
    flags.verbose = flags.verbose && !quick;
    
    /*
     * we're identifying from the screen.
     */
    do {
	/* Reset some variables. */
	found = 0;
	out_str[0] = '\0';
	objplur = 0;

	if (flags.verbose)
	    pline("Please move the cursor to %s.",
		    what_is_an_unknown_object);
	else
	    pline("Pick an object.");

	ans = getpos(&cc, FALSE, what_is_an_unknown_object);
	if (ans < 0 || cc.x < 0) {
	    flags.verbose = save_verbose;
	    return 0;	/* done */
	}
	flags.verbose = FALSE;	/* only print long question once */

	nh_describe_pos(cc.x, cc.y, &descbuf);
	
	otmp = vobj_at(cc.x, cc.y);
	if (otmp && is_plural(otmp))
	    objplur = 1;
	
	out_str[0] = '\0';
	if (append_str(out_str, descbuf.effectdesc, 0))
	    if (++found == 1)
		strcpy (firstmatch, descbuf.effectdesc);
	
	if (append_str(out_str, descbuf.invisdesc, 0))
	    if (++found == 1)
		strcpy (firstmatch, descbuf.invisdesc);
	
	if (append_str(out_str, descbuf.mondesc, 0))
	    if (++found == 1)
		strcpy (firstmatch, descbuf.mondesc);
	
	if (append_str(out_str, descbuf.objdesc, objplur))
	    if (++found == 1)
		strcpy (firstmatch, descbuf.objdesc);
	
	if (append_str(out_str, descbuf.trapdesc, 0))
	    if (++found == 1)
		strcpy (firstmatch, descbuf.trapdesc);
	
	if (append_str(out_str, descbuf.bgdesc, 0))
	    if (!found) {
		found++; /* only increment found if nothing else was seen,
		so that checkfile can be called below */
		strcpy (firstmatch, descbuf.bgdesc);
	    }
	

	/* Finally, print out our explanation. */
	if (found) {
	    out_str[0] = highc(out_str[0]);
	    pline("%s.", out_str);
	    /* check the data file for information about this thing */
	    if (found == 1 && ans != LOOK_QUICK && ans != LOOK_ONCE &&
			(ans == LOOK_VERBOSE || !quick)) {
		checkfile(firstmatch, NULL, FALSE, ans == LOOK_VERBOSE);
	    }
	} else {
	    pline("I've never heard of such things.");
	}
    } while (!quick && ans != LOOK_ONCE);

    flags.verbose = save_verbose;

    return 0;
}
//--------------------------------------------------------------------------
int idaapi rpc_debmod_t::dbg_rexec(const char *cmdline)
{
  bytevec_t req = prepare_rpc_packet(RPC_REXEC);
  append_str(req, cmdline);
  return process_long(req);
}
//--------------------------------------------------------------------------
bool rpc_debmod_t::open_remote(
    const char *hostname,
    int port_number,
    const char *password)
{
  rpc_packet_t *rp = NULL;
  network_error_code = 0;
  irs = init_client_irs(hostname, port_number);
  if ( irs == NULL )
  {
FAILURE:
    if ( rp != NULL )
      qfree(rp);
    term_irs();
    return false;
  }

  rp = recv_request();
  if ( rp == NULL || rp->code != RPC_OPEN )  // is this an ida debugger server?
  {
    rpc_client_t::dwarning("ICON ERROR\nAUTOHIDE NONE\n"
                           "Bogus or irresponsive remote server");
    goto FAILURE;
  }

  const uchar *answer = (uchar *)(rp+1);
  const uchar *end = answer + rp->length;
  int version = extract_long(&answer, end);
  int remote_debugger_id = extract_long(&answer, end);
  int easize = extract_long(&answer, end);
  qstring errstr;
  if ( version != IDD_INTERFACE_VERSION )
    errstr.sprnt("protocol version is %d, expected %d", version, IDD_INTERFACE_VERSION);
  else if ( remote_debugger_id != debugger.id )
    errstr.sprnt("debugger id is %d, expected %d (%s)", remote_debugger_id, debugger.id, debugger.name);
  else if ( easize != get_expected_addrsize() )
    errstr.sprnt("address size is %d bytes, expected %d", easize, inf.is_64bit() ? 8 : 4);
  if ( !errstr.empty() )
  {
    bytevec_t req = prepare_rpc_packet(RPC_OK);
    append_dd(req, false);
    send_request(req);
    warning("ICON ERROR\nAUTOHIDE NONE\n"
            "Incompatible debugging server:\n"
            "%s\n", errstr.c_str());
    goto FAILURE;
  }
  qfree(rp);

  bytevec_t req = prepare_rpc_packet(RPC_OK);
  append_dd(req, true);
  append_str(req, password);
  send_request(req);

  rp = recv_request();
  if ( rp == NULL || rp->code != RPC_OK )
    goto FAILURE;

  answer = (uchar *)(rp+1);
  end = answer + rp->length;
  bool password_ok = extract_long(&answer, end) != 0;
  if ( !password_ok )  // is this an ida debugger server?
  {
    warning("ICON ERROR\nAUTOHIDE NONE\n"
            "Bad password");
    goto FAILURE;
  }

  qfree(rp);
  return true;
}
Exemple #15
0
/* dumps the current status of all mediaproxies as a json blob */
int
sipp_mp_dump_json(char **msg)
{
	int buflen = 0, datalen = 0;
	char *buf = 0;
	void *ptr = 0, *ptr2 = 0;
        sipp_media_proxy_t *mp = NULL;
	char *tmpaddr1 = 0, *tmpaddr2 = 0, *tmp = 0;
	ship_list_t *callids = 0;
	char *str = 0;
	int ret = -1;
	ship_lock(sipp_mps);
	
	/* collect callids */
	ASSERT_TRUE(callids = ship_list_new(), err);
	while ((mp = ship_list_next(sipp_mps, &ptr))) {
		int found = 0;
		while (!found && (str = ship_list_next(callids, &ptr2))) {
			if (!strcmp(str, mp->callid))
				found = 1;
		}
		
		if (!found) {
			ship_list_add(callids, mp->callid);
		}
	}
	
	/* for each call id .. */
	ASSERT_TRUE(buf = append_str("var p2pship_mps = {\n", buf, &buflen, &datalen), err);
	ptr2 = 0;
	while ((str = ship_list_next(callids, &ptr2))) {
		ASSERT_TRUE(buf = append_str("     \"", buf, &buflen, &datalen), err);
		ASSERT_TRUE(buf = append_str(str, buf, &buflen, &datalen), err);
		ASSERT_TRUE(buf = append_str("\" : [\n", buf, &buflen, &datalen), err);

		ptr = 0;
		while ((mp = ship_list_next(sipp_mps, &ptr))) {
			int len = 0;
			
			if (!strcmp(mp->callid, str)) {
				ASSERT_ZERO(ident_addr_addr_to_str(&(mp->local_addr), &tmpaddr1), err);
				ASSERT_ZERO(ident_addr_addr_to_str(&(mp->remote_addr), &tmpaddr2), err);
				
				len = zstrlen(mp->sip_aor) + zstrlen(tmpaddr1) + zstrlen(mp->remote_aor) + zstrlen(tmpaddr2) + 
					zstrlen(mp->callid) + zstrlen(mp->mediatype) + 512;
				ASSERT_TRUE(tmp = mallocz(len), err);
				
				sprintf(tmp, "         [ \"%s\", \"%s\", \"%s\", \"%s\", \"%s\",\n           \"%s\", \"%s\", \"%d\", \"%d\", \"%d\", \"%d\" ],\n",
					mp->sip_aor, tmpaddr1, mp->remote_aor, tmpaddr2, sipp_mp_sendby_str(mp->sendby),
					mp->callid, mp->mediatype,
					mp->started, (int)mp->start_time, (int)mp->last, mp->counter);
				
				ASSERT_TRUE(buf = append_str(tmp, buf, &buflen, &datalen), err);
				freez(tmp);
				freez(tmpaddr1);
				freez(tmpaddr2);
			}
		}
		ASSERT_TRUE(replace_end(buf, &buflen, &datalen, ",\n", "\n"), err);
		ASSERT_TRUE(buf = append_str("     ],\n", buf, &buflen, &datalen), err);
	}

	ASSERT_TRUE(replace_end(buf, &buflen, &datalen, ",\n", "\n"), err);
	ASSERT_TRUE(buf = append_str("};\n", buf, &buflen, &datalen), err);
	*msg = buf;
	buf = 0;
	ret = 0;
 err:
	ship_unlock(sipp_mps);
	ship_list_free(callids);
	freez(buf);
	freez(tmpaddr1);
	freez(tmpaddr2);
	freez(tmp);
	return ret;
}
Exemple #16
0
int send_sip_msg_request(str *to, str *from_user, str *body)
{
	str msg_type = STR_STATIC_INIT("MESSAGE");
	str from;
	str hdrs;
	int foo;
	char *p;
	uac_req_t uac_r;

	from.s = hdrs.s = 0;
	from.len = hdrs.len = 0;

	/* From header */
	from.len = 6 /*"<sip:+"*/ +  from_user->len/*user*/ + 1/*"@"*/
		+ domain.len /*host*/ + 1 /*">"*/ ;
	from.s = (char*)pkg_malloc(from.len);
	if (!from.s)
		goto error;
	p=from.s;
	append_str(p,"<sip:+",6);
	append_str(p,from_user->s,from_user->len);
	*(p++)='@';
	append_str(p,domain.s,domain.len);
	*(p++)='>';

	/* hdrs = Contact header + Content-type */
	/* length */
	hdrs.len = CONTENT_TYPE_HDR_LEN + CRLF_LEN;
	if (use_contact)
		hdrs.len += 15 /*"Contact: <sip:+"*/ + from_user->len/*user*/ +
			1/*"@"*/ + domain.len/*host*/ + 1 /*">"*/ + CRLF_LEN;
	hdrs.s = (char*)pkg_malloc(hdrs.len);
	if (!hdrs.s)
		goto error;
	p=hdrs.s;
	append_str(p,CONTENT_TYPE_HDR,CONTENT_TYPE_HDR_LEN);
	append_str(p,CRLF,CRLF_LEN);
	if (use_contact) {
		append_str(p,"Contact: <sip:+",15);
		append_str(p,from_user->s,from_user->len);
		*(p++)='@';
		append_str(p,domain.s,domain.len);
		append_str(p,">"CRLF,1+CRLF_LEN);
	}

	/* sending the request */
	set_uac_req(&uac_r,
			&msg_type,	/* request type */
			&hdrs,		/* Additional headers including CRLF */
			body,		/* Message body */
			0,		/* dialog structure */
			0,		/* callback flags */
			0,		/* Callback function */
			0		/* Callback parameter */
		);
	
	foo = tmb.t_request(&uac_r,
			0,	/* Request-URI */
			to,	/* To */
			&from,	/* From */
			0	/* next hop */
		);

	if (from.s) pkg_free(from.s);
	if (hdrs.s) pkg_free(hdrs.s);
	return foo;
error:
	LM_ERR("no free pkg memory!\n");
	if (from.s) pkg_free(from.s);
	if (hdrs.s) pkg_free(hdrs.s);
	return -1;
}
Exemple #17
0
int send_as_sms(struct sms_msg *sms_messg, struct modem *mdm)
{
	static char   buf[MAX_SMS_LENGTH];
	unsigned int  buf_len;
	unsigned char len_array_1[256], len_array_2[256], *len_array;
	unsigned int  nr_chunks_1,  nr_chunks_2, nr_chunks;
	unsigned int  use_nice;
	str  text;
	char *p, *q;
	int  ret_code;
	int  i;

	text.s   = sms_messg->text.s;
	text.len = sms_messg->text.len;

	nr_chunks_1 = split_text( &text, len_array_1, 0);
	nr_chunks_2 = split_text( &text, len_array_2, 1);
	if (nr_chunks_1==nr_chunks_2) {
		len_array = len_array_2;
		nr_chunks = nr_chunks_2;
		use_nice = 1;
	} else {
		len_array = len_array_1;
		nr_chunks = nr_chunks_1;
		use_nice = 0;
	}

	sms_messg->ref = 1;
	for(i=0,p=text.s ; i<nr_chunks&&i<max_sms_parts ; p+=len_array[i++]) {
		if (use_nice) {
			q = buf;
			if (nr_chunks>1 && i)  {
				append_str(q,SMS_EDGE_PART,SMS_EDGE_PART_LEN);
				*(q-2)=nr_chunks+'0';
				*(q-4)=i+1+'0';
			}
			append_str(q,p,len_array[i]);
			if (nr_chunks>1 && !i)  {
				append_str(q,SMS_EDGE_PART,SMS_EDGE_PART_LEN);
				*(q-2)=nr_chunks+'0';
				*(q-4)=i+1+'0';
			}
			buf_len = q-buf;
		} else {
			q = buf;
			append_str(q,p,len_array[i]);
			buf_len = len_array[i];
		}
		if (i+1==max_sms_parts && i+1<nr_chunks) {
			/* simply override the end of the last allowed part */
			buf_len += SMS_TRUNCATED_LEN+SMS_FOOTER_LEN;
			if (buf_len>MAX_SMS_LENGTH) buf_len = MAX_SMS_LENGTH;
			q = buf + (buf_len-SMS_TRUNCATED_LEN-SMS_FOOTER_LEN);
			append_str(q,SMS_TRUNCATED,SMS_TRUNCATED_LEN);
			append_str(q,SMS_FOOTER,SMS_FOOTER_LEN);
			p += buf_len-SMS_TRUNCATED_LEN-SMS_FOOTER_LEN-SMS_EDGE_PART_LEN;
			send_error(sms_messg, ERR_TRUNCATE_TEXT, ERR_TRUNCATE_TEXT_LEN,
				p, text.len-(p-text.s)-SMS_FOOTER_LEN);
		}
		LM_DBG("---%d--<%d><%d>--\n|%.*s|\n", i, len_array[i], buf_len,
										(int)buf_len, buf);
		sms_messg->text.s   = buf;
		sms_messg->text.len = buf_len;
		if ( (ret_code=putsms(sms_messg,mdm))<0)
			goto error;
		if (sms_report_type!=NO_REPORT)
			add_sms_into_report_queue(ret_code,sms_messg,
				p-use_nice*(nr_chunks>1)*SMS_EDGE_PART_LEN,len_array[i]);
	}

	sms_messg->ref--;
	/* put back the pointer to the beginning of the message*/
	sms_messg->text.s = text.s;
	sms_messg->text.len = text.len;
	/* remove the sms if nobody points to it */
	if (!sms_messg->ref){
		shm_free(sms_messg);
	}
	return 1;
error:
	if (ret_code==-1)
		/* bad number */
		send_error(sms_messg, sms_messg->to.s, sms_messg->to.len,
			ERR_NUMBER_TEXT, ERR_NUMBER_TEXT_LEN);
	else if (ret_code==-2)
		/* bad modem */
		send_error(sms_messg, ERR_MODEM_TEXT, ERR_MODEM_TEXT_LEN,
			text.s+SMS_HDR_BF_ADDR_LEN+sms_messg->from.len+SMS_HDR_AF_ADDR_LEN,
			text.len-SMS_FOOTER_LEN-SMS_HDR_BF_ADDR_LEN-sms_messg->from.len-
			SMS_HDR_AF_ADDR_LEN );

	if (!(--(sms_messg->ref)))
		shm_free(sms_messg);
	return -1;
}
Exemple #18
0
/* Dumps a static frame's guard set into a string. */
char * MVM_spesh_dump_arg_guard(MVMThreadContext *tc, MVMStaticFrame *sf) {
    MVMSpeshArgGuard *ag = sf->body.spesh->body.spesh_arg_guard;

    DumpStr ds;
    ds.alloc  = 8192;
    ds.buffer = MVM_malloc(ds.alloc);
    ds.pos    = 0;

    /* Dump name and CUID. */
    append(&ds, "Latest guard tree for '");
    append_str(tc, &ds, sf->body.name);
    append(&ds, "' (cuid: ");
    append_str(tc, &ds, sf->body.cuuid);
    append(&ds, ", file: ");
    dump_fileinfo(tc, &ds, sf);
    append(&ds, ")\n\n");

    /* Dump nodes. */
    if (ag) {
        MVMuint32 i = 0;
        for (i = 0; i < ag->used_nodes; i++) {
            MVMSpeshArgGuardNode *agn = &(ag->nodes[i]);
            switch (agn->op) {
                case MVM_SPESH_GUARD_OP_CALLSITE:
                    appendf(&ds, "%u: CALLSITE %p | Y: %u, N: %u\n",
                        i, agn->cs, agn->yes, agn->no);
                    break;
                case MVM_SPESH_GUARD_OP_LOAD_ARG:
                    appendf(&ds, "%u: LOAD ARG %d | Y: %u\n",
                        i, agn->arg_index, agn->yes);
                    break;
                case MVM_SPESH_GUARD_OP_STABLE_CONC:
                    appendf(&ds, "%u: STABLE CONC %s | Y: %u, N: %u\n",
                        i, MVM_6model_get_stable_debug_name(tc, agn->st), agn->yes, agn->no);
                    break;
                case MVM_SPESH_GUARD_OP_STABLE_TYPE:
                    appendf(&ds, "%u: STABLE CONC %s | Y: %u, N: %u\n",
                        i, MVM_6model_get_stable_debug_name(tc, agn->st), agn->yes, agn->no);
                    break;
                case MVM_SPESH_GUARD_OP_DEREF_VALUE:
                    appendf(&ds, "%u: DEREF_VALUE %u | Y: %u, N: %u\n",
                        i, agn->offset, agn->yes, agn->no);
                    break;
                case MVM_SPESH_GUARD_OP_DEREF_RW:
                    appendf(&ds, "%u: DEREF_RW %u | Y: %u, N: %u\n",
                        i, agn->offset, agn->yes, agn->no);
                    break;
                case MVM_SPESH_GUARD_OP_CERTAIN_RESULT:
                    appendf(&ds, "%u: CERTAIN RESULT %u\n", i, agn->result);
                    break;
                case MVM_SPESH_GUARD_OP_RESULT:
                    appendf(&ds, "%u: RESULT %u\n", i, agn->result);
                    break;
            }
        }
    }
    else {
        append(&ds, "No argument guard nodes\n");
    }

    append(&ds, "\n");
    append_null(&ds);
    return ds.buffer;
}
Exemple #19
0
static void create_inf_file(void)
{
    char data[1024];
    char *ptr = data;
    DWORD dwNumberOfBytesWritten;
    HANDLE hf = CreateFileA(inf_file, GENERIC_WRITE, 0, NULL,
                            CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    append_str(&ptr, "[Version]\n");
    append_str(&ptr, "Signature=\"$Chicago$\"\n");
    append_str(&ptr, "[CustInstDestSection]\n");
    append_str(&ptr, "49001=ProgramFilesDir\n");
    append_str(&ptr, "49010=DestA,1\n");
    append_str(&ptr, "49020=DestB\n");
    append_str(&ptr, "49030=DestC\n");
    append_str(&ptr, "[ProgramFilesDir]\n");
    append_str(&ptr, "HKLM,\"Software\\Microsoft\\Windows\\CurrentVersion\",");
    append_str(&ptr, "\"ProgramFilesDir\",,\"%%24%%\\%%LProgramF%%\"\n");
    append_str(&ptr, "[section]\n");
    append_str(&ptr, "NotACustomDestination=Version\n");
    append_str(&ptr, "CustomDestination=CustInstDestSection\n");
    append_str(&ptr, "[Options.NTx86]\n");
    append_str(&ptr, "49001=ProgramFilesDir\n");
    append_str(&ptr, "InstallDir=%%49001%%\\%%DefaultAppPath%%\n");
    append_str(&ptr, "Result1=%%49010%%\n");
    append_str(&ptr, "Result2=%%49020%%\n");
    append_str(&ptr, "Result3=%%49030%%\n");
    append_str(&ptr, "CustomHDestination=CustInstDestSection\n");
    append_str(&ptr, "[Strings]\n");
    append_str(&ptr, "DefaultAppPath=\"Application Name\"\n");
    append_str(&ptr, "LProgramF=\"%s\"\n", PROG_FILES);
    append_str(&ptr, "[DestA]\n");
    append_str(&ptr, "HKLM,\"Software\\Garbage\",\"ProgramFilesDir\",,'%%24%%\\%%LProgramF%%'\n");
    append_str(&ptr, "[DestB]\n");
    append_str(&ptr, "'HKLM','Software\\Microsoft\\Windows\\CurrentVersion',");
    append_str(&ptr, "'ProgramFilesDir',,\"%%24%%\"\n");
    append_str(&ptr, "[DestC]\n");
    append_str(&ptr, "HKLM,\"Software\\Garbage\",\"ProgramFilesDir\",,'%%24%%'\n");

    WriteFile(hf, data, ptr - data, &dwNumberOfBytesWritten, NULL);
    CloseHandle(hf);
}
Exemple #20
0
/* called to re-update the buddy list to the pathfinder */
static int
sipp_buddy_perform_buddylist_update(ident_t *from)
{
	char *postdata = 0, *tmp = 0;
	int len = 0, size = 0;
	int ret = -1;
	char buf[128];
	time_t exp, now;
	char *xml = 0;
	buddy_t* buddy = 0;
	void *ptr = 0;
	char *x = 0, *x2 = 0;
	
	/* construct the xml package of all still-valid subscribes */
	time(&now);
	exp = now;

	while ((buddy = ship_list_next(from->buddy_list, &ptr))) {
		int valid = buddy->created + buddy->expire;
		if (valid > now) {
			ASSERT_TRUE((x = append_str("<buddy><hash>", xml, &size, &len)) &&
				    (xml = x), berr);
			ASSERT_TRUE(x2 = ship_hash_sha1_base64(buddy->sip_aor, strlen(buddy->sip_aor)), berr);
			ASSERT_TRUE((x = append_str(x2, xml, &size, &len)) &&
				    (xml = x), berr);
			freez(x2);
			ASSERT_TRUE((x = append_str("</hash></buddy>", xml, &size, &len)) &&
				    (xml = x), berr);
			if (valid < exp || exp == now)
				exp = valid;
		}
	}
 berr:
	freez(x2);
	if (!x)
		freez(xml);
	
	if (!xml) {
		ASSERT_TRUE(xml = strdup(""), err);
	}
	
	/* construct complete xml - timestamps */
	len = 0; size = 0;
	ASSERT_TRUE((tmp = append_str("<buddylistdoc><payload><![CDATA[<load><timestamp>", postdata, &size, &len)) &&
		    (postdata = tmp), err);
	ship_format_time(now, buf, sizeof(buf));
	ASSERT_TRUE((tmp = append_str(buf, postdata, &size, &len)) &&
		    (postdata = tmp), err);
	ASSERT_TRUE((tmp = append_str("</timestamp><expires>", postdata, &size, &len)) &&
		    (postdata = tmp), err);
	ship_format_time(exp, buf, sizeof(buf));
	ASSERT_TRUE((tmp = append_str(buf, postdata, &size, &len)) &&
		    (postdata = tmp), err);

	/* self hash */
	ASSERT_TRUE((tmp = append_str("</expires><self><hash>", postdata, &size, &len)) &&
		    (postdata = tmp), err);
	
	ASSERT_TRUE(x2 = ship_hash_sha1_base64(from->sip_aor, strlen(from->sip_aor)), err);
	ASSERT_TRUE((tmp = append_str(x2, postdata, &size, &len)) &&
		    (postdata = tmp), err);
	freez(x2);

	/* buddies */
	ASSERT_TRUE((tmp = append_str("</hash><cert></cert></self><buddies>", postdata, &size, &len)) &&
		    (postdata = tmp), err);
	ASSERT_TRUE((tmp = append_str(xml, postdata, &size, &len)) &&
		    (postdata = tmp), err);
	ASSERT_TRUE((tmp = append_str("</buddies></load>]]></payload><signature /></buddylistdoc>", postdata, &size, &len)) &&
		    (postdata = tmp), err);
	freez(xml);
	xml = postdata;

	/* url-encode & post */
	len = 0; size = 0;
	postdata = 0;
	x2 = ship_urlencode(xml);
	ASSERT_TRUE((tmp = append_str("submission.xml=", postdata, &size, &len)) && (postdata = tmp), err);
	ASSERT_TRUE((tmp = append_str(x2, postdata, &size, &len)) && (postdata = tmp), err);
	
	ret = netio_http_post_host(trustman_get_pathfinder(),
				   "/postbuddylist",
				   "",
				   "application/x-www-form-urlencoded",
				   postdata, strlen(postdata),
				   sipp_buddy_pf_cb, NULL);
 err:
	freez(x2);
	freez(xml);
	freez(postdata);
	return ret;
}
Exemple #21
0
int main(void)
{
	char *cmdline = GetCommandLine();
	char *new_cmdline;

	{
		char full_path[256];
		GetModuleFileName(NULL, full_path, sizeof(full_path));
		PathRemoveFileSpec(full_path);
		append_str(full_path);
		append_str("\\");
	}

	if(MessageBox(0, "Enable COPY?", "Switcher", MB_YESNO | MB_ICONQUESTION) == IDYES) {
		int kv = 0;
		const char *my_client = "..\\spicy\\spicy.exe";
		const char *required_args[] = { "-h", "-p", "-s", "-w", NULL };

		{
			char path[256];
			GetModuleFileName(NULL, path, sizeof(path));
			PathRemoveFileSpec(path);
			strcat(path, "\\..\\spicy");
			SetCurrentDirectory(path);
		}

		get_item(&cmdline); // skip program path
		append_str(my_client);

		while(get_item(&cmdline)) {
			int required = 0;
			const char **p = required_args;
			for(; *p; p++) if(strcmp(item, *p) == 0) { required = 1; break; }

			if(required) { append_arg(); get_item(&cmdline); append_arg(); }
			else { get_item(&cmdline); }
		}
	} else {
		const char *orig_client = "_spicec.exe";
		get_item(&cmdline); // skip program path
		append_str(orig_client);
		append_str(cmdline);
	}

	new_cmdline = finish_args();

	{
		STARTUPINFO si;
		PROCESS_INFORMATION pi;
		DWORD flags = 0;

		memset(&si, 0, sizeof(si));
		si.cb = sizeof(STARTUPINFO);

/* want to show the console of spicy for debug? */
#if 0
		flags = CREATE_NEW_CONSOLE;
#endif
		CreateProcessA(NULL, new_cmdline, NULL, NULL, FALSE, flags, NULL, NULL, &si, &pi);
	}
	return 0;
}
Exemple #22
0
/*
 * Converts URI, if it is tel URI, to SIP URI.  Returns 1, if
 * conversion succeeded or if no conversion was needed, i.e., URI was not
 * tel URI.  Returns -1, if conversion failed.  Takes SIP URI hostpart from
 * second parameter and (if needed) writes the result to third paramater.
 */
int tel2sip(struct sip_msg* _msg, char* _uri, char* _hostpart, char* _res)
{
    str uri, hostpart, tel_uri, sip_uri;
    char *at;
    int i, j, in_tel_parameters = 0;
    pv_spec_t *res;
    pv_value_t res_val;

    /* get parameters */
    if (get_str_fparam(&uri, _msg, (fparam_t*)_uri) < 0) {
	LM_ERR("failed to get uri value\n");
    }
    if (get_str_fparam(&hostpart, _msg, (fparam_t*)_hostpart) < 0) {
	LM_ERR("failed to get hostpart value\n");
    }
    res = (pv_spec_t *)_res;

    /* check if anything needs to be done */
    if (uri.len < 4) return 1;
    if (strncasecmp(uri.s, "tel:", 4) != 0) return 1;
    
    /* reserve memory for clean tel uri */
    tel_uri.s = pkg_malloc(uri.len+1);
    if (tel_uri.s == 0) {
	LM_ERR("no more pkg memory\n");
	return -1;
    }
	
    /* Remove visual separators before converting to SIP URI. Don't remove 
       visual separators in TEL URI parameters (after the first ";") */
    for (i=0, j=0; i < uri.len; i++) {
	if (in_tel_parameters == 0) {
	    if (uri.s[i] == ';')
		in_tel_parameters = 1;
	}
	if (in_tel_parameters == 0) {
	    if ((uri.s[i] != '-') && (uri.s[i] != '.') && 
		(uri.s[i] != '(') && (uri.s[i] != ')'))
		tel_uri.s[j++] = tolower(uri.s[i]);
	} else {
	    tel_uri.s[j++] = tolower(uri.s[i]);
	}
    }
    tel_uri.s[j] = '\0';
    tel_uri.len = strlen(tel_uri.s);

    /* reserve memory for resulting sip uri */
    sip_uri.len = 4 + tel_uri.len - 4 + 1 + hostpart.len + 1 + 10;
    sip_uri.s = pkg_malloc(sip_uri.len);
    if (sip_uri.s == 0) {
	LM_ERR("no more pkg memory\n");
	pkg_free(tel_uri.s);
	return -1;
    }

    /* create resulting sip uri */
    at = sip_uri.s;
    append_str(at, "sip:", 4);
    append_str(at, tel_uri.s + 4, tel_uri.len - 4);
    append_chr(at, '@');
    append_str(at, hostpart.s, hostpart.len);
    append_chr(at, ';');
    append_str(at, "user=phone", 10);

    /* tel_uri is not needed anymore */
    pkg_free(tel_uri.s);

    /* set result pv value and write sip uri to result pv */
    res_val.rs = sip_uri;
    res_val.flags = PV_VAL_STR;
    if (res->setf(_msg, &res->pvp, (int)EQ_T, &res_val) != 0) {
	LM_ERR("failed to set result pvar\n");
	pkg_free(sip_uri.s);
	return -1;
    }

    /* free allocated pkg memory and return */
    pkg_free(sip_uri.s);
    return 1;
}
Exemple #23
0
void send_text(char *text)
{
#if WIN32
  if (test_mode)
    return;
#endif

  char *filter;

  if (!text)
    return;
  int len = strlen(text);

  add_ch_time_str(text);

  append_str(&output_buffer_raw, &output_buffer_rawN, text, len);

  char *utf8_gbtext = NULL;

  if (gb_output) {
    len = trad2sim(text, len, &utf8_gbtext);
    text = utf8_gbtext;
  }

//direct:
#if UNIX
  filter = getenv("HIME_OUTPUT_FILTER");
  char filter_text[512];

  if (filter) {
    int pfdr[2], pfdw[2];

    if (pipe(pfdr) == -1) {
      dbg("cannot pipe r\n");
      goto next;
    }

    if (pipe(pfdw) == -1) {
      dbg("cannot pipe w\n");
      goto next;
    }

    int pid = fork();

    if (pid < 0) {
      dbg("cannot fork filter\n");
      goto next;
    }

    if (pid) {
      close(pfdw[0]);
      close(pfdr[1]);
      write(pfdw[1], text, len);
      close(pfdw[1]);
      int rn = read(pfdr[0], filter_text, sizeof(filter_text) - 1);
      filter_text[rn] = 0;
//      puts(filter_text);
      close(pfdr[0]);
      text = filter_text;
      len = rn;
    } else {
      close(pfdr[0]);
      close(pfdw[1]);
      dup2(pfdw[0], 0);
      dup2(pfdr[1], 1);
      if (execl(filter, filter, NULL) < 0) {
        dbg("execl %s err", filter);
        goto next;
      }
    }

  }
#endif
next:
  if (len) {
    append_str(&output_buffer, &output_bufferN, text, len);
  }

  free(utf8_gbtext);
}
Exemple #24
0
/*
 * Set userpart of URI
 */
int set_uri_user(struct sip_msg* _m, char* _uri, char* _value)
{
    pv_spec_t *uri_pv, *value_pv;
    pv_value_t uri_val, value_val, res_val;
    str uri, value;
    char *at, *colon, *c;
    char new_uri[MAX_URI_SIZE + 1];

    uri_pv = (pv_spec_t *)_uri;
    if (uri_pv && (pv_get_spec_value(_m, uri_pv, &uri_val) == 0)) {
	if (uri_val.flags & PV_VAL_STR) {
	    if (uri_val.rs.len == 0 || uri_val.rs.s == NULL) {
		LM_ERR("missing uri value\n");
		return -1;
	    }
	} else {
	    LM_ERR("uri value is not string\n");
	    return -1;
	}
    } else {
	LM_ERR("failed to get uri value\n");
	return -1;
    }
    uri = uri_val.rs;

    value_pv = (pv_spec_t *)_value;
    if (value_pv && (pv_get_spec_value(_m, value_pv, &value_val) == 0)) {
	if (value_val.flags & PV_VAL_STR) {
	    if (value_val.rs.s == NULL) {
		LM_ERR("missing uriuser value\n");
		return -1;
	    }
	} else {
	    LM_ERR("uriuser value is not string\n");
	    return -1;
	}
    } else {
	LM_ERR("failed to get uriuser value\n");
	return -1;
    }
    value = value_val.rs;

    colon = strchr(uri.s, ':');
    if (colon == NULL) {
	LM_ERR("uri does not contain ':' character\n");
	return -1;
    }
    at = strchr(uri.s, '@');
    c = &(new_uri[0]);
    if (at == NULL) {
	if (value.len == 0) return 1;
	if (uri.len + value.len > MAX_URI_SIZE) {
	    LM_ERR("resulting uri would be too large\n");
	    return -1;
	}
	append_str(c, uri.s, colon - uri.s + 1);
	append_str(c, value.s, value.len);
	append_chr(c, '@');
	append_str(c, colon + 1, uri.len - (colon - uri.s + 1));
	res_val.rs.len = uri.len + value.len + 1;
    } else {
	if (value.len == 0) {
	    append_str(c, uri.s, colon - uri.s + 1);
	    append_str(c, at + 1, uri.len - (at - uri.s + 1));
	    res_val.rs.len = uri.len - (at - colon);
	} else {
	    if (uri.len + value.len - (at - colon - 1) > MAX_URI_SIZE) {
		LM_ERR("resulting uri would be too large\n");
		return -1;
	    }
	    append_str(c, uri.s, colon - uri.s + 1);
	    append_str(c, value.s, value.len);
	    append_str(c, at, uri.len - (at - uri.s));
	    res_val.rs.len = uri.len + value.len - (at - colon - 1);
	}
    }

    res_val.rs.s = &(new_uri[0]);
    LM_DBG("resulting uri: %.*s\n", res_val.rs.len, res_val.rs.s);
    res_val.flags = PV_VAL_STR;
    uri_pv->setf(_m, &uri_pv->pvp, (int)EQ_T, &res_val);

    return 1;
}
Exemple #25
0
/* Re-parsing version of build_local() function:
 * it builds a local CANCEL or ACK (for non-200 response) request based on
 * the previous INVITE which was sent out.
 *
 * Can not be used to build other type of requests!
 */
char *build_local_reparse(struct cell *Trans,unsigned int branch,
	unsigned int *len, char *method, int method_len, str *to
#ifdef CANCEL_REASON_SUPPORT
	, struct cancel_reason *reason
#endif /* CANCEL_REASON_SUPPORT */
	)
{
	char	*invite_buf, *invite_buf_end;
	char	*cancel_buf;
	char	*s, *s1, *d;	/* source and destination buffers */
	short	invite_len;
	enum _hdr_types_t	hf_type;
	int	first_via, to_len;
	int cancel_buf_len;
#ifdef CANCEL_REASON_SUPPORT
	int reason_len, code_len;
	struct hdr_field *reas1, *reas_last, *hdr;
#endif /* CANCEL_REASON_SUPPORT */
	int hadded = 0;
	sr_cfgenv_t *cenv = NULL;

	invite_buf = Trans->uac[branch].request.buffer;
	invite_len = Trans->uac[branch].request.buffer_len;

	if (!invite_buf || !invite_len) {
		LM_ERR("INVITE is missing\n");
		goto error;
	}
	if ((*invite_buf != 'I') && (*invite_buf != 'i')) {
		LM_ERR("trying to build with local reparse"
					" for a non-INVITE request?\n");
		goto error;
	}

#ifdef CANCEL_REASON_SUPPORT
	reason_len = 0;
	reas1 = 0;
	reas_last = 0;
	/* compute reason size (if no reason or disabled => reason_len == 0)*/
	if (reason && reason->cause != CANCEL_REAS_UNKNOWN){
		if (likely(reason->cause > 0 &&
					cfg_get(tm, tm_cfg, local_cancel_reason))){
			/* Reason: SIP;cause=<reason->cause>[;text=<reason->u.text.s>] */
			reason_len = REASON_PREFIX_LEN + USHORT2SBUF_MAX_LEN +
				(reason->u.text.s?
					REASON_TEXT_LEN + 1 + reason->u.text.len + 1 : 0) +
				CRLF_LEN;
		} else if (likely(reason->cause == CANCEL_REAS_PACKED_HDRS &&
					!(Trans->flags & T_NO_E2E_CANCEL_REASON))) {
			reason_len = reason->u.packed_hdrs.len;
		} else if (reason->cause == CANCEL_REAS_RCVD_CANCEL &&
					reason->u.e2e_cancel &&
					!(Trans->flags & T_NO_E2E_CANCEL_REASON)) {
			/* parse the entire cancel, to get all the Reason headers */
			if(parse_headers(reason->u.e2e_cancel, HDR_EOH_F, 0)<0) {
				LM_WARN("failed to parse headers\n");
			}
			for(hdr=get_hdr(reason->u.e2e_cancel, HDR_REASON_T), reas1=hdr;
					hdr; hdr=next_sibling_hdr(hdr)) {
				/* hdr->len includes CRLF */
				reason_len += hdr->len;
				reas_last=hdr;
			}
		} else if (unlikely(reason->cause < CANCEL_REAS_MIN))
			LM_BUG("unhandled reason cause %d\n", reason->cause);
	}
#endif /* CANCEL_REASON_SUPPORT */

	invite_buf_end = invite_buf + invite_len;
	s = invite_buf;

	/* Allocate memory for the new message.
	The new request will be smaller than the INVITE, so the same size is enough.
	I just extend it with the length of new To HF to be sure.
	Ugly, but we avoid lots of checks and memory allocations this way */
	to_len = to ? to->len : 0;
#ifdef CANCEL_REASON_SUPPORT
	cancel_buf_len = invite_len + to_len + reason_len;
#else
	cancel_buf_len = invite_len + to_len;
#endif /* CANCEL_REASON_SUPPORT */
	cancel_buf = shm_malloc(sizeof(char)*cancel_buf_len);
	if (!cancel_buf)
	{
		LM_ERR("cannot allocate shared memory\n");
		goto error;
	}
	d = cancel_buf;

	/* method name + space */
	append_str(d, method, method_len);
	*d = ' ';
	d++;
	/* skip "INVITE " and copy the rest of the line including CRLF */
	s += 7;
	s1 = s;
	s = eat_line(s, invite_buf_end - s);
	append_str(d, s1, s - s1);

	cenv = sr_cfgenv_get();

	/* check every header field name,
	we must exclude and modify some of the headers */
	first_via = 1;
	while (s < invite_buf_end) {
		s1 = s;
		if ((*s == '\n') || (*s == '\r')) {
			/* end of SIP msg */
			hf_type = HDR_EOH_T;
		} else {
			/* parse HF name */
			s = lw_get_hf_name(s, invite_buf_end,
						&hf_type);
		}

		switch(hf_type) {
			case HDR_CSEQ_T:
				/* find the method name and replace it */
				while ((s < invite_buf_end)
					&& ((*s == ':') || (*s == ' ') || (*s == '\t') ||
						((*s >= '0') && (*s <= '9')))
					) s++;
				append_str(d, s1, s - s1);
				append_str(d, method, method_len);
				append_str(d, CRLF, CRLF_LEN);
				s = lw_next_line(s, invite_buf_end);
				break;

			case HDR_VIA_T:
				s = lw_next_line(s, invite_buf_end);
				if (first_via) {
					/* copy hf */
					append_str(d, s1, s - s1);
					first_via = 0;
				} /* else skip this line, we need olny the first via */
				break;

			case HDR_TO_T:
				if (to_len == 0) {
					/* there is no To tag required, just copy paste
					 * the header */
					s = lw_next_line(s, invite_buf_end);
					append_str(d, s1, s - s1);
				} else {
					/* use the given To HF instead of the original one */
					append_str(d, to->s, to->len);
					/* move the pointer to the next line */
					s = lw_next_line(s, invite_buf_end);
				}
				break;

			case HDR_FROM_T:
			case HDR_CALLID_T:
			case HDR_ROUTE_T:
			case HDR_MAXFORWARDS_T:
				/* copy hf */
				s = lw_next_line(s, invite_buf_end);
				append_str(d, s1, s - s1);
				break;

			case HDR_REQUIRE_T:
			case HDR_PROXYREQUIRE_T:
				/* skip this line */
				s = lw_next_line(s, invite_buf_end);
				break;

			case HDR_CONTENTLENGTH_T:
				/* copy hf name with 0 value */
				append_str(d, s1, s - s1);
				append_str(d, ": 0" CRLF, 3 + CRLF_LEN);
				/* move the pointer to the next line */
				s = lw_next_line(s, invite_buf_end);
				break;

			case HDR_EOH_T:
				/* end of SIP message found */
#ifdef CANCEL_REASON_SUPPORT
				/* add reason if needed */
				if (reason_len) {
					/* if reason_len !=0, no need for any reason enabled
					 * checks */
					if (likely(reason->cause > 0)) {
						append_str(d, REASON_PREFIX, REASON_PREFIX_LEN);
						code_len=ushort2sbuf(reason->cause, d,
										cancel_buf_len-(int)(d-cancel_buf));
						if (unlikely(code_len==0))
							LM_BUG("not enough space to write reason code");
						d+=code_len;
						if (reason->u.text.s){
							append_str(d, REASON_TEXT, REASON_TEXT_LEN);
							*d='"'; d++;
							append_str(d, reason->u.text.s,
											reason->u.text.len);
							*d='"'; d++;
						}
						append_str(d, CRLF, CRLF_LEN);
					} else if (likely(reason->cause ==
										CANCEL_REAS_PACKED_HDRS)) {
							append_str(d, reason->u.packed_hdrs.s,
											reason->u.packed_hdrs.len);
					} else if (reason->cause == CANCEL_REAS_RCVD_CANCEL) {
						for(hdr=reas1; hdr; hdr=next_sibling_hdr(hdr)) {
							/* hdr->len includes CRLF */
							append_str(d, hdr->name.s, hdr->len);
							if (likely(hdr==reas_last))
								break;
						}
					}
				}
#endif /* CANCEL_REASON_SUPPORT */
				/* final (end-of-headers) CRLF */
				append_str(d, CRLF, CRLF_LEN);
				*len = d - cancel_buf;
				/* LOG(L_DBG, "DBG: build_local: %.*s\n", *len, cancel_buf); */
				return cancel_buf;

			default:
				s = lw_next_line(s, invite_buf_end);
				hadded = 0;

				/* uac auth headers */
				if(Trans->uas.request &&
						(Trans->uas.request->msg_flags & FL_UAC_AUTH)) {
					if(s1 + cenv->uac_cseq_auth.len + 2 < invite_buf_end) {
						if(s1[cenv->uac_cseq_auth.len]==':'
								&& strncmp(s1, cenv->uac_cseq_auth.s,
									cenv->uac_cseq_auth.len)==0) {
							hadded = 1;
							append_str(d, s1, s - s1);
						} else if(s1[cenv->uac_cseq_refresh.len]==':'
								&& strncmp(s1, cenv->uac_cseq_refresh.s,
									cenv->uac_cseq_refresh.len)==0) {
							hadded = 1;
							append_str(d, s1, s - s1);
						}
					}
				}

				if(likely(hadded==0)) {
					if (cfg_get(tm, tm_cfg, ac_extra_hdrs).len
							&& (s1 + cfg_get(tm, tm_cfg, ac_extra_hdrs).len < invite_buf_end)
							&& (strncasecmp(s1,
									cfg_get(tm, tm_cfg, ac_extra_hdrs).s,
									cfg_get(tm, tm_cfg, ac_extra_hdrs).len) == 0)) {
						append_str(d, s1, s - s1);
					}
				}
				break;
		}
	}

	/* HDR_EOH_T was not found in the buffer, the message is corrupt */
	LM_ERR("HDR_EOH_T was not found\n");

	shm_free(cancel_buf);
error:
	LM_ERR("cannot build %.*s request\n", method_len, method);
	return NULL;

}
Exemple #26
0
/*
 * Set hostpart of URI
 */
int set_uri_host(struct sip_msg* _m, char* _uri, char* _value)
{
    pv_spec_t *uri_pv, *value_pv;
    pv_value_t uri_val, value_val, res_val;
    str uri, value;
    char *at, *colon, *c, *next;
    unsigned int host_len;
    char new_uri[MAX_URI_SIZE + 1];

    uri_pv = (pv_spec_t *)_uri;
    if (uri_pv && (pv_get_spec_value(_m, uri_pv, &uri_val) == 0)) {
	if (uri_val.flags & PV_VAL_STR) {
	    if (uri_val.rs.len == 0 || uri_val.rs.s == NULL) {
		LM_ERR("missing uri value\n");
		return -1;
	    }
	} else {
	    LM_ERR("uri value is not string\n");
	    return -1;
	}
    } else {
	LM_ERR("failed to get uri value\n");
	return -1;
    }
    uri = uri_val.rs;

    value_pv = (pv_spec_t *)_value;
    if (value_pv && (pv_get_spec_value(_m, value_pv, &value_val) == 0)) {
	if (value_val.flags & PV_VAL_STR) {
	    if (value_val.rs.s == NULL) {
		LM_ERR("missing uri value\n");
		return -1;
	    }
	} else {
	    LM_ERR("uri value is not string\n");
	    return -1;
	}
    } else {
	LM_ERR("failed to get uri value\n");
	return -1;
    }
    value = value_val.rs;

    if (value.len == 0) {
	LM_ERR("hostpart of uri cannot be empty\n");
	return -1;
    }
    if (uri.len + value.len > MAX_URI_SIZE) {
	LM_ERR("resulting uri would be too large\n");
	return -1;
    }

    colon = strchr(uri.s, ':');
    if (colon == NULL) {
	LM_ERR("uri does not contain ':' character\n");
	return -1;
    }
    c = &(new_uri[0]);
    at = strchr(colon + 1, '@');
    if (at == NULL) {
	next = colon + 1;
    } else {
	next = at + 1;
    }
    append_str(c, uri.s, next - uri.s);
    host_len = strcspn(next, ":;?");
    append_str(c, value.s, value.len);
    strcpy(c, next + host_len);
    res_val.rs.len = uri.len + value.len - host_len;
    res_val.rs.s = &(new_uri[0]);

    LM_DBG("resulting uri: %.*s\n", res_val.rs.len, res_val.rs.s);
    res_val.flags = PV_VAL_STR;
    uri_pv->setf(_m, &uri_pv->pvp, (int)EQ_T, &res_val);

    return 1;
}
Exemple #27
0
/* quick: use cursor && don't search for "more info" */
static int
do_look(boolean quick, const struct nh_cmd_arg *arg)
{
    const char *out_str;
    const char *firstmatch;
    int i, ans = 0, objplur = 0, is_in;
    coord cc;   /* screen pos of unknown glyph */
    boolean save_verbose;       /* saved value of flags.verbose */
    boolean from_screen;        /* question from the screen */
    struct nh_desc_buf descbuf;
    struct obj *otmp;

    if (arg->argtype & CMD_ARG_OBJ) {
        from_screen = FALSE;
    } else if (quick || (arg->argtype & CMD_ARG_POS)) {
        from_screen = TRUE;     /* yes, we want to use the cursor */
    } else {
        i = ynq("Specify unknown object by cursor?");
        if (i == 'q')
            return 0;
        from_screen = (i == 'y');
    }

    if (from_screen) {
        cc.x = u.ux;
        cc.y = u.uy;
    } else {
        if (arg->argtype & CMD_ARG_OBJ) {
            static const char allowall[] = { ALL_CLASSES, 0 };
            out_str = simple_typename(getargobj(arg, allowall, "explain")->otyp);
        } else {
            out_str = getarglin(arg, "Specify what? (type the word)");
            if (out_str[0] == '\0' || out_str[0] == '\033')
                return 0;
        }

        /* the ability to specify symbols is gone: it is simply impossible to
           know how the window port is displaying things (tiles?) and even if
           charaters are used it may not be possible to type them (utf8) */

        checkfile(out_str, NULL, !(arg->argtype & CMD_ARG_OBJ), TRUE);
        return 0;
    }
    /* Save the verbose flag, we change it later. */
    save_verbose = flags.verbose;
    flags.verbose = flags.verbose && !quick;

    /* 
     * we're identifying from the screen.
     */
    do {
        /* Reset some variables. */
        firstmatch = NULL;
        objplur = 0;

        if (flags.verbose)
            pline("Please move the cursor to %s.", what_is_an_unknown_object);
        else
            pline("Pick an object.");

        ans = getargpos(arg, &cc, FALSE, what_is_an_unknown_object);
        if (ans == NHCR_CLIENT_CANCEL || cc.x < 0) {
            flags.verbose = save_verbose;
            if (flags.verbose)
                pline(quick ? "Never mind." : "Done.");
            return 0;   /* done */
        }
        flags.verbose = FALSE;  /* only print long question once */

        nh_describe_pos(cc.x, cc.y, &descbuf, &is_in);

        otmp = vobj_at(cc.x, cc.y);
        if (otmp && is_plural(otmp))
            objplur = 1;

        out_str = "";
        if (append_str(&out_str, descbuf.effectdesc, 0, 0))
            if (!firstmatch)
                firstmatch = descbuf.effectdesc;

        if (append_str(&out_str, descbuf.invisdesc, 0, 0))
            if (!firstmatch)
                firstmatch = descbuf.invisdesc;

        /* We already have a/an added by describe_mon; don't add it again,
           because that'll fail in cases like "Dudley's ghost" */
        if (append_str(&out_str, descbuf.mondesc, 1, 0))
            if (!firstmatch)
                firstmatch = descbuf.mondesc;

        if (append_str(&out_str, descbuf.objdesc, objplur, 0))
            if (!firstmatch)
                firstmatch = descbuf.objdesc;

        if (append_str(&out_str, descbuf.trapdesc, 0, 0))
            if (!firstmatch)
                firstmatch = descbuf.trapdesc;

        if (!descbuf.feature_described &&
            append_str(&out_str, descbuf.bgdesc, 0, is_in))
            if (!firstmatch)
                firstmatch = descbuf.bgdesc;

        /* Finally, print out our explanation. */
        if (firstmatch) {
            pline("%s.", msgupcasefirst(out_str));
            /* check the data file for information about this thing */
            if (firstmatch && ans != NHCR_CONTINUE &&
                (ans == NHCR_MOREINFO ||
                 ans == NHCR_MOREINFO_CONTINUE || !quick)) {
                checkfile(firstmatch, NULL, FALSE,
                          ans == NHCR_MOREINFO ||
                          ans == NHCR_MOREINFO_CONTINUE);
            }
        } else {
            pline("I've never heard of such things.");
        }
    } while (ans == NHCR_CONTINUE || ans == NHCR_MOREINFO_CONTINUE);

    flags.verbose = save_verbose;
    if (!quick && flags.verbose)
        pline("Done.");

    return 0;
}
Exemple #28
0
int push_on_network(struct sip_msg *msg, int net)
{
	str    body;
	struct sip_uri  uri;
	struct sms_msg  *sms_messg;
	struct to_body  *from;
	char   *p;
	int    len;
	int    mime;

	/* get the message's body
	 * anyhow we have to call this function, so let's do it at the beginning
	 * to force the parsing of all the headers - like this we avoid separate
	 * calls of parse_headers function for FROM, CONTENT_LENGTH, TO hdrs  */
	body.s = get_body( msg );
	if (body.s==0) {
		LM_ERR("failed to extract body from msg!\n");
		goto error;
	}

	/* content-length (if present) must be already parsed */
	if (!msg->content_length) {
		LM_ERR("no Content-Length header found!\n");
		goto error;
	}
	body.len = get_content_length( msg );

	/* parse the content-type header */
	if ( (mime=parse_content_type_hdr(msg))<1 ) {
		LM_ERR("failed to parse Content-Type header\n");
		goto error;
	}

	/* check the content-type value */
	if ( mime!=(TYPE_TEXT<<16)+SUBTYPE_PLAIN
	&& mime!=(TYPE_MESSAGE<<16)+SUBTYPE_CPIM ) {
		LM_ERR("invalid content-type for a message request! type found=%d\n",
				mime);
		goto error;
	}

	/* we try to get the user name (phone number) first from the RURI 
	   (in our case means from new_uri or from first_line.u.request.uri);
	   if it's missing there (like in requests generated by MSN MESSENGER),
	   we go for "to" header
	*/
	LM_DBG("string to get user from new_uri\n");
	if ( !msg->new_uri.s||parse_uri( msg->new_uri.s,msg->new_uri.len,&uri)
	|| !uri.user.len )
	{
		LM_DBG("string to get user from R_uri\n");
		if ( parse_uri( msg->first_line.u.request.uri.s,
		msg->first_line.u.request.uri.len ,&uri)||!uri.user.len )
		{
			LM_DBG("string to get user from To\n");
			if ( (!msg->to&&((parse_headers(msg,HDR_TO_F,0)==-1) ||
					!msg->to)) ||
				parse_uri( get_to(msg)->uri.s, get_to(msg)->uri.len, &uri)==-1
			|| !uri.user.len)
			{
				LM_ERR("unable to extract user name from RURI and To header!\n");
				goto error;
			}
		}
	}
	/* check the uri.user format = '+(inter code)(number)' */
	if (uri.user.len<2 || uri.user.s[0]!='+' || uri.user.s[1]<'1'
	|| uri.user.s[1]>'9') {
		LM_ERR("user tel number [%.*s] does not respect international format\n"
				,uri.user.len,uri.user.s);
		goto error;
	}

	/* parsing from header */
	if ( parse_from_header( msg )==-1 ) {
		LM_ERR("failed to get FROM header\n");
		goto error;
	}
	from = (struct to_body*)msg->from->parsed;

#if 0
	/* adds contact header into reply */
	if (add_contact(msg,&(uri.user))==-1) {
		LM_ERR("can't build contact for reply\n");
		goto error;
	}
#endif

	/*-------------BUILD AND FILL THE SMS_MSG STRUCTURE --------------------*/
	/* computes the amount of memory needed */
	len = SMS_HDR_BF_ADDR_LEN + from->uri.len
		+ SMS_HDR_AF_ADDR_LEN + body.len + SMS_FOOTER_LEN /*text to send*/
		+ from->uri.len /* from */
		+ uri.user.len-1 /* to user (without '+') */
		+ sizeof(struct sms_msg) ; /* the sms_msg structure */
	/* allocs a new sms_msg structure in shared memory */
	sms_messg = (struct sms_msg*)shm_malloc(len);
	if (!sms_messg) {
		LM_ERR("failed to get shm memory!\n");
		goto error;
	}
	p = (char*)sms_messg + sizeof(struct sms_msg);

	/* copy "from" into sms struct */
	sms_messg->from.len = from->uri.len;
	sms_messg->from.s = p;
	append_str(p,from->uri.s,from->uri.len);

	/* copy "to.user" - we have to strip out the '+' */
	sms_messg->to.len = uri.user.len-1;
	sms_messg->to.s = p;
	append_str(p,uri.user.s+1,sms_messg->to.len);

	/* copy (and composing) sms body */
	sms_messg->text.len = SMS_HDR_BF_ADDR_LEN + sms_messg->from.len
		+ SMS_HDR_AF_ADDR_LEN + body.len+SMS_FOOTER_LEN;
	sms_messg->text.s = p;
	append_str(p, SMS_HDR_BF_ADDR, SMS_HDR_BF_ADDR_LEN);
	append_str(p, sms_messg->from.s, sms_messg->from.len);
	append_str(p, SMS_HDR_AF_ADDR, SMS_HDR_AF_ADDR_LEN);
	append_str(p, body.s, body.len);
	append_str(p, SMS_FOOTER, SMS_FOOTER_LEN);

	if (*queued_msgs>MAX_QUEUED_MESSAGES)
		goto error;
	(*queued_msgs)++;

	if (write(net_pipes_in[net], &sms_messg, sizeof(sms_messg))!=
	sizeof(sms_messg) )
	{
		LM_ERR("error when writing for net %d to pipe [%d] : %s\n",
				net,net_pipes_in[net],strerror(errno) );
		shm_free(sms_messg);
		(*queued_msgs)--;
		goto error;
	}

	return 1;
 error:
	return -1;
}
Exemple #29
0
static void create_inf_file()
{
    char data[1024];
    char *ptr = data;
    DWORD dwNumberOfBytesWritten;
    HANDLE hf = CreateFile("c:\\test.inf", GENERIC_WRITE, 0, NULL,
                           CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    append_str(&ptr, "[Version]\n");
    append_str(&ptr, "Signature=\"$Chicago$\"\n");
    append_str(&ptr, "[CustInstDestSection]\n");
    append_str(&ptr, "49001=ProgramFilesDir\n");
    append_str(&ptr, "[ProgramFilesDir]\n");
    append_str(&ptr, "HKLM,\"Software\\Microsoft\\Windows\\CurrentVersion\",");
    append_str(&ptr, "\"ProgramFilesDir\",,\"%%24%%\\%%LProgramF%%\"\n");
    append_str(&ptr, "[section]\n");
    append_str(&ptr, "NotACustomDestination=Version\n");
    append_str(&ptr, "CustomDestination=CustInstDestSection\n");
    append_str(&ptr, "[Options.NTx86]\n");
    append_str(&ptr, "49001=ProgramFilesDir\n");
    append_str(&ptr, "InstallDir=%%49001%%\\%%DefaultAppPath%%\n");
    append_str(&ptr, "CustomHDestination=CustInstDestSection\n");
    append_str(&ptr, "[Strings]\n");
    append_str(&ptr, "DefaultAppPath=\"Application Name\"\n");
    append_str(&ptr, "LProgramF=\"Program Files\"\n");

    WriteFile(hf, data, ptr - data, &dwNumberOfBytesWritten, NULL);
    CloseHandle(hf);
}
Exemple #30
0
error_t
cvt_to_hyper(menu_t *mp, char *osroot, char *extra_args)
{
	const char *fcn = "cvt_to_hyper()";

	line_t *lp;
	entry_t *ent;
	size_t len, zfslen;

	char *newstr;
	char *osdev;

	char *title = NULL;
	char *findroot = NULL;
	char *bootfs = NULL;
	char *kernel = NULL;
	char *mod_kernel = NULL;
	char *module = NULL;

	char *kern_path = NULL;
	char *kern_bargs = NULL;

	int curdef, newdef;
	int kp_allocated = 0;
	int ret = BAM_ERROR;

	assert(osroot);

	BAM_DPRINTF((D_FUNC_ENTRY2, fcn, osroot, extra_args));

	/*
	 * First just check to verify osroot is a sane directory.
	 */
	if ((osdev = get_special(osroot)) == NULL) {
		bam_error(CANT_FIND_SPECIAL, osroot);
		return (BAM_ERROR);
	}

	free(osdev);

	/*
	 * While the effect is purely cosmetic, if osroot is "/" don't
	 * bother prepending it to any paths as they are constructed to
	 * begin with "/" anyway.
	 */
	if (strcmp(osroot, "/") == 0)
		osroot = "";

	/*
	 * Found the GRUB signature on the target partitions, so now get the
	 * default GRUB boot entry number from the menu.lst file
	 */
	curdef = atoi(mp->curdefault->arg);

	/* look for the first line of the matching boot entry */
	for (ent = mp->entries; ((ent != NULL) && (ent->entryNum != curdef));
	    ent = ent->next)
		;

	/* couldn't find it, so error out */
	if (ent == NULL) {
		bam_error(CANT_FIND_DEFAULT, curdef);
		goto abort;
	}

	/*
	 * We found the proper menu entry, so first we need to process the
	 * bootenv.rc file to look for boot options the hypervisor might need
	 * passed as kernel start options such as the console device and serial
	 * port parameters.
	 *
	 * If there's no bootenv.rc, it's not an issue.
	 */
	parse_bootenvrc(osroot);

	if (bootenv_rc_console != NULL)
		console_metal_to_hyper(bootenv_rc_console);

	if (bootenv_rc_serial[0] != NULL)
		(void) serial_metal_to_hyper("ttya-mode", bootenv_rc_serial[0]);

	if (bootenv_rc_serial[1] != NULL)
		(void) serial_metal_to_hyper("ttyb-mode", bootenv_rc_serial[1]);

	/*
	 * Now process the entry itself.
	 */
	for (lp = ent->start; lp != NULL; lp = lp->next) {
		/*
		 * Process important lines from menu.lst boot entry.
		 */
		if (lp->flags == BAM_TITLE) {
			title = alloca(strlen(lp->arg) + 1);
			(void) strcpy(title, lp->arg);
		} else if (strcmp(lp->cmd, "findroot") == 0) {
			findroot = alloca(strlen(lp->arg) + 1);
			(void) strcpy(findroot, lp->arg);
		} else if (strcmp(lp->cmd, "bootfs") == 0) {
			bootfs = alloca(strlen(lp->arg) + 1);
			(void) strcpy(bootfs, lp->arg);
		} else if (strcmp(lp->cmd, menu_cmds[MODULE_DOLLAR_CMD]) == 0) {
			module = alloca(strlen(lp->arg) + 1);
			(void) strcpy(module, lp->arg);
		} else if ((strcmp(lp->cmd,
		    menu_cmds[KERNEL_DOLLAR_CMD]) == 0) &&
		    (ret = cvt_metal_kernel(lp->arg, &kern_path)) != 0) {
			if (ret < 0) {
				ret = BAM_ERROR;
				bam_error(KERNEL_NOT_PARSEABLE, curdef);
			} else
				ret = BAM_NOCHANGE;

			goto abort;
		}

		if (lp == ent->end)
			break;
	}

	/*
	 * If findroot, module or kern_path are NULL, the boot entry is
	 * malformed.
	 */
	if (findroot == NULL) {
		bam_error(FINDROOT_NOT_FOUND, curdef);
		goto abort;
	}

	if (module == NULL) {
		bam_error(MODULE_NOT_PARSEABLE, curdef);
		goto abort;
	}

	if (kern_path == NULL) {
		bam_error(KERNEL_NOT_FOUND, curdef);
		goto abort;
	}

	/* assemble new kernel and module arguments from parsed values */
	if (console_dev != NULL) {
		kern_bargs = s_strdup(console_dev);

		if (serial_config[0] != NULL) {
			newstr = append_str(kern_bargs, serial_config[0], " ");
			free(kern_bargs);
			kern_bargs = newstr;
		}

		if (serial_config[1] != NULL) {
			newstr = append_str(kern_bargs, serial_config[1], " ");
			free(kern_bargs);
			kern_bargs = newstr;
		}
	}

	if ((extra_args != NULL) && (*extra_args != NULL)) {
		newstr = append_str(kern_bargs, extra_args, " ");
		free(kern_bargs);
		kern_bargs = newstr;
	}

	len = strlen(osroot) + strlen(XEN_MENU) + strlen(kern_bargs) +
	    WHITESPC(1) + 1;

	kernel = alloca(len);

	if (kern_bargs != NULL) {
		if (*kern_bargs != NULL)
			(void) snprintf(kernel, len, "%s%s %s", osroot,
			    XEN_MENU, kern_bargs);

		free(kern_bargs);
	} else {
		(void) snprintf(kernel, len, "%s%s", osroot, XEN_MENU);
	}

	/*
	 * Change the kernel directory from the metal version to that needed for
	 * the hypervisor.  Convert either "direct boot" path to the default
	 * path.
	 */
	if ((strcmp(kern_path, DIRECT_BOOT_32) == 0) ||
	    (strcmp(kern_path, DIRECT_BOOT_64) == 0)) {
		kern_path = HYPERVISOR_KERNEL;
	} else {
		newstr = modify_path(kern_path, METAL_KERNEL_DIR,
		    HYPER_KERNEL_DIR);
		free(kern_path);
		kern_path = newstr;
		kp_allocated = 1;
	}

	/*
	 * We need to allocate space for the kernel path (twice) plus an
	 * intervening space, possibly the ZFS boot string, and NULL,
	 * of course.
	 */
	len = (strlen(kern_path) * 2) + WHITESPC(1) + 1;
	zfslen = (zfs_boot ? (WHITESPC(1) + strlen(ZFS_BOOT)) : 0);

	mod_kernel = alloca(len + zfslen);
	(void) snprintf(mod_kernel, len, "%s %s", kern_path, kern_path);

	if (kp_allocated)
		free(kern_path);

	if (zfs_boot) {
		char *zfsstr = alloca(zfslen + 1);

		(void) snprintf(zfsstr, zfslen + 1, " %s", ZFS_BOOT);
		(void) strcat(mod_kernel, zfsstr);
	}

	/* shut off warning messages from the entry line parser */
	if (ent->flags & BAM_ENTRY_BOOTADM)
		ent->flags &= ~BAM_ENTRY_BOOTADM;

	BAM_DPRINTF((D_CVT_CMD_KERN_DOLLAR, fcn, kernel));
	BAM_DPRINTF((D_CVT_CMD_MOD_DOLLAR, fcn, mod_kernel));

	if ((newdef = add_boot_entry(mp, title, findroot, kernel, mod_kernel,
	    module, bootfs)) == BAM_ERROR)
		return (newdef);

	/*
	 * Now try to delete the current default entry from the menu and add
	 * the new hypervisor entry with the parameters we've setup.
	 */
	if (delete_boot_entry(mp, curdef, DBE_QUIET) == BAM_SUCCESS)
		newdef--;
	else
		bam_print(NEW_BOOT_ENTRY, title);

	/*
	 * If we successfully created the new entry, set the default boot
	 * entry to that entry and let the caller know the new menu should
	 * be written out.
	 */
	return (set_global(mp, menu_cmds[DEFAULT_CMD], newdef));

abort:
	if (ret != BAM_NOCHANGE)
		bam_error(HYPER_ABORT, ((*osroot == NULL) ? "/" : osroot));

	return (ret);
}