Пример #1
0
int HttpMessage::getContentLength() const
{
    return getHeader(http::ContentLength).getValue().toInt();
}
Пример #2
0
void AmB2BSession::relaySip(const AmSipRequest& orig, const AmSipReply& reply)
{
  string content_type = getHeader(reply.hdrs,"Content-Type");
  dlg.reply(orig,reply.code,reply.reason,content_type,reply.body);
}
Пример #3
0
std::shared_ptr<const contentDispositionField> bodyPartAttachment::getContentDisposition() const
{
	return std::dynamic_pointer_cast<const contentDispositionField>(getHeader()->
			findField(fields::CONTENT_DISPOSITION));
}
Пример #4
0
void AmSIPRegistration::onSipReply(const AmSipRequest& req,
				   const AmSipReply& reply, 
				   AmBasicSipDialog::Status old_dlg_status)
{
  if ((seh!=NULL) && seh->onSipReply(req,reply, old_dlg_status))
    return;

  if (reply.code>=200)
    waiting_result = false;

  if ((reply.code>=200)&&(reply.code<300)) {

    string contacts = reply.contact;
    if (contacts.empty()) 
      contacts = getHeader(reply.hdrs, "Contact", "m", true);

    if (unregistering) {
      DBG("received positive reply to De-REGISTER\n");

      active = false;
      remove = true;
      if (!contacts.length()) {
	DBG("no contacts registered any more\n");
      }
      if (sess_link.length()) {
	AmSessionContainer::instance()->
	  postEvent(sess_link,
		    new SIPRegistrationEvent(SIPRegistrationEvent::RegisterNoContact,
					     req.from_tag,
					     reply.code, reply.reason));
      }

    } else {
      DBG("positive reply to REGISTER!\n");

      size_t end  = 0;
      string local_contact_hdr = dlg.getContactHdr();
      local_contact.parse_contact(local_contact_hdr, (size_t)0, end);
      local_contact.dump();

      bool found = false;

      if (!contacts.length()) {
	// should not happen - positive reply without contact
	DBG("no contacts registered any more\n");
	active = false;
	remove = true;
      } else {
	end = 0;
	while (!found) {
	  if (contacts.length() == end)
	    break;

	  if (!server_contact.parse_contact(contacts, end, end)) {
	    ERROR("while parsing contact\n");
	    break;
	  }
	  server_contact.dump();

	  if (server_contact.isEqual(local_contact)) {
	    DBG("contact found\n");
	    found = active = true;

	    if (str2i(server_contact.params["expires"], reg_expires)) {
	      ERROR("could not extract expires value, default to 300.\n");
	      reg_expires = 300;
	    }
	    DBG("got an expires of %d\n", reg_expires);
	    // save TS
	    reg_begin = time(0);

	    if (sess_link.length()) {
	      DBG("posting SIPRegistrationEvent to '%s'\n", sess_link.c_str());
	      AmSessionContainer::instance()->
		postEvent(sess_link,
			  new SIPRegistrationEvent(SIPRegistrationEvent::RegisterSuccess,
						   req.from_tag,
						   reply.code, reply.reason));
	    }
	    break;
	  }
	}
      }
      if (!found) {
	if (sess_link.length()) {
	  AmSessionContainer::instance()->
	    postEvent(sess_link,
		      new SIPRegistrationEvent(SIPRegistrationEvent::RegisterNoContact,
					       req.from_tag,
					       reply.code, reply.reason));
	}
	DBG("no matching Contact - deregistered.\n");
	active = false;
	remove = true;
      }
    }
		
  } else if (reply.code >= 300) {
    DBG("Registration failed.\n");
    if (sess_link.length()) {
      AmSessionContainer::instance()->
	postEvent(sess_link,
		  new SIPRegistrationEvent(SIPRegistrationEvent::RegisterFailed,
					   req.from_tag,
					   reply.code, reply.reason));
    }
    active = false;
    remove = true;		
  }
}
Пример #5
0
static EjsVar *getRequestVar(void *handle, int field)
{
    switch (field) {
    case ES_ejs_web_Request_accept:
        return createString(ejs, getHeader(handle, "HTTP_ACCEPT"));

    case ES_ejs_web_Request_acceptCharset:
        return createString(ejs, getHeader(handle, "HTTP_ACCEPT_CHARSET"));

    case ES_ejs_web_Request_acceptEncoding:
        return createString(ejs, getHeader(handle, "HTTP_ACCEPT_ENCODING"));

    case ES_ejs_web_Request_authAcl:
    case ES_ejs_web_Request_authGroup:
    case ES_ejs_web_Request_authUser:
        return (EjsVar*) ejs->undefinedValue;

    case ES_ejs_web_Request_authType:
        return createString(ejs, getHeader(handle, "HTTP_AUTH_TYPE"));

#if TODO
    case ES_ejs_web_Request_connection:
        return createString(ejs, req->connection);
#endif

    case ES_ejs_web_Request_contentLength:
        return (EjsVar*) ejsCreateNumber(ejs, contentLength);

    case ES_ejs_web_Request_cookies:
        if (cookie) {
            return (EjsVar*) ejsCreateCookies(ejs);
        } else {
            return ejs->nullValue;
        }
        break;

    case ES_ejs_web_Request_extension:
        return createString(ejs, ext);

    case ES_ejs_web_Request_files:
        return (EjsVar*) ejs->undefinedValue;

    case ES_ejs_web_Request_headers:
        return (EjsVar*) createHeaderObject(ejs, requestHeaders);

    case ES_ejs_web_Request_hostName:
        return createString(ejs, getHeader(handle, "HTTP_HOST"));

    case ES_ejs_web_Request_method:
        return createString(ejs, getHeader(handle, "REQUEST_METHOD"));

    case ES_ejs_web_Request_mimeType:
        return createString(ejs, getHeader(handle, "CONTENT_TYPE"));

    case ES_ejs_web_Request_pathInfo:
        return createString(ejs, getHeader(handle, "PATH_INFO"));

    case ES_ejs_web_Request_pathTranslated:
        return createString(ejs, getHeader(handle, "PATH_TRANSLATED"));

    case ES_ejs_web_Request_pragma:
        return createString(ejs, getHeader(handle, "HTTP_PRAGMA"));

    case ES_ejs_web_Request_query:
        return createString(ejs, getHeader(handle, "QUERY_STRING"));

    case ES_ejs_web_Request_originalUri:
        return createString(ejs, getHeader(handle, "REQUEST_URI"));

    case ES_ejs_web_Request_referrer:
        return createString(ejs, getHeader(handle, "HTTP_REFERRER"));

    case ES_ejs_web_Request_remoteAddress:
        return createString(ejs, getHeader(handle, "REMOTE_ADDR"));

    case ES_ejs_web_Request_remoteHost:
#if BLD_FEATURE_REVERSE_DNS && BLD_UNIX_LIKE
    {
        /*
         *  This feature has denial of service risks. Doing a reverse DNS will be slower,
         *  and can potentially hang the web server. Use at your own risk!!  Not supported for windows.
         */
        struct addrinfo *result;
        char            name[MPR_MAX_STRING];
        int             rc;

        if (getaddrinfo(remoteIpAddr, NULL, NULL, &result) == 0) {
            rc = getnameinfo(result->ai_addr, sizeof(struct sockaddr), name, sizeof(name), NULL, 0, NI_NAMEREQD);
            freeaddrinfo(result);
            if (rc == 0) {
                return createString(ejs, name);
            }
        }
    }
#endif
    return createString(ejs, getHeader(handle, "REMOTE_ADDR"));

    case ES_ejs_web_Request_sessionID:
        return createString(ejs, web->session ? web->session->id : "");

    case ES_ejs_web_Request_url:
        return createString(ejs, uri);

    case ES_ejs_web_Request_userAgent:
        return createString(ejs, getHeader(handle, "HTTP_USER_AGENT"));
    }

    ejsThrowOutOfBoundsError(ejs, "Bad property slot reference");
    return 0;
}
Пример #6
0
/*
 * Update the read/write status of one or more pages.
 */
static void updatePages(Object* classLoader, void* mem, int direction)
{
    LinearAllocHdr* pHdr = getHeader(classLoader);
    dvmLockMutex(&pHdr->lock);

    /* make sure we have the right region */
    assert(mem >= (void*) pHdr->mapAddr &&
           mem < (void*) (pHdr->mapAddr + pHdr->curOffset));

    u4* pLen = getBlockHeader(mem);
    u4 len = *pLen & LENGTHFLAG_MASK;
    int firstPage, lastPage;

    firstPage = ((u1*)pLen - (u1*)pHdr->mapAddr) / SYSTEM_PAGE_SIZE;
    lastPage = ((u1*)mem - (u1*)pHdr->mapAddr + (len-1)) / SYSTEM_PAGE_SIZE;
    LOGVV("--- updating pages %d-%d (%d)", firstPage, lastPage, direction);

    int i, cc;

    /*
     * Update individual pages.  We could do some sort of "lazy update" to
     * combine mprotect calls, but that's almost certainly more trouble
     * than it's worth.
     */
    for (i = firstPage; i <= lastPage; i++) {
        if (direction < 0) {
            /*
             * Trying to mark read-only.
             */
            if (i == firstPage) {
                if ((*pLen & LENGTHFLAG_RW) == 0) {
                    ALOGW("Double RO on %p", mem);
                    dvmAbort();
                } else
                    *pLen &= ~LENGTHFLAG_RW;
            }

            if (pHdr->writeRefCount[i] == 0) {
                ALOGE("Can't make page %d any less writable", i);
                dvmAbort();
            }
            pHdr->writeRefCount[i]--;
            if (pHdr->writeRefCount[i] == 0) {
                LOGVV("---  prot page %d RO", i);
                cc = mprotect(pHdr->mapAddr + SYSTEM_PAGE_SIZE * i,
                        SYSTEM_PAGE_SIZE, PROT_READ);
                assert(cc == 0);
            }
        } else {
            /*
             * Trying to mark writable.
             */
            if (pHdr->writeRefCount[i] >= 32767) {
                ALOGE("Can't make page %d any more writable", i);
                dvmAbort();
            }
            if (pHdr->writeRefCount[i] == 0) {
                LOGVV("---  prot page %d RW", i);
                cc = mprotect(pHdr->mapAddr + SYSTEM_PAGE_SIZE * i,
                        SYSTEM_PAGE_SIZE, PROT_READ | PROT_WRITE);
                assert(cc == 0);
            }
            pHdr->writeRefCount[i]++;

            if (i == firstPage) {
                if ((*pLen & LENGTHFLAG_RW) != 0) {
                    ALOGW("Double RW on %p", mem);
                    dvmAbort();
                } else
                    *pLen |= LENGTHFLAG_RW;
            }
        }
    }

    dvmUnlockMutex(&pHdr->lock);
}
bool UnixSocketAdapter::receive(AmSipReply &reply)
{
  string tmp_str;
  string cseq_str;

#ifdef OpenSER
  unsigned int mi_res_code;
  string mi_res_msg;
#endif

  if (cacheMsg() < 0)
    goto failure;

#ifdef OpenSER
  SAFECTRLCALL1(getParam,tmp_str);
    
  DBG("MI response from OpenSER: %s\n",tmp_str.c_str());
  if( parse_return_code(tmp_str.c_str(),// res_code_str,
      mi_res_code, mi_res_msg) == -1 ){
    ERROR("while parsing MI return code from OpenSER.\n");
    goto failure;
  }

  if (mi_res_code != 200) {
      ERROR("MI response from OpenSER\n");
      goto failure;
  }

  SAFECTRLCALL1(getParam,tmp_str);
  DBG("SIP response from OpenSER: %s\n",tmp_str.c_str());
  if( parse_return_code(tmp_str.c_str(),// res_code_str,
      reply.code, reply.reason) == -1 ){
    ERROR("while parsing return code from Ser.\n");
    goto failure;
  }
#else
  SAFECTRLCALL1(getParam,tmp_str);

  DBG("response from Ser: %s\n",tmp_str.c_str());
  if( parse_return_code(tmp_str.c_str(),// res_code_str,
      reply.code,reply.reason) == -1 ){
    ERROR("while parsing return code from Ser.\n");
    goto failure;
  }
#endif

  /* Parse complete response:
   *
   *   [next_request_uri->cmd.from_uri]CRLF
   *   [next_hop->cmd.next_hop]CRLF
   *   [route->cmd.route]CRLF
   *   ([headers->n_cmd.hdrs]CRLF)*
   *   CRLF
   *   ([body->body]CRLF)*
   */
	
  SAFECTRLCALL1(getParam,reply.next_request_uri);
  SAFECTRLCALL1(getParam,reply.next_hop);
  SAFECTRLCALL1(getParam,reply.route);

  SAFECTRLCALL1(getLines,reply.hdrs);
  SAFECTRLCALL1(getLines,reply.body);

  if(reply.hdrs.empty()){
    ERROR("reply is missing headers: <%i %s>\n",
	  reply.code,reply.reason.c_str());
    goto failure;
  }

  reply.local_tag = getHeader(reply.hdrs,"From");
  reply.local_tag = extract_tag(reply.local_tag);

  reply.remote_tag = getHeader(reply.hdrs,"To");
  reply.remote_tag = extract_tag(reply.remote_tag);

  cseq_str   = getHeader(reply.hdrs,"CSeq");
  if(str2i(cseq_str,reply.cseq)){
    ERROR("could not parse CSeq header\n");
    goto failure;
  }

  reply.content_type = getHeader(reply.hdrs,"Content-Type");

  return true;
failure:
  //cleanup(ctrl);
  return false;
}
Пример #8
0
std::string HttpHeaders::transferEncoding()
{
	return mol::str::tolower(getHeader("Transfer-Encoding"));
}
Пример #9
0
std::string HttpHeaders::contentType()
{
	return mol::str::tolower(getHeader("Content-Type"));
}
Пример #10
0
/*
 *	the thing that gets called...
 */
__declspec(dllexport) DWORD HttpExtensionProc(EXTENSION_CONTROL_BLOCK *p)
{
   HTTPRequest *req;
   HTTPResponse *resp = NULL;
   WOURLComponents wc = WOURLComponents_Initializer;
   const char *reqerr;
   const char *qs;
   char *script_name;
   char *server_protocol;
   char *uri;
   WOURLError urlerr;

   if (!adaptorEnabled)
   {
      WOLog(WO_ERR, "WebObjects adaptor disabled.");
      return HSE_STATUS_ERROR;
   }
   
   /*
    *	extract WebObjects request components from URI
    */
   script_name = getHeader(p, CGI_SCRIPT_NAME);
   uri = WOMALLOC(strlen(p->lpszPathInfo) + strlen(script_name) + 1);
   strcpy(uri, script_name);
   strcat(uri, p->lpszPathInfo);
   WOLog(WO_INFO,"<WebObjects ISAPI> new request: %s", uri);
   WOFREE(script_name);

   urlerr = WOParseApplicationName(&wc, uri);

   if (urlerr != WOURLOK) {
      const char *_urlerr;
      _urlerr = WOURLstrerror(urlerr);
      WOLog(WO_INFO,"URL Parsing Error: %s", _urlerr);
      if (urlerr == WOURLInvalidApplicationName) {
          if (ac_authorizeAppListing(&wc)) {
              resp = WOAdaptorInfo(NULL, &wc);
              WOFREE(uri); /* this has to be freed before a return in this function */
              return die_resp(p, resp);
          } else {
              WOFREE(uri); /* this has to be freed before a return in this function */
              return die(p, _urlerr, HTTP_NOT_FOUND);
          }
      }
      WOFREE(uri); /* this has to be freed before a return in this function */
      return die(p, _urlerr, HTTP_BAD_REQUEST);
   }

   /*
    *	build the request...
    */
   req = req_new(p->lpszMethod, NULL);

   /*
    *	validate the method
    */
   reqerr = req_validateMethod(req);
   if (reqerr) {
      req_free(req);
      WOFREE(uri); /* this has to be freed before a return in this function */
      return die(p,reqerr, HTTP_BAD_REQUEST);
   }

   /*
    *	get the headers....
    */
   copyHeaders(p, req);

   /*
    *	get form data if any
    *   assume that POSTs with content length will be reformatted to GETs later
    */
   req->content_length = p->cbTotalBytes;
   if (req->content_length > 0)
   {
      char *buffer = WOMALLOC(req->content_length);

      if (p->cbAvailable > 0)
         memcpy(buffer, p->lpbData, p->cbAvailable);

      /*
       * IIS has a weird (or is it convenient?) data queuing mechanism...
       */
      if (req->content_length > p->cbAvailable) {
          DWORD len;
          DWORD totalLength, fetchedLength;

          len = req->content_length - p->cbAvailable;
          totalLength = len;
          fetchedLength = 0;

          while (fetchedLength < totalLength) {
              len = totalLength - fetchedLength;

              if (p->ReadClient (p->ConnID,buffer + p->cbAvailable + fetchedLength, &len) != TRUE) {
                  WOFREE(buffer);
                  req_free(req);
                  return die(p, INV_FORM_DATA, HTTP_BAD_REQUEST);
              }

              fetchedLength += len;
          }
      }
      req->content = buffer;
      if (req_HeaderForKey(req, CONTENT_LENGTH) == NULL) {
         char *length;
         length = (char *)WOMALLOC(32);
         if (length)
         {
            sprintf(length,"%d",req->content_length);
            req_addHeader(req, CONTENT_LENGTH, length, STR_FREEVALUE);
         }
         if (p->lpszContentType != NULL)
            req_addHeader(req, CONTENT_TYPE, p->lpszContentType, 0);
      }
   }

   /* Always get the query string */
   qs = p->lpszQueryString;
   wc.queryString.start = qs;
   wc.queryString.length = qs ? strlen(qs) : 0;

   /*
    *	message the application & collect the response
    *
    *	note that handleRequest free()'s the 'req' for us
    */
   if (resp == NULL) {
      /* if no error so far... */
      req->api_handle = p;			/* stash this... */
      server_protocol = getHeader(p, CGI_SERVER_PROTOCOL);
      resp = tr_handleRequest(req, uri, &wc, server_protocol, NULL);
      WOFREE(server_protocol);
   }

   if (resp != NULL) {
      sendResponse(p, resp);
      resp_free(resp);
   }

   WOFREE(uri); /* this has to be freed before a return in this function */
   req_free(req);
#if defined(FINDLEAKS)
      showleaks();
#endif
   return HSE_STATUS_SUCCESS;
}
Пример #11
0
std::string HttpHeaders::contentEncoding()
{
	return mol::str::tolower(getHeader("Content-Encoding"));
}
Пример #12
0
void notifyProfileStateChanged(bt_addr_struct *bd_addr, PROFILE_enum id, ProfileStatus state)
{
	dev_op             *devOp = getDeviceOpList(bd_addr);
	int                 old_state = getProfileState(bd_addr, id);
    int                 new_state = state;
	profile_op_queue_t *opCur = NULL;
	profile_op_queue_t *opNext = NULL;
	
	if(devOp == NULL)
	{
		return;
	}

	ALOGI("%s addr:[0x%lX:0x%X:0x%X], profile[%d], old[%d] ==> new[%d]!\n",
		  __FUNCTION__, bd_addr->lap, bd_addr->uap, bd_addr->nap, id, old_state, new_state);
	setProfileState(bd_addr, id, new_state);
	if(isCurrentDevice(bd_addr))
	{
	    int state = PROFILE_STATE_DISCONNECTED;

		if(new_state == PROFILE_STATE_CONNECTED || new_state == PROFILE_STATE_DISCONNECTED)
		{
		    setBusy(bd_addr, 0);				
			if(!isEmpty((btmtk_list_header_struct **)&devOp->op_list))
			{
			    opCur = (profile_op_queue_t *)getHeader((btmtk_list_header_struct **)&devOp->op_list);
				if(opCur->node.op == PROFILE_OP_CONNECT)
				{
					state = getProfileState(bd_addr, opCur->node.profile_id);
					if(state == PROFILE_STATE_DISCONNECTED)
				    	connect_profile_int(bd_addr, opCur->node.profile_id);
				}
				else if(opCur->node.op == PROFILE_OP_DISCONNECT)
				{
				    state = getProfileState(bd_addr, opCur->node.profile_id);
					if(state == PROFILE_STATE_CONNECTED)
						disconnect_profile_int(bd_addr, opCur->node.profile_id);
					else if(state == PROFILE_STATE_DISCONNECTED)
					{
						PROFILE_enum profile_id = opCur->node.profile_id;
						ProfileOpType profile_op = opCur->node.op;
						
						removeOp(bd_addr, profile_id, profile_op);
						notifyProfileStateChanged(bd_addr, profile_id, PROFILE_STATE_DISCONNECTED);
						return;
					}
				}
				removeOp(bd_addr, opCur->node.profile_id, opCur->node.op);
			}
		}
	}
	else
	{
		removeAll((btmtk_list_header_struct **)&devOp->op_list);
		if(new_state == PROFILE_STATE_CONNECTED || new_state == PROFILE_STATE_DISCONNECTED)
		{
		    setBusy(bd_addr, 0);
		}
	}
	ProfileStateChangedCB(bd_addr, id, new_state);
}
Пример #13
0
void SkXMLStreamWriter::writeHeader() {
    const char* header = getHeader();
    fStream.write(header, strlen(header));
    fStream.newline();
}
Пример #14
0
void DSMFactory::runMonitorAppSelect(const AmSipRequest& req, string& start_diag, 
				     map<string, string>& vars) {
#define FALLBACK_OR_EXCEPTION(code, reason)				\
  if (MonSelectFallback.empty()) {					\
    throw AmSession::Exception(code, reason);				\
  } else {								\
    DBG("falling back to '%s'\n", MonSelectFallback.c_str());		\
    start_diag = MonSelectFallback;					\
    return;								\
  }

#ifdef USE_MONITORING
      if (NULL == MONITORING_GLOBAL_INTERFACE) {
	ERROR("using $(mon_select) but monitoring not loaded\n");
	FALLBACK_OR_EXCEPTION(500, "Internal Server Error");
      }

      AmArg di_args, ret;
      if (MonSelectCaller != MonSelect_NONE) {
	AmUriParser from_parser;
	if (MonSelectCaller == MonSelect_FROM)
	  from_parser.uri = req.from_uri;
	else {
	  size_t end;
	  string pai = getHeader(req.hdrs, SIP_HDR_P_ASSERTED_IDENTITY, true);
	  if (!from_parser.parse_contact(pai, 0, end)) {
	    WARN("Failed to parse " SIP_HDR_P_ASSERTED_IDENTITY " '%s'\n",
		  pai.c_str());
	    FALLBACK_OR_EXCEPTION(500, "Internal Server Error");
	  }
	}

	if (!from_parser.parse_uri()) {
	  DBG("failed to parse caller uri '%s'\n", from_parser.uri.c_str());
	  FALLBACK_OR_EXCEPTION(500, "Internal Server Error");
	}
	
	AmArg caller_filter;
	caller_filter.push("caller");
	caller_filter.push(from_parser.uri_user);
	DBG(" && looking for caller=='%s'\n", from_parser.uri_user.c_str());
	di_args.push(caller_filter);
      }


      if (MonSelectCallee != MonSelect_NONE) {
	AmArg callee_filter;
	callee_filter.push("callee");
	if (MonSelectCallee == MonSelect_RURI)
	  callee_filter.push(req.user);
	else {
	  AmUriParser to_parser;
	  size_t end;
	  if (!to_parser.parse_contact(req.to, 0, end)) {
	    ERROR("Failed to parse To '%s'\n", req.to.c_str());
	    FALLBACK_OR_EXCEPTION(500, "Internal Server Error");
	  }
	  if (!to_parser.parse_uri()) {
	    DBG("failed to parse callee uri '%s'\n", to_parser.uri.c_str());
	    FALLBACK_OR_EXCEPTION(500, "Internal Server Error");
	  }
	  callee_filter.push(to_parser.uri_user);
	}
	  
	DBG(" && looking for callee=='%s'\n", req.user.c_str());
	di_args.push(callee_filter);
      }
      // apply additional filters
      if (MonSelectFilters.size()) {
	string app_params = getHeader(req.hdrs, PARAM_HDR);
	for (vector<string>::iterator it = 
	       MonSelectFilters.begin(); it != MonSelectFilters.end(); it++) {
	  AmArg filter;
	  filter.push(*it); // avp name
	  string app_param_val = get_header_keyvalue(app_params, *it);
	  filter.push(app_param_val);
	  di_args.push(filter);
	  DBG(" && looking for %s=='%s'\n", it->c_str(), app_param_val.c_str());
	}
      }

      MONITORING_GLOBAL_INTERFACE->invoke("listByFilter",di_args,ret);
      
      if ((ret.getType()!=AmArg::Array)||
	  !ret.size()) {
	DBG("call info not found. caller uri %s, r-uri %s\n", 
	     req.from_uri.c_str(), req.r_uri.c_str());
	FALLBACK_OR_EXCEPTION(500, "Internal Server Error");
      }

      AmArg sess_id, sess_params;
      if (ret.size()>1) {
	DBG("multiple call info found - picking the first one\n");
      }
      const char* session_id = ret.get(0).asCStr();
      sess_id.push(session_id);
      MONITORING_GLOBAL_INTERFACE->invoke("get",sess_id,sess_params);
      
      if ((sess_params.getType()!=AmArg::Array)||
	  !sess_params.size() ||
	  sess_params.get(0).getType() != AmArg::Struct) {
	INFO("call parameters not found. caller uri %s, r-uri %s, id %s\n", 
	     req.from_uri.c_str(), req.r_uri.c_str(), ret.get(0).asCStr());
	FALLBACK_OR_EXCEPTION(500, "Internal Server Error");
      }

      AmArg& sess_dict = sess_params.get(0);
      if (sess_dict.hasMember("app")) {
	start_diag = sess_dict["app"].asCStr();
	DBG("selected application '%s' for session\n", start_diag.c_str());
      } else {
	ERROR("selected session params don't contain 'app'\n");
	FALLBACK_OR_EXCEPTION(500, "Internal Server Error");
      }
      AmArg2DSMStrMap(sess_dict["appParams"], vars);
      vars["mon_session_record"] = session_id;
	
#else
      ERROR("using $(mon_select) for dsm application, "
	    "but compiled without monitoring support!\n");
      throw AmSession::Exception(500, "Internal Server Error");
#endif

#undef FALLBACK_OR_EXCEPTION
}
Пример #15
0
void HttpRequest::readHeader(QTcpSocket& socket) {
#ifdef SUPERVERBOSE
    //qDebug("HttpRequest: read header");
#endif
    int toRead=maxSize-currentSize+1; // allow one byte more to be able to detect overflow
    QByteArray newData=socket.readLine(toRead).trimmed();
    currentSize+=newData.size();
    int colon=newData.indexOf(':');
    if (colon>0)  {
        // Received a line with a colon - a header
        currentHeader=newData.left(colon);
        QByteArray value=newData.mid(colon+1).trimmed();
        headers.insert(currentHeader,value);
#ifdef SUPERVERBOSE
        //qDebug("HttpRequest: received header %s: %s",currentHeader.data(),value.data());
#endif
    }
    else if (!newData.isEmpty()) {
        // received another line - belongs to the previous header
#ifdef SUPERVERBOSE
        //qDebug("HttpRequest: read additional line of header");
#endif
        // Received additional line of previous header
        if (headers.contains(currentHeader)) {
            headers.insert(currentHeader,headers.value(currentHeader)+" "+newData);
        }
    }
    else {
        // received an empty line - end of headers reached
#ifdef SUPERVERBOSE
        //qDebug("HttpRequest: headers completed");
#endif
        // Empty line received, that means all headers have been received
        // Check for multipart/form-data
        QByteArray contentType=headers.value("Content-Type");
        if (contentType.startsWith("multipart/form-data")) {
            int posi=contentType.indexOf("boundary=");
            if (posi>=0) {
                boundary=contentType.mid(posi+9);
            }
        }
        QByteArray contentLength=getHeader("Content-Length");
        if (!contentLength.isEmpty()) {
            expectedBodySize=contentLength.toInt();
        }
        if (expectedBodySize==0) {
#ifdef SUPERVERBOSE
            //qDebug("HttpRequest: expect no body");
#endif
            status=complete;
        }
        else if (boundary.isEmpty() && expectedBodySize+currentSize>maxSize) {
            qWarning("HttpRequest: expected body is too large");
            status=abort;
        }
        else if (!boundary.isEmpty() && expectedBodySize>maxMultiPartSize) {
            qWarning("HttpRequest: expected multipart body is too large");
            status=abort;
        }
        else {
#ifdef SUPERVERBOSE
            //qDebug("HttpRequest: expect %i bytes body",expectedBodySize);
#endif
            status=waitForBody;
        }
    }
}
Пример #16
0
std::string HttpHeaders::connection()
{
	return mol::str::tolower(getHeader("Connection"));
}
Пример #17
0
/*
 * Allocate "size" bytes of storage, associated with a particular class
 * loader.
 *
 * It's okay for size to be zero.
 *
 * We always leave "curOffset" pointing at the next place where we will
 * store the header that precedes the returned storage.
 *
 * This aborts the VM on failure, so it's not necessary to check for a
 * NULL return value.
 */
void* dvmLinearAlloc(Object* classLoader, size_t size)
{
    LinearAllocHdr* pHdr = getHeader(classLoader);
    int startOffset, nextOffset;
    int lastGoodOff, firstWriteOff, lastWriteOff;

#ifdef DISABLE_LINEAR_ALLOC
    return calloc(1, size);
#endif

    LOGVV("--- LinearAlloc(%p, %d)", classLoader, size);

    /*
     * What we'd like to do is just determine the new end-of-alloc size
     * and atomic-swap the updated value in.  The trouble is that, the
     * first time we reach a new page, we need to call mprotect() to
     * make the page available, and we don't want to call mprotect() on
     * every allocation.  The troubled situation is:
     *  - thread A allocs across a page boundary, but gets preempted
     *    before mprotect() completes
     *  - thread B allocs within the new page, and doesn't call mprotect()
     */
    dvmLockMutex(&pHdr->lock);

    startOffset = pHdr->curOffset;
    assert(((startOffset + HEADER_EXTRA) & (BLOCK_ALIGN-1)) == 0);

    /*
     * Compute the new offset.  The old offset points at the address where
     * we will store the hidden block header, so we advance past that,
     * add the size of data they want, add another header's worth so we
     * know we have room for that, and round up to BLOCK_ALIGN.  That's
     * the next location where we'll put user data.  We then subtract the
     * chunk header size off so we're back to the header pointer.
     *
     * Examples:
     *   old=12 size=3 new=((12+(4*2)+3+7) & ~7)-4 = 24-4 --> 20
     *   old=12 size=5 new=((12+(4*2)+5+7) & ~7)-4 = 32-4 --> 28
     */
    nextOffset = ((startOffset + HEADER_EXTRA*2 + size + (BLOCK_ALIGN-1))
                    & ~(BLOCK_ALIGN-1)) - HEADER_EXTRA;
    LOGVV("--- old=%d size=%d new=%d", startOffset, size, nextOffset);

    if (nextOffset > pHdr->mapLength) {
        /*
         * We don't have to abort here.  We could fall back on the system
         * malloc(), and have our "free" call figure out what to do.  Only
         * works if the users of these functions actually free everything
         * they allocate.
         */
        ALOGE("LinearAlloc exceeded capacity (%d), last=%d",
            pHdr->mapLength, (int) size);
        dvmAbort();
    }

    /*
     * Round up "size" to encompass the entire region, including the 0-7
     * pad bytes before the next chunk header.  This way we get maximum
     * utility out of "realloc", and when we're doing ENFORCE_READ_ONLY
     * stuff we always treat the full extent.
     */
    size = nextOffset - (startOffset + HEADER_EXTRA);
    LOGVV("--- (size now %d)", size);

    /*
     * See if we are starting on or have crossed into a new page.  If so,
     * call mprotect on the page(s) we're about to write to.  We have to
     * page-align the start address, but don't have to make the length a
     * SYSTEM_PAGE_SIZE multiple (but we do it anyway).
     *
     * Note that "startOffset" is not the last *allocated* byte, but rather
     * the offset of the first *unallocated* byte (which we are about to
     * write the chunk header to).  "nextOffset" is similar.
     *
     * If ENFORCE_READ_ONLY is enabled, we have to call mprotect even if
     * we've written to this page before, because it might be read-only.
     */
    lastGoodOff = (startOffset-1) & ~(SYSTEM_PAGE_SIZE-1);
    firstWriteOff = startOffset & ~(SYSTEM_PAGE_SIZE-1);
    lastWriteOff = (nextOffset-1) & ~(SYSTEM_PAGE_SIZE-1);
    LOGVV("---  lastGood=0x%04x firstWrite=0x%04x lastWrite=0x%04x",
        lastGoodOff, firstWriteOff, lastWriteOff);
    if (lastGoodOff != lastWriteOff || ENFORCE_READ_ONLY) {
        int cc, start, len;

        start = firstWriteOff;
        assert(start <= nextOffset);
        len = (lastWriteOff - firstWriteOff) + SYSTEM_PAGE_SIZE;

        LOGVV("---    calling mprotect(start=%d len=%d RW)", start, len);
        cc = mprotect(pHdr->mapAddr + start, len, PROT_READ | PROT_WRITE);
        if (cc != 0) {
            ALOGE("LinearAlloc mprotect (+%d %d) failed: %s",
                start, len, strerror(errno));
            /* we're going to fail soon, might as do it now */
            dvmAbort();
        }
    }

    /* update the ref counts on the now-writable pages */
    if (ENFORCE_READ_ONLY) {
        int i, start, end;

        start = firstWriteOff / SYSTEM_PAGE_SIZE;
        end = lastWriteOff / SYSTEM_PAGE_SIZE;

        LOGVV("---  marking pages %d-%d RW (alloc %d at %p)",
            start, end, size, pHdr->mapAddr + startOffset + HEADER_EXTRA);
        for (i = start; i <= end; i++)
            pHdr->writeRefCount[i]++;
    }

    /* stow the size in the header */
    if (ENFORCE_READ_ONLY)
        *(u4*)(pHdr->mapAddr + startOffset) = size | LENGTHFLAG_RW;
    else
        *(u4*)(pHdr->mapAddr + startOffset) = size;

    /*
     * Update data structure.
     */
    pHdr->curOffset = nextOffset;

    dvmUnlockMutex(&pHdr->lock);
    return pHdr->mapAddr + startOffset + HEADER_EXTRA;
}
Пример #18
0
bool Renderable::initialize(const std::string &modelPath)
{
	mFilePath = modelPath;
	mSamplerState = nullptr;
	mTextureSRV = nullptr;

	std::ifstream file;
	if (!Fileutils::readFile(mFilePath, file)) {
		LOG("error loading renderable from file");
		return 0;
	}

	RenderableHeader header = getHeader(file);
	mVerticeCount = header.verticeCount;
	mIndiceCount = header.indiceCount;

	D3D11_INPUT_ELEMENT_DESC ied[MAX_ELEMENT_COUNT];
	UINT elementCount = 0;
	getIEDfromHeader(header, ied, mStride, elementCount);

	std::vector<Vertex1P> v1P;
	std::vector<Vertex1P1N1UV> v1P1N1UV;
	void *v = nullptr;

	if (header.vsInputLayout & VERTEX_ELEMENT::POSITION &&
		header.vsInputLayout & VERTEX_ELEMENT::TEXCOORD &&
		header.vsInputLayout & VERTEX_ELEMENT::NORMAL) {
		v1P1N1UV.resize(mVerticeCount);
		v = &v1P1N1UV[0];
	}
	else {
		v1P.resize(mVerticeCount);
		v = &v1P[0];
	}

	file.read((char*)v, mVerticeCount * mStride);
	mVBuffer = DirectX11Core::createVertexBuffer(mStride * mVerticeCount, 0, 0, v);

	std::vector<UINT> i;
	i.resize(mIndiceCount);
	file.read((char*)&i[0], mIndiceCount * sizeof(UINT));
	mIBuffer = DirectX11Core::createIndexBuffer(sizeof(UINT) * mIndiceCount, 0, &i[0]);

	
	ID3DBlob *vsByteCode = DirectX11Core::readShaderFromFile(header.vshaderPath);
	mInputLayout = DirectX11Core::createInputLayout(vsByteCode, ied, elementCount);
	mVShader = DirectX11Core::createVertexShader(vsByteCode);

	ID3DBlob *psByteCode = DirectX11Core::readShaderFromFile(header.pshaderPath);
	mPShader = DirectX11Core::createPixelShader(psByteCode);
	
	file.read((char*)&mCBData.world, sizeof(XMMATRIX));
	mCBData.world = XMMatrixTranspose(mCBData.world);
	mCBuffer = DirectX11Core::createConstantBuffer(sizeof(CBufferWorld), 1, 0, &mCBData);
	
	if (header.vsInputLayout & VERTEX_ELEMENT::TEXCOORD) {
		std::vector<std::string> texs;
		int cnt = 0;
		file.read((char*)&cnt, sizeof(int));
		for (int k = 0; k < cnt; ++k) {
			char path[75];
			file.read(path, sizeof(char) * 75);
			std::string g = path;
			texs.push_back(g);
		}
		
		mSamplerState = DirectX11Core::createSamplerState();
		mTextureSRV = DirectX11Core::createShaderResourceViewFromFile(texs[0]);
	}
	file.close();

	return true;
}
bool UnixSocketAdapter::receive(AmSipRequest &req)
{
  string            version;
  string            fct_name;
  string            cmd;
  string::size_type pos;
  string cseq_str;

  if (cacheMsg() < 0)
    goto failure;

  // handle API version
  SAFECTRLCALL1(getParam, version);
  if (version == "") {
    // some odd trailer from previous request -- ignore
    ERROR("odd trailer\n");
    goto failure;
  }
  if(version != FIFO_VERSION){
    ERROR("wrong FIFO Interface version: %s\n",version.c_str());
    goto failure;
  }

  // handle invoked function
  SAFECTRLCALL1(getParam, fct_name);
  if((pos = fct_name.find('.')) != string::npos){
    cmd = fct_name.substr(pos+1,string::npos);
    fct_name = fct_name.substr(0,pos);
  }
  if(fct_name != "sip_request") {
    ERROR("unexpected request function: '%s'\n",fct_name.c_str());
    goto failure;
  }
  if(cmd.empty()) {
    ERROR("parameter plug-in name missing.\n");
    goto failure;
  }
  req.cmd = cmd;

#define READ_PARAMETER(p) \
  do {  \
    SAFECTRLCALL1(getParam, p); \
    DBG("%s = <%s>\n",#p,p.c_str());  \
  } while (0)

  READ_PARAMETER(req.method);
  READ_PARAMETER(req.user);
  READ_PARAMETER(req.domain);
  READ_PARAMETER(req.dstip);    // will be taken for UDP's local peer IP & Contact
  READ_PARAMETER(req.port);     // will be taken for Contact
  READ_PARAMETER(req.r_uri);    // ??? will be taken for the answer's Contact header field ???
  READ_PARAMETER(req.from_uri); // will be taken for subsequent request uri
  READ_PARAMETER(req.from);
  READ_PARAMETER(req.to);
  READ_PARAMETER(req.callid);
  READ_PARAMETER(req.from_tag);
  READ_PARAMETER(req.to_tag);

  READ_PARAMETER(cseq_str);
    
  if(sscanf(cseq_str.c_str(),"%u", &req.cseq) != 1){
    ERROR("invalid cseq number '%s'\n",cseq_str.c_str());
    goto failure;
  }
  DBG("cseq = <%s>(%i)\n",cseq_str.c_str(),req.cseq);
    
  READ_PARAMETER(req.serKey);
  READ_PARAMETER(req.route);
  READ_PARAMETER(req.next_hop);


  SAFECTRLCALL1(getLines,req.hdrs);
  DBG("hdrs = <%s>\n",req.hdrs.c_str());

  SAFECTRLCALL1(getLines,req.body);
  DBG("body = <%s>\n",req.body.c_str());

  req.content_type = getHeader(req.hdrs,"Content-Type");

  if(req.from.empty() || 
     req.to.empty() || 
     req.callid.empty() || 
     req.from_tag.empty()) {
    ERROR("%s::%s: empty mandatory parameter (from|to|callid|from_tag)\n", 
      __FILE__, __FUNCTION__);
    goto failure;
  }

  return true;

failure:
  return false;

#undef READ_PARAMETER
}
Пример #20
0
int GetCCDInfo (WF3Info *wf3, CCD_Switch *sci_sw, RefFileInfo *sciref) {

/* arguments:
WF3Info *wf3          i: calibration flags and other info
CCD_Switch *sci_sw    o: all calibration switches (0 or 1) for science file
RefFileInfo *sciref  io: list of keyword,filename pairs for science file
*/

	extern int status;

	IODescPtr im;		/* descriptor for an image */
	Hdr phdr;		/* primary header */
	int nextend;		/* number of FITS extensions in rawfile */

	int GetKeyInt (Hdr *, char *, int, int, int *);
	int GetKeyFlt (Hdr *, char *, int, float, float *);
	int GetCCDSws (CCD_Switch *, Hdr *);
	int GetCCDRef (WF3Info *, CCD_Switch *, Hdr *, RefFileInfo *);
	
	/* Open input raw data file. */
	initHdr (&phdr);
	im = openInputImage (wf3->rawfile, "", 0);
	if (hstio_err()) {
	    sprintf (MsgText, "Member \"%s\" is not present", wf3->rawfile);
	    trlerror (MsgText);
        freeHdr(&phdr);
	    return (status = OPEN_FAILED);
	}

	/* Read primary header into pdhr. */
	getHeader (im, &phdr);
	if (hstio_err()) {
	    sprintf (MsgText, "Could not open PRIMARY header for \"%s\" ",
		     wf3->rawfile);
	    trlmessage (MsgText);
        closeImage(im);
        freeHdr(&phdr);
	    return (status = OPEN_FAILED);
	}
	closeImage (im);
	
	/* Get generic parameters: */

	/* Find out how many extensions there are in this file. */
	if (GetKeyInt (&phdr, "NEXTEND", USE_DEFAULT, EXT_PER_GROUP, &nextend)){
        freeHdr(&phdr);
        closeImage(im);
	    return (status = KEYWORD_MISSING);
    }
        
	wf3->nchips = nextend / EXT_PER_GROUP;

	/* Get binning and gain info.  We really only need this for the CCD. */
	if (GetKeyInt (&phdr, "BINAXIS1", USE_DEFAULT, 1, &wf3->scibin[0])) {
        closeImage(im);
        freeHdr(&phdr);
	    return (status = KEYWORD_MISSING);
    }
	if (GetKeyInt (&phdr, "BINAXIS2", USE_DEFAULT, 1, &wf3->scibin[1])){
        closeImage(im);
        freeHdr(&phdr);
	    return (status = KEYWORD_MISSING);
    }
	if (GetKeyFlt (&phdr, "CCDGAIN",  USE_DEFAULT, 1.5, &wf3->scigain)){
        closeImage(im);
        freeHdr(&phdr);
	    return (status = KEYWORD_MISSING);
    }
    
	wf3->samebin = 1;	/* default */

	/* Get calibration switches, and check that reference files exist. */
	if (GetCCDSws (sci_sw, &phdr))
	    return (status = KEYWORD_MISSING);
	if (GetCCDRef (wf3, sci_sw, &phdr, sciref))
	    return (status = CAL_FILE_MISSING);

	freeHdr (&phdr);
	return (status);
}
Пример #21
0
static int FluxToNet (StisInfo6 *sts, IntensArray *inta, int sporder) {

	/* This is used to store information from the fflux file in a
           form suitable for the reference file input routines.
        */
	StisInfo6 fsts;
	ApInfo slit;
	PhotInfo phot;

	IODescPtr im;
	Hdr phdr;
	double photfactor, throughput, response, dispersion;
	double atodgain, readnoise;
	float correction;
	int i, dispc, helc, status;
	int abs_starti, thr_starti;
	int dummy;

	void FreePhot6 (PhotInfo *);
	void FreeThroughput6 (ApInfo *);
	int GetAbsPhot6 (StisInfo6 *, int, PhotInfo *, int, int *);
	int GetApDes6 (StisInfo6 *, ApInfo *);
	int GetApThr6 (StisInfo6 *, ApInfo *);
	int Get_KeyD (Hdr *, char *, int, double, double *);
	int Get_KeyS (Hdr *, char *, int, char *, char *, int);
	int GetSwitch (Hdr *, char *, int *);
	double interp1d (double, double *, double *, int, int *);
	void StisInit6 (StisInfo6 *);

	photfactor = H_PLANCK * C_LIGHT / HST_AREA;

	/* Initialize local data structures. */
	StisInit6 (&fsts);
        InitRefTab (&fsts.phottab);
        InitRefTab (&fsts.apertab);
        InitRefTab (&fsts.apdestab);
	slit.allocated  = 0;
	slit.gac_allocated  = 0;
	phot.allocated  = 0;
	phot.pcorr      = NULL;

	/* Handling the primary header here is not efficient. But keeps
           this new code manageable since everything new is added at a
           single point. In the future we may move this to outside the
           main loop and pass the necessary values as part of the sts
           structure.
        */
	initHdr (&phdr);
	im = openInputImage (sts->pxtab.name, "", 0);
	if (hstio_err())
	    return (OPEN_FAILED);
	getHeader (im, &phdr);
	if (hstio_err())
	    return (OPEN_FAILED);
	closeImage (im);

	/* Abort if both helcorr and dispcorr weren't performed.
           The criterion is: if a keyword is set to either COMPLETE
           or PERFORM, we assume that the operation was performed.
           This is because UpdHdrSwitch in Do1Dx only updates the
           keywords to COMPLETE if they are set to PERFORM in the
           input file.  (note:  UpdHdrSwitch is no longer used)
        */
	if ((status = GetSwitch (&phdr, "DISPCORR", &dispc)))
	    return (status);
	if ((status = GetSwitch (&phdr, "HELCORR", &helc)))
	    return (status);
	if (!((dispc == PERFORM || dispc == COMPLETE) &&
              (helc  == PERFORM || helc  == COMPLETE))) {
	    printf ("ERROR    No DISPCORR/HELCORR in fflux file.\n");
	    return (ERROR_RETURN);
	}

	/* Read header keywords. */
	if ((status = Get_KeyD (&phdr, "READNSE", 1, 0., &readnoise)))
	    return (status);
	if ((status = Get_KeyD (&phdr, "ATODGAIN", 1, 1., &atodgain)))
	    return (status);
	if ((status = Get_KeyS (&phdr, "PHOTTAB", FATAL, "",
                                fsts.phottab.name, STIS_LINE)))
	    return (status);
	if ((status = Get_KeyS (&phdr, "APDESTAB", FATAL, "",
                                fsts.apdestab.name, STIS_LINE)))
	    return (status);
	if ((status = Get_KeyS (&phdr, "APERTAB", FATAL, "",
                                fsts.apertab.name, STIS_LINE)))
	    return (status);

	/* Copy stuff from primary data structure into local one. */
	fsts.x1d_o    = sts->x1d_o;
	fsts.dispcorr = sts->dispcorr;
	fsts.fluxcorr = sts->fluxcorr;
	fsts.pctcorr  = sts->pctcorr;
	fsts.cenwave  = sts->cenwave;
	strcpy (fsts.opt_elem, sts->opt_elem);
	strcpy (fsts.aperture, sts->aperture);

	/* Read the required reference info. */
	dummy = 0;
	if ((status = GetAbsPhot6 (&fsts, sporder, &phot, 0, &dummy)))
	    return (status);
	if ((status = GetApDes6 (&fsts, &slit)))
	    return (status);
        if ((status = GetApThr6 (&fsts, &slit)))
	    return (status);

	abs_starti = 1;				/* initial values */
	thr_starti = 1;

	/* Loop over flux array. */
	for (i = 0;  i < inta->nelem;  i++) {
	    response   = interp1d (inta->wave[i], phot.wl, phot.thru,
                                   phot.nelem, &abs_starti);
	    throughput = interp1d (inta->wave[i], slit.wl, slit.thr,
                                   slit.nelem, &thr_starti);
	    if (i > 0)
	        dispersion = inta->wave[i] - inta->wave[i-1];
	    else
	        dispersion = inta->wave[1] - inta->wave[0];

	    /* This check is provisional; final version awaits IS's words. */
	    if (response   <= 0.0 ||
	        dispersion <= 0.0 ||
	        throughput <= 0.0) {
	        printf ("ERROR    Error in fflux file contents.\n");
	        return (ERROR_RETURN);
	    }

	    correction = (float) (photfactor / (response * throughput *
                         inta->wave[i] * dispersion * atodgain *
                         CM_PER_ANGSTROM));

	    inta->intens[i] = inta->intens[i] / correction;
	}

	FreeThroughput6 (&slit);
	FreePhot6 (&phot);

	freeHdr (&phdr);
	return STIS_OK;
}
Пример #22
0
std::string HttpMessage::getHeader(const char* name, const char* defaultValue)
{
	std::string str(name);
	std::string strDef(defaultValue);
	return getHeader(str, strDef);
}
Пример #23
0
/*
 *  Add a response cookie
 */
static void setCookie(void *handle, cchar *name, cchar *value, cchar *path, cchar *cookieDomain, int lifetime, bool isSecure)
{
    struct tm   tm;
    cchar       *userAgent, *hostName;
    char        dateStr[64], *cp, *expiresAtt, *expires, *domainAtt, *domain, *secure;

    if (path == 0) {
        path = "/";
    }

    userAgent = getHeader(handle, "HTTP_USER_AGENT");
    hostName = getHeader(handle, "HTTP_HOST");

    /*
     *  Fix for Safari and Bonjour addresses with a trailing ".". Safari discards cookies without a domain specifier
     *  or with a domain that includes a trailing ".". Solution: include an explicit domain and trim the trailing ".".
     *
     *   User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us)
     *       AppleWebKit/530.0+ (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1
     */
    if (cookieDomain == 0 && userAgent && strstr(userAgent, "AppleWebKit") != 0) {
        domain = mprStrdup(mpr, hostName);
        if ((cp = strchr(domain, ':')) != 0) {
            *cp = '\0';
        }
        if (*domain && domain[strlen(domain) - 1] == '.') {
            domain[strlen(domain) - 1] = '\0';
        } else {
            domain = 0;
        }
    } else {
        domain = 0;
    }
    if (domain) {
        domainAtt = "; domain=";
    } else {
        domainAtt = "";
    }
    if (lifetime > 0) {
        mprDecodeUniversalTime(mpr, &tm, mprGetTime(mpr) + (lifetime * MPR_TICKS_PER_SEC));
        mprFormatTime(mpr, MPR_HTTP_DATE, &tm);
        expiresAtt = "; expires=";
        expires = dateStr;

    } else {
        expires = expiresAtt = "";
    }
    if (isSecure) {
        secure = "; secure";
    } else {
        secure = ";";
    }

    /*
     *  Allow multiple cookie headers. Even if the same name. Later definitions take precedence
     */
    setHeader(handle, 1, "Set-Cookie",
              mprStrcat(mpr, -1, name, "=", value, "; path=", path, domainAtt, domain, expiresAtt, expires, secure, NULL));

    setHeader(handle, 0, "Cache-control", "no-cache=\"set-cookie\"");
}
Пример #24
0
int ImgPedigree (RefImage *ref) {

	FitsKw key;		/* location of keyword in header */
	IODescPtr im;		/* descriptor for primary header unit */
	Hdr phdr;		/* primary header */

	initHdr (&phdr);
	ref->goodPedigree = GOOD_PEDIGREE;	/* initial value */

	if (!GotFileName (ref->name)) {
	    ref->exists = EXISTS_NO;
	    return (0);
	}

	/* Open the primary header of the reference file. */
	im = openInputImage (ref->name, "", 0);
	if (hstio_err()) {
	    ref->exists = EXISTS_NO;
	    clear_hstioerr();
	    return (0);
	}
	ref->exists = EXISTS_YES;
	getHeader (im, &phdr);
	if (hstio_err())
	    return (HEADER_PROBLEM);

	/* Get pedigree and descrip.  If either or both are missing,
	   that's not an error in this case.
	*/
	key = findKw (&phdr, "PEDIGREE");
	if (key == NotFound) {
	    ref->pedigree[0] = '\0';
	} else {
	    getStringKw (key, ref->pedigree, STIS_FITS_REC);
	    if (hstio_err()) {
		printf ("ERROR    Trying to get PEDIGREE.\n");
		return (HEADER_PROBLEM);
	    }
	}

	key = findKw (&phdr, "DESCRIP");
	if (key == NotFound) {
	    ref->descrip[0] = '\0';
	} else {
	    getStringKw (key, ref->descrip, STIS_FITS_REC);
	    if (hstio_err()) {
		printf ("ERROR    Trying to get DESCRIP.\n");
		return (HEADER_PROBLEM);
	    }
	}

	/* Is this a dummy reference file? */
	if (strncmp (ref->pedigree, "DUMMY", 5) == 0)
	    ref->goodPedigree = DUMMY_PEDIGREE;	/* dummy, so pedigree is bad */
	else
	    ref->goodPedigree = GOOD_PEDIGREE;		/* pedigree is good */

	/* Done with this image for the time being. */
	closeImage (im);
	freeHdr (&phdr);

	return (0);
}
AmSession* AnswerMachineFactory::onInvite(const AmSipRequest& req, const string& app_name,
					  const map<string,string>& app_params)
{
  string language;
  string email;
  string domain;
  string user;
  string sender;
  string typ;
  string uid; // user ID
  string did; // domain ID
  string mode;
  string iptel_app_param;

  EmailTmplDict template_variables;

  int vm_mode = DefaultVMMode; 

  if(SimpleMode) {
    email = EmailAddress;
    uid = user = req.user;
    //did = domain = req.domain;
    did = domain = "default";
    sender = req.from;
    typ = DEFAULT_TYPE;
  }
  else {
  
    iptel_app_param = getHeader(req.hdrs, PARAM_HDR, true);
    mode = get_header_keyvalue(iptel_app_param,"mod", "Mode");
    
    if (!EmailAddress.length()) {
      
      if (!iptel_app_param.length()) {
	throw AmSession::Exception(500, "voicemail: parameters not found");
      }
      
      language = get_header_keyvalue(iptel_app_param, "lng", "Language");
      email = get_header_keyvalue(iptel_app_param, "eml", "Email-Address");
      
      if (!mode.empty()) {
	if (mode == "box")
	  vm_mode = MODE_BOX;
	else if (mode == "both")
	  vm_mode = MODE_BOTH;
	else if (mode == "ann")
	  vm_mode = MODE_ANN;
      }
    } else {
      // overrides email address
      //vm_mode = MODE_VOICEMAIL;
      email = EmailAddress;
    }
    
    if (((vm_mode == MODE_BOTH) || (vm_mode == MODE_VOICEMAIL)) &&
	(email.find('@') == string::npos)) {
      ERROR("no @ found in email address '%s' from params '%s'\n",
	    email.c_str(), iptel_app_param.c_str());
      throw AmSession::Exception(500, "voicemail: no email address");
    }
    
    user = get_header_keyvalue(iptel_app_param,"usr", "User");
    if (!user.length())
      user = req.user;
    
    sender = get_header_keyvalue(iptel_app_param, "snd", "Sender");
    if (!sender.length()) 
      sender = req.from;  
    
    domain = get_header_keyvalue(iptel_app_param, "dom", "Domain");
    if (!domain.length())
      domain = req.domain;
    
    typ = get_header_keyvalue(iptel_app_param, "typ", "Type");
    if (!typ.length())
      typ = DEFAULT_TYPE;
    
    uid = get_header_keyvalue(iptel_app_param, "uid", "UserID");
    if (uid.empty())
      uid=user;
    
    did = get_header_keyvalue(iptel_app_param, "did", "DomainID");
    if (did.empty())
      did=domain;
  }
    
  // checks
  if (uid.empty()) 
    throw AmSession::Exception(500, "voicemail: user missing");
  
  if (sender.empty()) 
    throw AmSession::Exception(500, "voicemail: sender missing");
  
  if (((vm_mode == MODE_BOX) || (vm_mode == MODE_BOTH))
      && (NULL == MessageStorage)) {
    throw AmSession::Exception(500, "voicemail: no message storage available");
  }
  
  
  DBG("voicemail invocation parameters: \n");
  DBG(" Mode:     <%s> \n", mode.c_str());
  DBG(" Email:    <%s> \n", email.c_str());
  DBG(" User:     <%s> \n", user.c_str());
  DBG(" Sender:   <%s> \n", sender.c_str());
  DBG(" Domain:   <%s> \n", domain.c_str());
  DBG(" Language: <%s> \n", language.c_str());
  DBG(" Type:     <%s> \n", typ.c_str());
  DBG(" UID:      <%s> \n", uid.c_str());
  DBG(" DID:      <%s> \n", did.c_str());
  
  FILE* greeting_fp = NULL;
  if (TryPersonalGreeting)
    greeting_fp = getMsgStoreGreeting(typ, uid, did);

#ifdef USE_MYSQL

  string announce_file;

  if (get_audio_file(GREETING_MSG, domain, req.user, "",
                    announce_file) && !announce_file.empty())
    goto announce_found;

  if (!language.empty()) {
    if (get_audio_file(GREETING_MSG, domain, "", language,
                      announce_file) && !announce_file.empty())
      goto announce_found;
  } else {
    if (get_audio_file(GREETING_MSG, domain, "", "",
                      announce_file) && !announce_file.empty())
      goto announce_found;
  }

  if (!language.empty())
    if (get_audio_file(GREETING_MSG, "", "", language,
                      announce_file) && !announce_file.empty())
      goto announce_found;

  get_audio_file(GREETING_MSG, "", "", "", announce_file);

#else

  string announce_file = add2path(AnnouncePath,2, 
				  did.c_str(), (uid + ".wav").c_str());
  if (file_exists(announce_file)) goto announce_found;

  if (!language.empty()) {
    announce_file = add2path(AnnouncePath,3, 
			     did.c_str(), language.c_str(), DefaultAnnounce.c_str());
    if (file_exists(announce_file)) goto announce_found;
  }

  announce_file = add2path(AnnouncePath,2, 
			   did.c_str(), DefaultAnnounce.c_str());
  if (file_exists(announce_file)) goto announce_found;

  if (!language.empty()) {
    announce_file = add2path(AnnouncePath,2, 
			     language.c_str(),  DefaultAnnounce.c_str());
    if (file_exists(announce_file)) goto announce_found;
  }
	
  announce_file = add2path(AnnouncePath,1, DefaultAnnounce.c_str());
  if (!file_exists(announce_file)) 
    announce_file = "";

#endif

 announce_found:
  if(announce_file.empty())
    throw AmSession::Exception(500,"voicemail: no greeting file found");

  if(!SimpleMode) {

    // a little inefficient this way - but get_header_keyvalue supports escaping
    for (vector<string>::iterator it=
	   MailHeaderVariables.begin(); it != MailHeaderVariables.end(); it++) {
      template_variables[*it] = get_header_keyvalue(iptel_app_param, *it);
    }
  }

  // VBOX mode does not need email template
  if ((vm_mode == MODE_BOX) || (vm_mode == MODE_ANN))
    return new AnswerMachineDialog(user, sender, domain,
				   email, announce_file, uid, did, 
				   greeting_fp, vm_mode, 
				   template_variables, NULL);

  if(email.empty())
    throw AmSession::Exception(404,"missing email address");

  map<string,EmailTemplate>::iterator tmpl_it;
  if (!language.empty()) {
    tmpl_it = email_tmpl.find(did + "_" + language);
    if(tmpl_it == email_tmpl.end()) {
      tmpl_it = email_tmpl.find(did);
      if(tmpl_it == email_tmpl.end()) {
	tmpl_it = email_tmpl.find(DEFAULT_MAIL_TMPL + "_"
				  + language);
	if(tmpl_it == email_tmpl.end())
	  tmpl_it = email_tmpl.find(DEFAULT_MAIL_TMPL);
      }
    }
  } else {
    tmpl_it = email_tmpl.find(did);
    if(tmpl_it == email_tmpl.end())
      tmpl_it = email_tmpl.find(DEFAULT_MAIL_TMPL);
  }
    
  if(tmpl_it == email_tmpl.end()){
    ERROR("Voicemail: unable to find an email template.\n");
    return 0;
  }
  return new AnswerMachineDialog(user, sender, domain,
				 email, announce_file, 
				 uid, did,
				 greeting_fp,
				 vm_mode, template_variables,
				 &tmpl_it->second);
}
string replaceParameters(const string& s,
			 const char* r_type,
			 const AmSipRequest& req,
			 const string& app_param,
			 AmUriParser& ruri_parser, AmUriParser& from_parser,
			 AmUriParser& to_parser) {
  string res;
  bool is_replaced = false;
  size_t p = 0;
  bool is_escaped = false;

  // char last_char=' ';
  
  while (p<s.length()) {
    size_t skip_chars = 1;

    if (is_escaped) {
      switch (s[p]) {
      case 'r': res += '\r'; break;
      case 'n': res += '\n'; break;
      case 't': res += '\t'; break;
      default: res += s[p]; break;
      }
      is_escaped = false;
    } else { // not escaped
      if (s[p]=='\\') {
	if (p==s.length()-1) {
	  res += '\\'; // add single \ at the end
	} else {
	  is_escaped = true;
	  is_replaced = true;
	}
      } else if ((s[p]=='$') && (s.length() >= p+1)) {
	is_replaced = true;
	p++;
	switch (s[p]) {
	case 'f': { // from
	  if ((s.length() == p+1) || (s[p+1] == '.')) {
	    res += req.from;
	    break;
	  }

	  if (s[p+1]=='t') { // $ft - from tag
	    res += req.from_tag;
	    break;
	  }

	  if (from_parser.uri.empty()) {
	    size_t end;
	    if (!from_parser.parse_contact(req.from, 0, end)) {
	      WARN("Error parsing From URI '%s'\n", req.from.c_str());
	      break;
	    }
	    from_parser.dump();
	  }

	  replaceParsedParam(s, p, from_parser, res);

	}; break;

	case 't': { // to
	  if ((s.length() == p+1) || (s[p+1] == '.')) {
	    res += req.to;
	    break;
	  }

	  if (to_parser.uri.empty()) {
	    size_t end;
	    if (!to_parser.parse_contact(req.to, 0, end)) {
	      WARN("Error parsing To URI '%s'\n", req.to.c_str());
	      break;
	    }
	  }

	  replaceParsedParam(s, p, to_parser, res);

	}; break;

	case 'r': { // r-uri
	  if ((s.length() == p+1) || (s[p+1] == '.')) {
	    res += req.r_uri;
	    break;
	  }

	  if (ruri_parser.uri.empty()) {
	    ruri_parser.uri = req.r_uri;
	    if (!ruri_parser.parse_uri()) {
	      WARN("Error parsing R-URI '%s'\n", req.r_uri.c_str());
	      break;
	    }
	  }
	  replaceParsedParam(s, p, ruri_parser, res);
	}; break;

	case 'c': { // call-id
	  if ((s.length() == p+1) || (s[p+1] == 'i')) {
	    res += req.callid;
	    break;
	  }
	  WARN("unknown replacement $c%c\n", s[p+1]);
	}; break;

	case 's': { // source (remote)
	  if (s.length() < p+1) {
	    WARN("unknown replacement $s\n");
	    break;
	  }

	  if (s[p+1] == 'i') { // $si source IP address
	    res += req.remote_ip.c_str();
	    break;
	  } else if (s[p+1] == 'p') { // $sp source port
	    res += int2str(req.remote_port);
	    break;
	  }

	  WARN("unknown replacement $s%c\n", s[p+1]);
	}; break;

	case 'R': { // received (local)
	  if (s.length() < p+1) {
	    WARN("unknown replacement $R\n");
	    break;
	  }

	  if (s[p+1] == 'i') { // $Ri received IP address
	    res += req.local_ip.c_str();
	    break;
	  } else if (s[p+1] == 'p') { // $Rp received port
	    res += int2str(req.local_port);
	    break;
	  } else if (s[p+1] == 'f') { // $Rf received interface id
	    res += int2str(req.local_if);
	  } else if (s[p+1] == 'n') { // $Rn received interface name
	    if ((req.local_if >= 0) && req.local_if < AmConfig::Ifs.size()) {
	      res += AmConfig::Ifs[req.local_if].name;
	    }
	  } else if (s[p+1] == 'I') { // $RI received interface public IP
	    if ((req.local_if >= 0) && req.local_if < AmConfig::Ifs.size()) {
	      res += AmConfig::Ifs[req.local_if].PublicIP;
	    }
	  }
	  WARN("unknown replacement $R%c\n", s[p+1]);
	}; break;


#define case_HDR(pv_char, pv_name, hdr_name)				\
	  case pv_char: {						\
	    AmUriParser uri_parser;					\
	    string m_uri = getHeader(req.hdrs, hdr_name);		\
	    if ((s.length() == p+1) || (s[p+1] == '.')) {		\
	      res += m_uri;						\
	      break;							\
	    }								\
	    size_t end;							\
	    if (!uri_parser.parse_contact(m_uri, 0, end)) {		\
	      WARN("Error parsing " pv_name " URI '%s'\n", m_uri.c_str()); \
	      break;							\
	    }								\
	    if (s[p+1] == 'i') {					\
	      res+=uri_parser.uri_user+"@"+uri_parser.uri_host;		\
	      if (!uri_parser.uri_port.empty())				\
		res+=":"+uri_parser.uri_port;				\
	    } else {							\
	      replaceParsedParam(s, p, uri_parser, res);		\
	    }								\
	  }; break;

	  case_HDR('a', "PAI", SIP_HDR_P_ASSERTED_IDENTITY);  // P-Asserted-Identity
	  case_HDR('p', "PPI", SIP_HDR_P_PREFERRED_IDENTITY); // P-Preferred-Identity

	case 'P': { // app-params
	  if (s[p+1] != '(') {
	    WARN("Error parsing P param replacement (missing '(')\n");
	    break;
	  }
	  if (s.length()<p+3) {
	    WARN("Error parsing P param replacement (short string)\n");
	    break;
	  }

	  size_t skip_p = p+2;
	  for (;skip_p<s.length() && s[skip_p] != ')';skip_p++) { }
	  if (skip_p==s.length()) {
	    WARN("Error parsing P param replacement (unclosed brackets)\n");
	    break;
	  }
	  string param_name = s.substr(p+2, skip_p-p-2);
	  // DBG("param_name = '%s' (skip-p - p = %d)\n", param_name.c_str(), skip_p-p);
	  res += get_header_keyvalue(app_param, param_name);
	  skip_chars = skip_p-p;
	} break;

	case 'H': { // header
	  size_t name_offset = 2;
	  if (s[p+1] != '(') {
	    if (s[p+2] != '(') {
	      WARN("Error parsing H header replacement (missing '(')\n");
	      break;
	    }
	    name_offset = 3;
	  }
	  if (s.length()<name_offset+1) {
	    WARN("Error parsing H header replacement (short string)\n");
	    break;
	  }

	  size_t skip_p = p+name_offset;
	  for (;skip_p<s.length() && s[skip_p] != ')';skip_p++) { }
	  if (skip_p==s.length()) {
	    WARN("Error parsing H header replacement (unclosed brackets)\n");
	    break;
	  }
	  string hdr_name = s.substr(p+name_offset, skip_p-p-name_offset);
	  // DBG("param_name = '%s' (skip-p - p = %d)\n", param_name.c_str(), skip_p-p);
	  if (name_offset == 2) {
	    // full header
	    res += getHeader(req.hdrs, hdr_name);
	  } else {
	    // parse URI and use component
	    AmUriParser uri_parser;
	    string m_uri = getHeader(req.hdrs, hdr_name);
	    if ((s[p+1] == '.')) {
	      res += m_uri;
	      break;
	    }

	    size_t end;
	    if (!uri_parser.parse_contact(m_uri, 0, end)) {
	      WARN("Error parsing header %s URI '%s'\n",
		   hdr_name.c_str(), m_uri.c_str());
	      break;
	    }
	    replaceParsedParam(s, p, uri_parser, res);
	  }
	  skip_chars = skip_p-p;
	} break;

	case 'M': { // regex map
	  if (s[p+1] != '(') {
	    WARN("Error parsing $M regex map replacement (missing '(')\n");
	    break;
	  }
	  if (s.length()<p+3) {
	    WARN("Error parsing $M regex map replacement (short string)\n");
	    break;
	  }

	  size_t skip_p = p+2;
	  skip_p = skip_to_end_of_brackets(s, skip_p);

	  if (skip_p==s.length()) {
	    WARN("Error parsing $M regex map replacement (unclosed brackets)\n");
	    skip_chars = skip_p-p;
	    break;
	  }

	  string map_str = s.substr(p+2, skip_p-p-2);
	  size_t spos = map_str.rfind("=>");
	  if (spos == string::npos) {
	    skip_chars = skip_p-p;
	    WARN("Error parsing $M regex map replacement: no => found in '%s'\n",
		 map_str.c_str());
	    break;
	  }

	  string map_val = map_str.substr(0, spos);
	  string map_val_replaced = replaceParameters(map_val, r_type, req, app_param,
						      ruri_parser, from_parser, to_parser);
	  string mapping_name = map_str.substr(spos+2);

	  string map_res; 
	  if (SBCFactory::regex_mappings.
	      mapRegex(mapping_name, map_val_replaced.c_str(), map_res)) {
	    DBG("matched regex mapping '%s' (orig '%s) in '%s'\n",
		map_val_replaced.c_str(), map_val.c_str(), mapping_name.c_str());
	    res+=map_res;
	  } else {
	    DBG("no match in regex mapping '%s' (orig '%s') in '%s'\n",
		map_val_replaced.c_str(), map_val.c_str(), mapping_name.c_str());
	  }
 
	  skip_chars = skip_p-p;
	} break;

	case '_': { // modify
	  if (s.length()<p+4) { // $_O()
	    WARN("Error parsing $_ modifier replacement (short string)\n");
	    break;
	  }

	  char operation = s[p+1];
	  if (operation != 'U' && operation != 'l'
	      && operation != 's' && operation != '5') {
	    WARN("Error parsing $_%c string modifier: unknown operator '%c'\n",
		 operation, operation);
	  }

	  if (s[p+2] != '(') {
	    WARN("Error parsing $U upcase replacement (missing '(')\n");
	    break;
	  }

	  size_t skip_p = p+3;
	  skip_p = skip_to_end_of_brackets(s, skip_p);

	  if (skip_p==s.length()) {
	    WARN("Error parsing $_ modifier (unclosed brackets)\n");
	    skip_chars = skip_p-p;
	    break;
	  }

	  string br_str = s.substr(p+3, skip_p-p-3);
	  string br_str_replaced = replaceParameters(br_str, "$_*(...)",
						     req, app_param,
						     ruri_parser, from_parser, to_parser);
	  br_str = br_str_replaced;
	  switch(operation) {
	  case 'u': // uppercase
	    transform(br_str_replaced.begin(), br_str_replaced.end(),
		      br_str_replaced.begin(), ::toupper); break;
	  case 'l': // lowercase
	    transform(br_str_replaced.begin(), br_str_replaced.end(),
		      br_str_replaced.begin(), ::tolower); break;

	  case 's': // size (string length)
	    br_str_replaced = int2str((unsigned int)br_str.length());
	    break;

	  case '5': // md5
	    br_str_replaced = calculateMD5(br_str);
	    break;

	  default: break;
	  }
	  DBG("applied operator '%c': '%s' => '%s'\n", operation,
	      br_str.c_str(), br_str_replaced.c_str());
	  res+=br_str_replaced;

	  skip_chars = skip_p-p;
	} break;

	default: {
	  WARN("unknown replace pattern $%c%c\n",
	       s[p], s[p+1]);
	}; break;
	};

	p+=skip_chars; // skip $.X
      } else {
	res += s[p];
      }
    } // end not escaped

    p++;
  }

  if (is_replaced) {
    DBG("%s pattern replace: '%s' -> '%s'\n", r_type, s.c_str(), res.c_str());
  }
  return res;
}
Пример #27
0
int AmB2BCallerSession::reinviteCaller(const AmSipReply& callee_reply)
{
  string content_type = getHeader(callee_reply.hdrs,"Content-Type");
  return dlg.sendRequest("INVITE",content_type,callee_reply.body);
}
Пример #28
0
AmSession* AnswerMachineFactory::onInvite(const AmSipRequest& req)
{
  string language;
  string email;

  string iptel_app_param = getHeader(req.hdrs, PARAM_HDR);

  if (!EmailAddress.length()) {
    if (iptel_app_param.length()) {
      language = get_header_keyvalue(iptel_app_param,"Language");
      email = get_header_keyvalue(iptel_app_param,"Email-Address");
    } else {      
      email = getHeader(req.hdrs,"P-Email-Address");
      language = getHeader(req.hdrs,"P-Language"); // local user's language
      
      if (email.length()) {
	INFO("Use of P-Email-Address/P-Language is deprecated. \n");
	INFO("Use '%s: Email-Address=<addr>;"
	     "Language=<lang>' instead.\n",PARAM_HDR);
      }
    }
  } else {
    email = EmailAddress;
  }

  DBG("email address for user '%s': <%s> \n",
      req.user.c_str(),email.c_str());
  DBG("language: <%s> \n", language.c_str());

#ifdef USE_MYSQL

  string announce_file;

  if (get_audio_file(GREETING_MSG, req.domain, req.user, "",
		     &announce_file) && !announce_file.empty())
    goto announce_found;

  if (!language.empty()) {
    if (get_audio_file(GREETING_MSG, req.domain, "", language,
		       &announce_file) && !announce_file.empty())
      goto announce_found;
  } else {
    if (get_audio_file(GREETING_MSG, req.domain, "", "",
		       &announce_file) && !announce_file.empty())
      goto announce_found;
  }
    
  if (!language.empty())
    if (get_audio_file(GREETING_MSG, "", "", language,
		       &announce_file) && !announce_file.empty())
      goto announce_found;
    
  get_audio_file(GREETING_MSG, "", "", "", &announce_file);
    
#else

  string announce_file = add2path(AnnouncePath,2, req.domain.c_str(), (req.user + ".wav").c_str());
  if (file_exists(announce_file)) goto announce_found;

  if (!language.empty()) {
    announce_file = add2path(AnnouncePath,3, req.domain.c_str(), language.c_str(), DefaultAnnounce.c_str());
    if (file_exists(announce_file)) goto announce_found;
  }

  announce_file = add2path(AnnouncePath,2, req.domain.c_str(), DefaultAnnounce.c_str());
  if (file_exists(announce_file)) goto announce_found;

  if (!language.empty()) {
    announce_file = add2path(AnnouncePath,2, language.c_str(),  DefaultAnnounce.c_str());
    if (file_exists(announce_file)) goto announce_found;
  }
	
  announce_file = add2path(AnnouncePath,1, DefaultAnnounce.c_str());
  if (!file_exists(announce_file)) 
    announce_file = "";

#endif

 announce_found:
  if(announce_file.empty())
    throw AmSession::Exception(500,"voicemail: no greeting file found");

  if(email.empty())
    throw AmSession::Exception(404,"missing email address");

  map<string,EmailTemplate>::iterator tmpl_it;
  if (!language.empty()) {
    tmpl_it = email_tmpl.find(req.domain + "_" + language);
    if(tmpl_it == email_tmpl.end()) {
      tmpl_it = email_tmpl.find(req.domain);
      if(tmpl_it == email_tmpl.end()) {
	tmpl_it = email_tmpl.find(DEFAULT_MAIL_TMPL + "_"
				  + language);
	if(tmpl_it == email_tmpl.end())
	  tmpl_it = email_tmpl.find(DEFAULT_MAIL_TMPL);
      }
    }
  } else {
    tmpl_it = email_tmpl.find(req.domain);
    if(tmpl_it == email_tmpl.end())
      tmpl_it = email_tmpl.find(DEFAULT_MAIL_TMPL);
  }
	    
  if(tmpl_it == email_tmpl.end()){
    ERROR("Voicemail: unable to find an email template.\n");
    return 0;
  }

  return new AnswerMachineDialog(email,announce_file,
				 &tmpl_it->second);
}
Пример #29
0
std::shared_ptr<const contentTypeField> bodyPartAttachment::getContentType() const
{
	return std::dynamic_pointer_cast<const
		contentTypeField>(getHeader()->findField(fields::CONTENT_TYPE));
}
Пример #30
0
bool HttpMessage::isKeepAlive() const
{
    return getHeader(http::Connection).getValue().toLower()=="keep-alive";
}