code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.updaters; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.ttrssreader.gui.interfaces.IUpdateEndListener; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.WeakReferenceHandler; import android.app.Activity; import android.os.Message; public class Updater extends AsyncTask<Void, Void, Void> { private IUpdatable updatable; public Updater(Activity parent, IUpdatable updatable) { this(parent, updatable, false); } public Updater(Activity parent, IUpdatable updatable, boolean goBackAfterUpdate) { this.updatable = updatable; if (parent instanceof IUpdateEndListener) this.handler = new MsgHandler((IUpdateEndListener) parent, goBackAfterUpdate); } // Use handler with weak reference on parent object private static class MsgHandler extends WeakReferenceHandler<IUpdateEndListener> { boolean goBackAfterUpdate; public MsgHandler(IUpdateEndListener parent, boolean goBackAfterUpdate) { super(parent); this.goBackAfterUpdate = goBackAfterUpdate; } @Override public void handleMessage(IUpdateEndListener parent, Message msg) { parent.onUpdateEnd(goBackAfterUpdate); } } private MsgHandler handler; @Override protected Void doInBackground(Void... params) { updatable.update(this); if (handler != null) handler.sendEmptyMessage(0); return null; } @SuppressWarnings("unchecked") public AsyncTask<Void, Void, Void> exec() { if (sExecuteMethod != null) { try { return (AsyncTask<Void, Void, Void>) sExecuteMethod.invoke(this, AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); } catch (InvocationTargetException unused) { } catch (IllegalAccessException unused) { } } return this.execute(); } private Method sExecuteMethod = findExecuteMethod(); // Why do we use this here though we have a method for this in Controller.isExecuteOnExecutorAvailable()? // -> There are many places we would have to alter and it would be the same code over and over again, so just leave // this here, it works. private Method findExecuteMethod() { // Didn't get Class.getMethod() to work so I just search for the right method-name and take the first hit. Class<?> cls = AsyncTask.class; for (Method m : cls.getMethods()) { if ("executeOnExecutor".equals(m.getName())) return m; } return null; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/updaters/Updater.java
Java
gpl3
3,309
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.updaters; public interface IUpdatable { public void update(Updater parent); }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/updaters/IUpdatable.java
Java
gpl3
685
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.updaters; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.UpdateController; import org.ttrssreader.model.pojos.Article; public class StarredStateUpdater implements IUpdatable { protected static final String TAG = StarredStateUpdater.class.getSimpleName(); private Article article; private int articleState; /** * Sets the articles' Starred-Status according to articleState */ public StarredStateUpdater(Article article, int articleState) { this.article = article; this.articleState = articleState; } @Override public void update(Updater parent) { if (articleState >= 0) { article.isStarred = articleState > 0 ? true : false; DBHelper.getInstance().markArticle(article.id, "isStarred", articleState); UpdateController.getInstance().notifyListeners(); Data.getInstance().setArticleStarred(article.id, articleState); } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/updaters/StarredStateUpdater.java
Java
gpl3
1,595
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.updaters; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.UpdateController; import org.ttrssreader.model.pojos.Article; public class PublishedStateUpdater implements IUpdatable { protected static final String TAG = PublishedStateUpdater.class.getSimpleName(); private Article article; private int articleState; private String note; /** * Sets the articles' Published-Status according to articleState */ public PublishedStateUpdater(Article article, int articleState) { this.article = article; this.articleState = articleState; this.note = null; } /** * Sets the articles' Published-Status according to articleState and adds the given note to the article. */ public PublishedStateUpdater(Article article, int articleState, String note) { this.article = article; this.articleState = articleState; this.note = note; } @Override public void update(Updater parent) { if (articleState >= 0) { article.isPublished = articleState > 0 ? true : false; DBHelper.getInstance().markArticle(article.id, "isPublished", articleState); UpdateController.getInstance().notifyListeners(); Data.getInstance().setArticlePublished(article.id, articleState, note); } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/updaters/PublishedStateUpdater.java
Java
gpl3
1,985
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.updaters; import org.ttrssreader.controllers.Data; public class StateSynchronisationUpdater implements IUpdatable { protected static final String TAG = StateSynchronisationUpdater.class.getSimpleName(); @Override public void update(Updater parent) { Data.getInstance().synchronizeStatus(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/updaters/StateSynchronisationUpdater.java
Java
gpl3
884
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.utils.Utils; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class FeedCursorHelper extends MainCursorHelper { protected static final String TAG = FeedCursorHelper.class.getSimpleName(); public FeedCursorHelper(Context context, int categoryId) { super(context); this.categoryId = categoryId; } @Override public Cursor createCursor(SQLiteDatabase db, boolean overrideDisplayUnread, boolean buildSafeQuery) { StringBuilder query = new StringBuilder(); String lastOpenedFeedsList = Utils.separateItems(Controller.getInstance().lastOpenedFeeds, ","); boolean displayUnread = Controller.getInstance().onlyUnread(); boolean invertSortFeedCats = Controller.getInstance().invertSortFeedscats(); if (overrideDisplayUnread) displayUnread = false; if (lastOpenedFeedsList.length() > 0 && !buildSafeQuery) { query.append("SELECT _id,title,unread FROM ("); } query.append("SELECT _id,title,unread FROM "); query.append(DBHelper.TABLE_FEEDS); query.append(" WHERE categoryId="); query.append(categoryId); query.append(displayUnread ? " AND unread>0" : ""); if (lastOpenedFeedsList.length() > 0 && !buildSafeQuery) { query.append(" UNION SELECT _id,title,unread"); query.append(" FROM feeds WHERE _id IN ("); query.append(lastOpenedFeedsList); query.append(" ))"); } query.append(" ORDER BY UPPER(title) "); query.append(invertSortFeedCats ? "DESC" : "ASC"); query.append(buildSafeQuery ? " LIMIT 200" : " LIMIT 600"); return db.rawQuery(query.toString(), null); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/FeedCursorHelper.java
Java
gpl3
2,617
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.pojos; public class Category implements Comparable<Category> { public int id; public String title; public int unread; public Category() { this.id = 0; this.title = ""; this.unread = 0; } public Category(int id, String title, int unread) { this.id = id; this.title = title; this.unread = unread; } @Override public int compareTo(Category ci) { // Sort by Id if Id is 0 or smaller, else sort by Title if (id <= 0 || ci.id <= 0) { Integer thisInt = id; Integer thatInt = ci.id; return thisInt.compareTo(thatInt); } return title.compareToIgnoreCase(ci.title); } @Override public boolean equals(Object o) { if (o instanceof Category) { Category other = (Category) o; return (id == other.id); } else { return false; } } @Override public int hashCode() { return id + "".hashCode(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/pojos/Category.java
Java
gpl3
1,655
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.pojos; public class Feed implements Comparable<Feed> { public int id; public int categoryId; public String title; public String url; public int unread; public Feed() { this.id = 0; this.categoryId = 0; this.title = ""; this.url = ""; this.unread = 0; } public Feed(int id, int categoryId, String title, String url, int unread) { this.id = id; this.categoryId = categoryId; this.title = title; this.url = url; this.unread = unread; } @Override public int compareTo(Feed fi) { return title.compareToIgnoreCase(fi.title); } @Override public boolean equals(Object o) { if (o instanceof Feed) { Feed other = (Feed) o; return (id == other.id); } else { return false; } } @Override public int hashCode() { return id + "".hashCode(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/pojos/Feed.java
Java
gpl3
1,586
/* * ttrss-reader-fork for Android * * Copyright (C) 2013 I. Lubimov. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.pojos; import java.util.Date; /** * this class represents remote file (image, attachment, etc) * belonging to article(s), which may be locally stored (cached) * * @author igor */ public class RemoteFile implements Comparable<RemoteFile> { /** numerical ID */ public int id; /** remote file URL */ public String url; /** file size */ public int length; /** extension - some kind of additional info (i.e. file extension) */ public String ext; /** last change date */ public Date updated; /** boolean flag determining if the file is locally stored */ public volatile boolean cached; /** * default constructor */ public RemoteFile() { } /** * constructor with parameters * * @param id * numerical ID * @param url * remote file URL * @param length * file size * @param ext * extension - some kind of additional info * @param updated * last change date * @param cached * boolean flag determining if the file is locally stored */ public RemoteFile(int id, String url, int length, String ext, Date updated, boolean cached) { this.id = id; this.url = url; this.length = length; this.ext = ext; this.updated = updated; this.cached = cached; } @Override public int compareTo(RemoteFile rf) { return rf.updated.compareTo(this.updated); } @Override public boolean equals(Object o) { boolean isEqual = false; if (o != null && o instanceof RemoteFile) { RemoteFile rf = (RemoteFile) o; isEqual = (id == rf.id); } return isEqual; } @Override public int hashCode() { return id; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/pojos/RemoteFile.java
Java
gpl3
2,457
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.pojos; public class Label implements Comparable<Label> { public Integer id; public String caption; public boolean checked; public boolean checkedChanged = false; public String foregroundColor; public String backgroundColor; @Override public int compareTo(Label l) { return id.compareTo(l.id); } @Override public boolean equals(Object o) { if (o instanceof Label) { Label other = (Label) o; return (id == other.id); } else { return false; } } @Override public int hashCode() { return id + "".hashCode(); } @Override public String toString() { return caption + ";" + foregroundColor + ";" + backgroundColor; } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/pojos/Label.java
Java
gpl3
1,346
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model.pojos; import java.util.Date; import java.util.Set; public class Article implements Comparable<Article> { public int id; public String title; public int feedId; public volatile boolean isUnread; public String url; public String commentUrl; public Date updated; public String content; public Set<String> attachments; public boolean isStarred; public boolean isPublished; public Integer cachedImages; public Set<Label> labels; public String author; public Article() { id = -1; title = null; isUnread = false; updated = null; feedId = 0; content = null; url = null; commentUrl = null; attachments = null; labels = null; isStarred = false; isPublished = false; author = null; } public Article(int id, int feedId, String title, boolean isUnread, String articleUrl, String articleCommentUrl, Date updateDate, String content, Set<String> attachments, boolean isStarred, boolean isPublished, int cachedImages, Set<Label> labels, String author) { this.id = id; this.title = title; this.feedId = feedId; this.isUnread = isUnread; this.updated = updateDate; this.url = articleUrl.trim(); this.commentUrl = articleCommentUrl; if (content == null || content.equals("null")) { this.content = null; } else { this.content = content; } this.attachments = attachments; this.isStarred = isStarred; this.isPublished = isPublished; this.labels = labels; this.cachedImages = cachedImages; this.author = author; } @Override public int compareTo(Article ai) { return ai.updated.compareTo(this.updated); } @Override public boolean equals(Object o) { if (o == null) return false; if (o instanceof Article) { Article ac = (Article) o; return id == ac.id; } return false; } @Override public int hashCode() { return id; } public enum ArticleField { id, title, unread, updated, feed_id, content, link, comments, attachments, marked, published, labels, is_updated, tags, feed_title, comments_count, comments_link, always_display_attachments, author, score, lang, note } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/pojos/Article.java
Java
gpl3
3,079
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model; import org.ttrssreader.controllers.Controller; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public abstract class MainCursorHelper { protected static final String TAG = MainCursorHelper.class.getSimpleName(); protected Context context; protected int categoryId = Integer.MIN_VALUE; protected int feedId = Integer.MIN_VALUE; protected boolean selectArticlesForCategory; public MainCursorHelper(Context context) { this.context = context; } /** * Creates a new query * * @param force * forces the creation of a new query */ public Cursor makeQuery(SQLiteDatabase db) { Cursor cursor = null; try { if (categoryId == 0 && (feedId == -1 || feedId == -2)) { // Starred/Published cursor = createCursor(db, true, false); } else { // normal query cursor = createCursor(db, false, false); // (categoryId == -2 || feedId >= 0): Normal feeds // (categoryId == 0 || feedId == Integer.MIN_VALUE): Uncategorized Feeds if ((categoryId == -2 || feedId >= 0) || (categoryId == 0 || feedId == Integer.MIN_VALUE)) { if (Controller.getInstance().onlyUnread() && !checkUnread(cursor)) { // Override unread if query was empty cursor = createCursor(db, true, false); } } } } catch (Exception e) { // Fail-safe-query cursor = createCursor(db, false, true); } return cursor; } /** * Tries to find out if the given cursor points to a dataset with unread articles in it, returns true if it does. * * @param cursor * the cursor. * @return true if there are unread articles in the dataset, else false. */ private static final boolean checkUnread(Cursor cursor) { if (cursor == null || cursor.isClosed()) return false; // Check null or closed if (!cursor.moveToFirst()) return false; // Check empty do { if (cursor.getInt(cursor.getColumnIndex("unread")) > 0) return cursor.moveToFirst(); // One unread article found, move to first entry } while (cursor.moveToNext()); cursor.moveToFirst(); return false; } abstract Cursor createCursor(SQLiteDatabase db, boolean overrideDisplayUnread, boolean buildSafeQuery); }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/MainCursorHelper.java
Java
gpl3
3,470
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.utils.Utils; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class FeedHeadlineCursorHelper extends MainCursorHelper { protected static final String TAG = FeedHeadlineCursorHelper.class.getSimpleName(); public FeedHeadlineCursorHelper(Context context, int feedId, int categoryId, boolean selectArticlesForCategory) { super(context); this.feedId = feedId; this.categoryId = categoryId; this.selectArticlesForCategory = selectArticlesForCategory; } @Override public Cursor createCursor(SQLiteDatabase db, boolean overrideDisplayUnread, boolean buildSafeQuery) { String query; if (feedId > -10) query = buildFeedQuery(overrideDisplayUnread, buildSafeQuery); else query = buildLabelQuery(overrideDisplayUnread, buildSafeQuery); return db.rawQuery(query, null); } private String buildFeedQuery(boolean overrideDisplayUnread, boolean buildSafeQuery) { String lastOpenedArticlesList = Utils.separateItems(Controller.getInstance().lastOpenedArticles, ","); boolean displayUnread = Controller.getInstance().onlyUnread(); boolean displayCachedImages = Controller.getInstance().onlyDisplayCachedImages(); boolean invertSortArticles = Controller.getInstance().invertSortArticlelist(); if (overrideDisplayUnread) displayUnread = false; StringBuilder query = new StringBuilder(); query.append("SELECT a._id AS _id, a.feedId AS feedId, a.title AS title, a.isUnread AS unread, a.updateDate AS updateDate, a.isStarred AS isStarred, a.isPublished AS isPublished FROM "); query.append(DBHelper.TABLE_ARTICLES); query.append(" a, "); query.append(DBHelper.TABLE_FEEDS); query.append(" b WHERE a.feedId=b._id"); switch (feedId) { case Data.VCAT_STAR: query.append(" AND a.isStarred=1"); break; case Data.VCAT_PUB: query.append(" AND a.isPublished=1"); break; case Data.VCAT_FRESH: query.append(" AND a.updateDate>"); query.append(System.currentTimeMillis() - Controller.getInstance().getFreshArticleMaxAge()); query.append(" AND a.isUnread>0"); break; case Data.VCAT_ALL: query.append(displayUnread ? " AND a.isUnread>0" : ""); break; default: // User selected to display all articles of a category directly query.append(selectArticlesForCategory ? (" AND b.categoryId=" + categoryId) : (" AND a.feedId=" + feedId)); query.append(displayUnread ? " AND a.isUnread>0" : ""); if (displayCachedImages) { query.append(" AND 0 < (SELECT SUM(r.cached) FROM "); query.append(DBHelper.TABLE_REMOTEFILE2ARTICLE); query.append(" r2a, "); query.append(DBHelper.TABLE_REMOTEFILES); query.append(" r WHERE a._id=r2a.articleId and r2a.remotefileId=r.id) "); } } if (lastOpenedArticlesList.length() > 0 && !buildSafeQuery) { query.append(" UNION SELECT c._id AS _id, c.feedId AS feedId, c.title AS title, c.isUnread AS unread, c.updateDate AS updateDate, c.isStarred AS isStarred, c.isPublished AS isPublished FROM "); query.append(DBHelper.TABLE_ARTICLES); query.append(" c, "); query.append(DBHelper.TABLE_FEEDS); query.append(" d WHERE c.feedId=d._id AND c._id IN ("); query.append(lastOpenedArticlesList); query.append(" )"); } query.append(" ORDER BY a.updateDate "); query.append(invertSortArticles ? "ASC" : "DESC"); query.append(" LIMIT 600 "); return query.toString(); } private String buildLabelQuery(boolean overrideDisplayUnread, boolean buildSafeQuery) { String lastOpenedArticlesList = Utils.separateItems(Controller.getInstance().lastOpenedArticles, ","); boolean displayUnread = Controller.getInstance().onlyUnread(); boolean invertSortArticles = Controller.getInstance().invertSortArticlelist(); if (overrideDisplayUnread) displayUnread = false; StringBuilder query = new StringBuilder(); query.append("SELECT a._id AS _id, a.feedId AS feedId, a.title AS title, a.isUnread AS unread, a.updateDate AS updateDate, a.isStarred AS isStarred, a.isPublished AS isPublished FROM "); query.append(DBHelper.TABLE_ARTICLES); query.append(" a, "); query.append(DBHelper.TABLE_ARTICLES2LABELS); query.append(" a2l, "); query.append(DBHelper.TABLE_FEEDS); query.append(" l WHERE a._id=a2l.articleId AND a2l.labelId=l._id"); query.append(" AND a2l.labelId=" + feedId); query.append(displayUnread ? " AND isUnread>0" : ""); if (lastOpenedArticlesList.length() > 0 && !buildSafeQuery) { query.append(" UNION SELECT b._id AS _id, b.feedId AS feedId, b.title AS title, b.isUnread AS unread, b.updateDate AS updateDate, b.isStarred AS isStarred, b.isPublished AS isPublished FROM "); query.append(DBHelper.TABLE_ARTICLES); query.append(" b, "); query.append(DBHelper.TABLE_ARTICLES2LABELS); query.append(" b2m, "); query.append(DBHelper.TABLE_FEEDS); query.append(" m WHERE b2m.labelId=m._id AND b2m.articleId=b._id"); query.append(" AND b._id IN ("); query.append(lastOpenedArticlesList); query.append(" )"); } query.append(" ORDER BY updateDate "); query.append(invertSortArticles ? "ASC" : "DESC"); query.append(" LIMIT 600 "); return query.toString(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/FeedHeadlineCursorHelper.java
Java
gpl3
7,044
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; public class CategoryCursorHelper extends MainCursorHelper { protected static final String TAG = CategoryCursorHelper.class.getSimpleName(); /* * This is quite a hack. Since partial-sorting of sql-results is not possible I wasn't able to sort virtual * categories by id, Labels by title, insert uncategorized feeds there and sort categories by title again. * No I insert these results one by one in a memory-table in the right order, add an auto-increment-column * ("sortId INTEGER PRIMARY KEY") and afterwards select everything from this memory-table sorted by sortId. * Works fine! */ private static final String INSERT = "REPLACE INTO " + MemoryDBOpenHelper.TABLE_NAME + " (_id, title, unread, sortId) VALUES (?, ?, ?, null)"; SQLiteDatabase memoryDb; SQLiteStatement insert; public CategoryCursorHelper(Context context, SQLiteDatabase memoryDb) { super(context); this.memoryDb = memoryDb; insert = memoryDb.compileStatement(INSERT); } @Override public Cursor createCursor(SQLiteDatabase db, boolean overrideDisplayUnread, boolean buildSafeQuery) { boolean displayUnread = Controller.getInstance().onlyUnread(); boolean invertSortFeedCats = Controller.getInstance().invertSortFeedscats(); if (overrideDisplayUnread) displayUnread = false; memoryDb.delete(MemoryDBOpenHelper.TABLE_NAME, null, null); StringBuilder query; // Virtual Feeds if (Controller.getInstance().showVirtual()) { query = new StringBuilder(); query.append("SELECT _id,title,unread FROM "); query.append(DBHelper.TABLE_CATEGORIES); query.append(" WHERE _id>=-4 AND _id<0 ORDER BY _id"); insertValues(db, query.toString()); } // Labels query = new StringBuilder(); query.append("SELECT _id,title,unread FROM "); query.append(DBHelper.TABLE_FEEDS); query.append(" WHERE _id<-10"); query.append(displayUnread ? " AND unread>0" : ""); query.append(" ORDER BY UPPER(title) ASC"); query.append(" LIMIT 500 "); insertValues(db, query.toString()); // "Uncategorized Feeds" query = new StringBuilder(); query.append("SELECT _id,title,unread FROM "); query.append(DBHelper.TABLE_CATEGORIES); query.append(" WHERE _id=0"); insertValues(db, query.toString()); // Categories query = new StringBuilder(); query.append("SELECT _id,title,unread FROM "); query.append(DBHelper.TABLE_CATEGORIES); query.append(" WHERE _id>0"); query.append(displayUnread ? " AND unread>0" : ""); query.append(" ORDER BY UPPER(title) "); query.append(invertSortFeedCats ? "DESC" : "ASC"); query.append(" LIMIT 500 "); insertValues(db, query.toString()); String[] columns = { "_id", "title", "unread" }; return memoryDb.query(MemoryDBOpenHelper.TABLE_NAME, columns, null, null, null, null, null, "600"); } private void insertValues(SQLiteDatabase db, String query) { Cursor c = null; try { c = db.rawQuery(query, null); if (c == null) return; if (c.isBeforeFirst() && !c.moveToFirst()) return; while (true) { insert.bindLong(1, c.getInt(0)); // id insert.bindString(2, c.getString(1)); // title insert.bindLong(3, c.getInt(2)); // unread insert.executeInsert(); if (!c.moveToNext()) break; } } finally { if (c != null && !c.isClosed()) c.close(); } } static class MemoryDBOpenHelper extends SQLiteOpenHelper { public static final String TABLE_NAME = "categories_memory_db"; MemoryDBOpenHelper(Context context) { super(context, null, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER, title TEXT, unread INTEGER, sortId INTEGER PRIMARY KEY)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/CategoryCursorHelper.java
Java
gpl3
5,520
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader.model; import java.util.ArrayList; import java.util.List; import org.ttrssreader.R; import android.content.Context; import android.database.Cursor; import android.view.View; import android.view.ViewGroup; import android.widget.SimpleCursorAdapter; public abstract class MainAdapter extends SimpleCursorAdapter { protected static final String TAG = MainAdapter.class.getSimpleName(); private static final int layout = R.layout.main; protected Context context; public MainAdapter(Context context) { super(context, layout, null, new String[] {}, new int[] {}, 0); this.context = context; } @Override public final long getItemId(int position) { return position; } public final int getId(int position) { int ret = Integer.MIN_VALUE; Cursor cur = getCursor(); if (cur == null) return ret; if (cur.getCount() >= position) if (cur.moveToPosition(position)) ret = cur.getInt(0); return ret; } public final List<Integer> getIds() { List<Integer> ret = new ArrayList<Integer>(); Cursor cur = getCursor(); if (cur == null) return ret; if (cur.moveToFirst()) { while (!cur.isAfterLast()) { ret.add(cur.getInt(0)); cur.move(1); } } return ret; } protected static final CharSequence formatItemTitle(String title, int unread) { if (unread > 0) { return title + " (" + unread + ")"; } else { return title; } } @Override public abstract Object getItem(int position); @Override public abstract View getView(int position, View convertView, ViewGroup parent); }
025003b-rss
ttrss-reader/src/org/ttrssreader/model/MainAdapter.java
Java
gpl3
2,399
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.ttrssreader; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.ProgressBarManager; import org.ttrssreader.controllers.UpdateController; import org.ttrssreader.utils.AsyncTask; import android.app.Application; import android.content.Context; import android.view.WindowManager; public class MyApplication extends Application { protected static final String TAG = MyApplication.class.getSimpleName(); public void onCreate() { super.onCreate(); // make sure AsyncTask is loaded in the Main thread new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { return null; } }.execute(); initSingletons(); } protected void initSingletons() { WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); ProgressBarManager.getInstance(); Controller.getInstance().checkAndInitializeController(this, wm.getDefaultDisplay()); DBHelper.getInstance().checkAndInitializeDB(this); Data.getInstance().checkAndInitializeData(this); UpdateController.getInstance().notifyListeners(); // Notify once to make sure the handler is initialized } @Override public void onLowMemory() { Controller.getInstance().lowMemory(true); super.onLowMemory(); } }
025003b-rss
ttrss-reader/src/org/ttrssreader/MyApplication.java
Java
gpl3
2,049
/** @license Hyphenator X.Y.Z - client side hyphenation for webbrowsers * Copyright (C) 2012 Mathias Nater, Zürich (mathias at mnn dot ch) * Project and Source hosted on http://code.google.com/p/hyphenator/ * * This JavaScript code is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser * General Public License (GNU LGPL) as published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. The code is distributed WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details. * * As additional permission under GNU GPL version 3 section 7, you * may distribute non-source (e.g., minimized or compacted) forms of * that code without the copy of the GNU GPL normally required by * section 4, provided you include this license notice and a URL * through which recipients can access the Corresponding Source. * * * Hyphenator.js contains code from Bram Steins hypher.js-Project: * https://github.com/bramstein/Hypher * * Code from this project is marked in the source and belongs * to the following license: * * Copyright (c) 2011, Bram Stein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* * Comments are jsdoctoolkit formatted. See http://code.google.com/p/jsdoc-toolkit/ */ /* The following comment is for JSLint: */ /*global window */ /*jslint browser: true */ /** * @constructor * @description Provides all functionality to do hyphenation, except the patterns that are loaded * externally. * @author Mathias Nater, <a href = "mailto:mathias@mnn.ch">mathias@mnn.ch</a> * @version X.Y.Z * @namespace Holds all methods and properties * @example * &lt;script src = "Hyphenator.js" type = "text/javascript"&gt;&lt;/script&gt;  * &lt;script type = "text/javascript"&gt;  *   Hyphenator.run();  * &lt;/script&gt; */ var Hyphenator = (function (window) { 'use strict'; /** * @name Hyphenator-contextWindow * @private * @description * contextWindow stores the window for the document to be hyphenated. * If there are frames this will change. * So use contextWindow instead of window! */ var contextWindow = window, /** * @name Hyphenator-supportedLangs * @description * A key-value object that stores supported languages and meta data. * The key is the bcp47 code of the language and the value * is an object containing following informations about the language: * file: filename of the pattern file, * script: script type of the language (e.g. 'latin' for english), this type is abbreviated by an id, * prompt: the sentence prompted to the user, if Hyphenator.js doesn't find a language hint. * @type {Object.<string>, Object>} * @private * @example * Check if language lang is supported: * if (supportedLangs.hasOwnProperty(lang)) */ supportedLangs = (function () { var r = {}, o = function (code, file, script, prompt) { r[code] = {'file': file, 'script': script, 'prompt': prompt}; }; //latin:0, cyrillic: 1, arabic: 2, armenian:3, bengali: 4, devangari: 5, greek: 6 //gujarati: 7, kannada: 8, lao: 9, malayalam: 10, oriya: 11, persian: 12, punjabi: 13, tamil: 14, telugu: 15 // //(language code, file name, script, prompt) o('be', 'be.js', 1, 'Мова гэтага сайта не можа быць вызначаны аўтаматычна. Калі ласка пакажыце мову:'); o('ca', 'ca.js', 0, ''); o('cs', 'cs.js', 0, 'Jazyk této internetové stránky nebyl automaticky rozpoznán. Určete prosím její jazyk:'); o('da', 'da.js', 0, 'Denne websides sprog kunne ikke bestemmes. Angiv venligst sprog:'); o('bn', 'bn.js', 4, ''); o('de', 'de.js', 0, 'Die Sprache dieser Webseite konnte nicht automatisch bestimmt werden. Bitte Sprache angeben:'); o('el', 'el-monoton.js', 6, ''); o('el-monoton', 'el-monoton.js', 6, ''); o('el-polyton', 'el-polyton.js', 6, ''); o('en', 'en-us.js', 0, 'The language of this website could not be determined automatically. Please indicate the main language:'); o('en-gb', 'en-gb.js', 0, 'The language of this website could not be determined automatically. Please indicate the main language:'); o('en-us', 'en-us.js', 0, 'The language of this website could not be determined automatically. Please indicate the main language:'); o('eo', 'eo.js', 0, 'La lingvo de ĉi tiu retpaĝo ne rekoneblas aŭtomate. Bonvolu indiki ĝian ĉeflingvon:'); o('es', 'es.js', 0, 'El idioma del sitio no pudo determinarse autom%E1ticamente. Por favor, indique el idioma principal:'); o('et', 'et.js', 0, 'Veebilehe keele tuvastamine ebaõnnestus, palun valige kasutatud keel:'); o('fi', 'fi.js', 0, 'Sivun kielt%E4 ei tunnistettu automaattisesti. M%E4%E4rit%E4 sivun p%E4%E4kieli:'); o('fr', 'fr.js', 0, 'La langue de ce site n%u2019a pas pu %EAtre d%E9termin%E9e automatiquement. Veuillez indiquer une langue, s.v.p.%A0:'); o('grc', 'grc.js', 6, ''); o('gu', 'gu.js', 7, ''); o('hi', 'hi.js', 5, ''); o('hu', 'hu.js', 0, 'A weboldal nyelvét nem sikerült automatikusan megállapítani. Kérem adja meg a nyelvet:'); o('hy', 'hy.js', 3, 'Չհաջողվեց հայտնաբերել այս կայքի լեզուն։ Խնդրում ենք նշեք հիմնական լեզուն՝'); o('it', 'it.js', 0, 'Lingua del sito sconosciuta. Indicare una lingua, per favore:'); o('kn', 'kn.js', 8, 'ಜಾಲ ತಾಣದ ಭಾಷೆಯನ್ನು ನಿರ್ಧರಿಸಲು ಸಾಧ್ಯವಾಗುತ್ತಿಲ್ಲ. ದಯವಿಟ್ಟು ಮುಖ್ಯ ಭಾಷೆಯನ್ನು ಸೂಚಿಸಿ:'); o('la', 'la.js', 0, ''); o('lt', 'lt.js', 0, 'Nepavyko automatiškai nustatyti šios svetainės kalbos. Prašome įvesti kalbą:'); o('lv', 'lv.js', 0, 'Šīs lapas valodu nevarēja noteikt automātiski. Lūdzu norādiet pamata valodu:'); o('ml', 'ml.js', 10, 'ഈ വെ%u0D2C%u0D4D%u200Cസൈറ്റിന്റെ ഭാഷ കണ്ടുപിടിയ്ക്കാ%u0D28%u0D4D%u200D കഴിഞ്ഞില്ല. ഭാഷ ഏതാണെന്നു തിരഞ്ഞെടുക്കുക:'); o('nb', 'nb-no.js', 0, 'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:'); o('no', 'nb-no.js', 0, 'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:'); o('nb-no', 'nb-no.js', 0, 'Nettstedets språk kunne ikke finnes automatisk. Vennligst oppgi språk:'); o('nl', 'nl.js', 0, 'De taal van deze website kan niet automatisch worden bepaald. Geef de hoofdtaal op:'); o('or', 'or.js', 11, ''); o('pa', 'pa.js', 13, ''); o('pl', 'pl.js', 0, 'Języka tej strony nie można ustalić automatycznie. Proszę wskazać język:'); o('pt', 'pt.js', 0, 'A língua deste site não pôde ser determinada automaticamente. Por favor indique a língua principal:'); o('ru', 'ru.js', 1, 'Язык этого сайта не может быть определен автоматически. Пожалуйста укажите язык:'); o('sk', 'sk.js', 0, ''); o('sl', 'sl.js', 0, 'Jezika te spletne strani ni bilo mogoče samodejno določiti. Prosim navedite jezik:'); o('sr-latn', 'sr-latn.js', 0, 'Jezika te spletne strani ni bilo mogoče samodejno določiti. Prosim navedite jezik:'); o('sv', 'sv.js', 0, 'Spr%E5ket p%E5 den h%E4r webbplatsen kunde inte avg%F6ras automatiskt. V%E4nligen ange:'); o('ta', 'ta.js', 14, ''); o('te', 'te.js', 15, ''); o('tr', 'tr.js', 0, 'Bu web sitesinin dili otomatik olarak tespit edilememiştir. Lütfen dökümanın dilini seçiniz%A0:'); o('uk', 'uk.js', 1, 'Мова цього веб-сайту не може бути визначена автоматично. Будь ласка, вкажіть головну мову:'); o('ro', 'ro.js', 0, 'Limba acestui sit nu a putut fi determinată automat. Alege limba principală:'); return r; }()), /** * @name Hyphenator-basePath * @description * A string storing the basepath from where Hyphenator.js was loaded. * This is used to load the patternfiles. * The basepath is determined dynamically by searching all script-tags for Hyphenator.js * If the path cannot be determined http://hyphenator.googlecode.com/svn/trunk/ is used as fallback. * @type {string} * @private * @see Hyphenator-loadPatterns */ basePath = (function () { var s = contextWindow.document.getElementsByTagName('script'), i = 0, p, src, t = s[i], r = ''; while (!!t) { if (!!t.src) { src = t.src; p = src.indexOf('Hyphenator.js'); if (p !== -1) { r = src.substring(0, p); } } i += 1; t = s[i]; } return !!r ? r : 'http://hyphenator.googlecode.com/svn/trunk/'; }()), /** * @name Hyphenator-isLocal * @private * @description * isLocal is true, if Hyphenator is loaded from the same domain, as the webpage, but false, if * it's loaded from an external source (i.e. directly from google.code) */ isLocal = (function () { var re = false; if (window.location.href.indexOf(basePath) !== -1) { re = true; } return re; }()), /** * @name Hyphenator-documentLoaded * @private * @description * documentLoaded is true, when the DOM has been loaded. This is set by runOnContentLoaded */ documentLoaded = false, /** * @name Hyphenator-persistentConfig * @private * @description * if persistentConfig is set to true (defaults to false), config options and the state of the * toggleBox are stored in DOM-storage (according to the storage-setting). So they haven't to be * set for each page. */ persistentConfig = false, /** * @name Hyphenator-doFrames * @private * @description * switch to control if frames/iframes should be hyphenated, too * defaults to false (frames are a bag of hurt!) */ doFrames = false, /** * @name Hyphenator-dontHyphenate * @description * A key-value object containing all html-tags whose content should not be hyphenated * @type {Object.<string,boolean>} * @private * @see Hyphenator-hyphenateElement */ dontHyphenate = {'script': true, 'code': true, 'pre': true, 'img': true, 'br': true, 'samp': true, 'kbd': true, 'var': true, 'abbr': true, 'acronym': true, 'sub': true, 'sup': true, 'button': true, 'option': true, 'label': true, 'textarea': true, 'input': true, 'math': true, 'svg': true, 'style': true}, /** * @name Hyphenator-enableCache * @description * A variable to set if caching is enabled or not * @type boolean * @default true * @private * @see Hyphenator.config * @see hyphenateWord */ enableCache = true, /** * @name Hyphenator-storageType * @description * A variable to define what html5-DOM-Storage-Method is used ('none', 'local' or 'session') * @type {string} * @default 'local' * @private * @see Hyphenator.config */ storageType = 'local', /** * @name Hyphenator-storage * @description * An alias to the storage-Method defined in storageType. * Set by Hyphenator.run() * @type {Object|undefined} * @default null * @private * @see Hyphenator.run */ storage, /** * @name Hyphenator-enableReducedPatternSet * @description * A variable to set if storing the used patterns is set * @type boolean * @default false * @private * @see Hyphenator.config * @see hyphenateWord * @see Hyphenator.getRedPatternSet */ enableReducedPatternSet = false, /** * @name Hyphenator-enableRemoteLoading * @description * A variable to set if pattern files should be loaded remotely or not * @type boolean * @default true * @private * @see Hyphenator.config * @see Hyphenator-loadPatterns */ enableRemoteLoading = true, /** * @name Hyphenator-displayToggleBox * @description * A variable to set if the togglebox should be displayed or not * @type boolean * @default false * @private * @see Hyphenator.config * @see Hyphenator-toggleBox */ displayToggleBox = false, /** * @name Hyphenator-onError * @description * A function that can be called upon an error. * @see Hyphenator.config * @type {function(Object)} * @private */ onError = function (e) { window.alert("Hyphenator.js says:\n\nAn Error occurred:\n" + e.message); }, /** * @name Hyphenator-createElem * @description * A function alias to document.createElementNS or document.createElement * @type {function(string, Object)} * @private */ createElem = function (tagname, context) { context = context || contextWindow; var el; if (window.document.createElementNS) { el = context.document.createElementNS('http://www.w3.org/1999/xhtml', tagname); } else if (window.document.createElement) { el = context.document.createElement(tagname); } return el; }, /** * @name Hyphenator-css3 * @description * A variable to set if css3 hyphenation should be used * @type boolean * @default false * @private * @see Hyphenator.config */ css3 = false, /** * @name Hyphenator-css3_hsupport * @description * A generated object containing information for CSS3-hyphenation support * { * support: boolean, * property: <the property name to access hyphen-settings>, * languages: <an object containing supported languages> * } * @type object * @default undefined * @private * @see Hyphenator-css3_gethsupport */ css3_h9n, /** * @name Hyphenator-css3_gethsupport * @description * This function sets Hyphenator-css3_h9n for the current UA * @type function * @private * @see Hyphenator-css3_h9n */ css3_gethsupport = function () { var s, createLangSupportChecker = function (prefix) { var testStrings = [ //latin: 0 'aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz', //cyrillic: 1 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя', //arabic: 2 'أبتثجحخدذرزسشصضطظعغفقكلمنهوي', //armenian: 3 'աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆ', //bengali: 4 'ঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣ', //devangari: 5 'ँंःअआइईउऊऋऌएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलळवशषसहऽािीुूृॄेैोौ्॒॑ॠॡॢॣ', //greek: 6 'αβγδεζηθικλμνξοπρσςτυφχψω', //gujarati: 7 'બહઅઆઇઈઉઊઋૠએઐઓઔાિીુૂૃૄૢૣેૈોૌકખગઘઙચછજઝઞટઠડઢણતથદધનપફસભમયરલળવશષ', //kannada: 8 'ಂಃಅಆಇಈಉಊಋಌಎಏಐಒಓಔಕಖಗಘಙಚಛಜಝಞಟಠಡಢಣತಥದಧನಪಫಬಭಮಯರಱಲಳವಶಷಸಹಽಾಿೀುೂೃೄೆೇೈೊೋೌ್ೕೖೞೠೡ', //lao: 9 'ກຂຄງຈຊຍດຕຖທນບປຜຝພຟມຢຣລວສຫອຮະັາິີຶືຸູົຼເແໂໃໄ່້໊໋ໜໝ', //malayalam: 10 'ംഃഅആഇഈഉഊഋഌഎഏഐഒഓഔകഖഗഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമയരറലളഴവശഷസഹാിീുൂൃെേൈൊോൌ്ൗൠൡൺൻർൽൾൿ', //oriya: 11 'ଁଂଃଅଆଇଈଉଊଋଌଏଐଓଔକଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଳଵଶଷସହାିୀୁୂୃେୈୋୌ୍ୗୠୡ', //persian: 12 'أبتثجحخدذرزسشصضطظعغفقكلمنهوي', //punjabi: 13 'ਁਂਃਅਆਇਈਉਊਏਐਓਔਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਲ਼ਵਸ਼ਸਹਾਿੀੁੂੇੈੋੌ੍ੰੱ', //tamil: 14 'ஃஅஆஇஈஉஊஎஏஐஒஓஔகஙசஜஞடணதநனபமயரறலளழவஷஸஹாிீுூெேைொோௌ்ௗ', //telugu: 15 'ఁంఃఅఆఇఈఉఊఋఌఎఏఐఒఓఔకఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరఱలళవశషసహాిీుూృౄెేైొోౌ్ౕౖౠౡ' ], f = function (lang) { var shadow, computedHeight, bdy = window.document.getElementsByTagName('body')[0], r = false; if (supportedLangs.hasOwnProperty(lang)) { //create and append shadow-test-element shadow = createElem('div', window); shadow.id = 'Hyphenator_LanguageChecker'; shadow.style.width = '5em'; shadow.style[prefix] = 'auto'; shadow.style.hyphens = 'auto'; shadow.style.fontSize = '12px'; shadow.style.lineHeight = '12px'; shadow.style.visibility = 'hidden'; shadow.lang = lang; shadow.style['-webkit-locale'] = "'" + lang + "'"; shadow.innerHTML = testStrings[supportedLangs[lang].script]; bdy.appendChild(shadow); //measure its height computedHeight = shadow.offsetHeight; //remove shadow element bdy.removeChild(shadow); r = (computedHeight > 12) ? true : false; } else { r = false; } return r; }; return f; }, r = { support: false, property: '', checkLangSupport: function () {} }; if (window.getComputedStyle) { s = contextWindow.getComputedStyle(contextWindow.document.getElementsByTagName('body')[0], null); } else { //ancient Browsers don't support CSS3 anyway css3_h9n = r; return; } if (s['-webkit-hyphens'] !== undefined) { r.support = true; r.property = '-webkit-hyphens'; r.checkLangSupport = createLangSupportChecker('-webkit-hyphens'); } else if (s.MozHyphens !== undefined) { r.support = true; r.property = '-moz-hyphens'; r.checkLangSupport = createLangSupportChecker('MozHyphens'); } else if (s['-ms-hyphens'] !== undefined) { r.support = true; r.property = '-ms-hyphens'; r.checkLangSupport = createLangSupportChecker('-ms-hyphens'); } css3_h9n = r; }, /** * @name Hyphenator-hyphenateClass * @description * A string containing the css-class-name for the hyphenate class * @type {string} * @default 'hyphenate' * @private * @example * &lt;p class = "hyphenate"&gt;Text&lt;/p&gt; * @see Hyphenator.config */ hyphenateClass = 'hyphenate', /** * @name Hyphenator-classPrefix * @description * A string containing a unique className prefix to be used * whenever Hyphenator sets a CSS-class * @type {string} * @private */ classPrefix = 'Hyphenator' + Math.round(Math.random() * 1000), /** * @name Hyphenator-hideClass * @description * The name of the class that hides elements * @type {string} * @private */ hideClass = classPrefix + 'hide', /** * @name Hyphenator-hideClassRegExp * @description * RegExp to remove hideClass from a list of classes * @type {RegExp} * @private */ hideClassRegExp = new RegExp("\\s?\\b" + hideClass + "\\b", "g"), /** * @name Hyphenator-hideClass * @description * The name of the class that unhides elements * @type {string} * @private */ unhideClass = classPrefix + 'unhide', /** * @name Hyphenator-hideClassRegExp * @description * RegExp to remove unhideClass from a list of classes * @type {RegExp} * @private */ unhideClassRegExp = new RegExp("\\s?\\b" + unhideClass + "\\b", "g"), /** * @name Hyphenator-css3hyphenateClass * @description * The name of the class that hyphenates elements with css3 * @type {string} * @private */ css3hyphenateClass = classPrefix + 'css3hyphenate', /** * @name Hyphenator-css3hyphenateClass * @description * The var where CSSEdit class is stored * @type {Object} * @private */ css3hyphenateClassHandle, /** * @name Hyphenator-dontHyphenateClass * @description * A string containing the css-class-name for elements that should not be hyphenated * @type {string} * @default 'donthyphenate' * @private * @example * &lt;p class = "donthyphenate"&gt;Text&lt;/p&gt; * @see Hyphenator.config */ dontHyphenateClass = 'donthyphenate', /** * @name Hyphenator-min * @description * A number wich indicates the minimal length of words to hyphenate. * @type {number} * @default 6 * @private * @see Hyphenator.config */ min = 6, /** * @name Hyphenator-orphanControl * @description * Control how the last words of a line are handled: * level 1 (default): last word is hyphenated * level 2: last word is not hyphenated * level 3: last word is not hyphenated and last space is non breaking * @type {number} * @default 1 * @private */ orphanControl = 1, /** * @name Hyphenator-isBookmarklet * @description * Indicates if Hyphanetor runs as bookmarklet or not. * @type boolean * @default false * @private */ isBookmarklet = (function () { var loc = null, re = false, scripts = contextWindow.document.getElementsByTagName('script'), i = 0, l = scripts.length; while (!re && i < l) { loc = scripts[i].getAttribute('src'); if (!!loc && loc.indexOf('Hyphenator.js?bm=true') !== -1) { re = true; } i += 1; } return re; }()), /** * @name Hyphenator-mainLanguage * @description * The general language of the document. In contrast to {@link Hyphenator-defaultLanguage}, * mainLanguage is defined by the client (i.e. by the html or by a prompt). * @type {string|null} * @private * @see Hyphenator-autoSetMainLanguage */ mainLanguage = null, /** * @name Hyphenator-defaultLanguage * @description * The language defined by the developper. This language setting is defined by a config option. * It is overwritten by any html-lang-attribute and only taken in count, when no such attribute can * be found (i.e. just before the prompt). * @type {string|null} * @private * @see Hyphenator-autoSetMainLanguage */ defaultLanguage = '', /** * @name Hyphenator-elements * @description * An object holding all elements that have to be hyphenated. This var is filled by * {@link Hyphenator-gatherDocumentInfos} * @type {Array} * @private */ elements = (function () { var Element = function (element) { this.element = element; this.hyphenated = false; this.treated = false; //collected but not hyphenated (dohyphenation is off) }, ElementCollection = function () { this.count = 0; this.hyCount = 0; this.list = {}; }; ElementCollection.prototype = { add: function (el, lang) { if (!this.list.hasOwnProperty(lang)) { this.list[lang] = []; } this.list[lang].push(new Element(el)); this.count += 1; }, each: function (fn) { var k; for (k in this.list) { if (this.list.hasOwnProperty(k)) { if (fn.length === 2) { fn(k, this.list[k]); } else { fn(this.list[k]); } } } } }; return new ElementCollection(); }()), /** * @name Hyphenator-exceptions * @description * An object containing exceptions as comma separated strings for each language. * When the language-objects are loaded, their exceptions are processed, copied here and then deleted. * @see Hyphenator-prepareLanguagesObj * @type {Object} * @private */ exceptions = {}, /** * @name Hyphenator-docLanguages * @description * An object holding all languages used in the document. This is filled by * {@link Hyphenator-gatherDocumentInfos} * @type {Object} * @private */ docLanguages = {}, /** * @name Hyphenator-state * @description * A number that inidcates the current state of the script * 0: not initialized * 1: loading patterns * 2: ready * 3: hyphenation done * 4: hyphenation removed * @type {number} * @private */ state = 0, /** * @name Hyphenator-url * @description * A string containing a RegularExpression to match URL's * @type {string} * @private */ url = '(\\w*:\/\/)?((\\w*:)?(\\w*)@)?((([\\d]{1,3}\\.){3}([\\d]{1,3}))|((www\\.|[a-zA-Z]\\.)?[a-zA-Z0-9\\-\\.]+\\.([a-z]{2,4})))(:\\d*)?(\/[\\w#!:\\.?\\+=&%@!\\-]*)*', // protocoll usr pwd ip or host tld port path /** * @name Hyphenator-mail * @description * A string containing a RegularExpression to match mail-adresses * @type {string} * @private */ mail = '[\\w-\\.]+@[\\w\\.]+', /** * @name Hyphenator-urlRE * @description * A RegularExpressions-Object for url- and mail adress matching * @type {RegExp} * @private */ urlOrMailRE = new RegExp('(' + url + ')|(' + mail + ')', 'i'), /** * @name Hyphenator-zeroWidthSpace * @description * A string that holds a char. * Depending on the browser, this is the zero with space or an empty string. * zeroWidthSpace is used to break URLs * @type {string} * @private */ zeroWidthSpace = (function () { var zws, ua = window.navigator.userAgent.toLowerCase(); zws = String.fromCharCode(8203); //Unicode zero width space if (ua.indexOf('msie 6') !== -1) { zws = ''; //IE6 doesn't support zws } if (ua.indexOf('opera') !== -1 && ua.indexOf('version/10.00') !== -1) { zws = ''; //opera 10 on XP doesn't support zws } return zws; }()), /** * @name Hyphenator-onBeforeWordHyphenation * @description * A method to be called for each word to be hyphenated before it is hyphenated. * Takes the word as a first parameter and its language as a second parameter. * Returns a string that will replace the word to be hyphenated. * @see Hyphenator.config * @type {function()} * @private */ onBeforeWordHyphenation = function (word) { return word; }, /** * @name Hyphenator-onAfterWordHyphenation * @description * A method to be called for each word to be hyphenated after it is hyphenated. * Takes the word as a first parameter and its language as a second parameter. * Returns a string that will replace the word that has been hyphenated. * @see Hyphenator.config * @type {function()} * @private */ onAfterWordHyphenation = function (word) { return word; }, /** * @name Hyphenator-onHyphenationDone * @description * A method to be called, when the last element has been hyphenated * @see Hyphenator.config * @type {function()} * @private */ onHyphenationDone = function () {}, /** * @name Hyphenator-selectorFunction * @description * A function set by the user that has to return a HTMLNodeList or array of Elements to be hyphenated. * By default this is set to false so we can check if a selectorFunction is set… * @see Hyphenator.config * @type {function()} * @private */ selectorFunction = false, /** * @name Hyphenator-mySelectorFunction * @description * A function that has to return a HTMLNodeList or array of Elements to be hyphenated. * By default it uses the classname ('hyphenate') to select the elements. * @type {function()} * @private */ mySelectorFunction = function (hyphenateClass) { var tmp, el = [], i, l; if (window.document.getElementsByClassName) { el = contextWindow.document.getElementsByClassName(hyphenateClass); } else if (window.document.querySelectorAll) { el = contextWindow.document.querySelectorAll('.' + hyphenateClass); } else { tmp = contextWindow.document.getElementsByTagName('*'); l = tmp.length; for (i = 0; i < l; i += 1) { if (tmp[i].className.indexOf(hyphenateClass) !== -1 && tmp[i].className.indexOf(dontHyphenateClass) === -1) { el.push(tmp[i]); } } } return el; }, /** * @name Hyphenator-selectElements * @description * A function that has to return a HTMLNodeList or array of Elements to be hyphenated. * It uses either selectorFunction set by the user (and adds a unique class to each element) * or the default mySelectorFunction. * @type {function()} * @private */ selectElements = function () { var elements; if (selectorFunction) { elements = selectorFunction(); } else { elements = mySelectorFunction(hyphenateClass); } return elements; }, /** * @name Hyphenator-intermediateState * @description * The value of style.visibility of the text while it is hyphenated. * @see Hyphenator.config * @type {string} * @private */ intermediateState = 'hidden', /** * @name Hyphenator-unhide * @description * How hidden elements unhide: either simultaneous (default: 'wait') or progressively. * 'wait' makes Hyphenator.js to wait until all elements are hyphenated (one redraw) * With 'progressive' Hyphenator.js unhides elements as soon as they are hyphenated. * @see Hyphenator.config * @type {string} * @private */ unhide = 'wait', /** * @name Hyphenator-CSSEditors * @description A container array that holds CSSEdit classes * For each window object one CSSEdit class is inserted * @see Hyphenator-CSSEdit * @type {array} * @private */ CSSEditors = [], /** * @name Hyphenator-CSSEditors * @description A custom class with two public methods: setRule() and clearChanges() * Rather sets style for CSS-classes then for single elements * This is used to hide/unhide elements when they are hyphenated. * @see Hyphenator-gatherDocumentInfos * @type {function ()} * @private */ CSSEdit = function (w) { w = w || window; var doc = w.document, //find/create an accessible StyleSheet sheet = (function () { var i, l = doc.styleSheets.length, sheet, element, r = false; for (i = 0; i < l; i += 1) { sheet = doc.styleSheets[i]; try { if (!!sheet.cssRules) { r = sheet; break; } } catch (e) {} } if (r === false) { element = doc.createElement('style'); element.type = 'text/css'; doc.getElementsByTagName('head')[0].appendChild(element); r = doc.styleSheets[doc.styleSheets.length - 1]; } return r; }()), changes = [], findRule = function (sel) { var sheet, rule, sheets = w.document.styleSheets, rules, i, j, r = false; for (i = 0; i < sheets.length; i += 1) { sheet = sheets[i]; try { //FF has issues here with external CSS (s.o.p) if (!!sheet.cssRules) { rules = sheet.cssRules; } else if (!!sheet.rules) { // IE < 9 rules = sheet.rules; } } catch (e) { //do nothing //console.log(e); } if (!!rules && !!rules.length) { for (j = 0; j < rules.length; j += 1) { rule = rules[j]; if (rule.selectorText === sel) { r = { index: j, rule: rule }; } } } } return r; }, addRule = function (sel, rulesStr) { var i, r; if (!!sheet.insertRule) { if (!!sheet.cssRules) { i = sheet.cssRules.length; } else { i = 0; } r = sheet.insertRule(sel + '{' + rulesStr + '}', i); } else if (!!sheet.addRule) { // IE < 9 if (!!sheet.rules) { i = sheet.rules.length; } else { i = 0; } sheet.addRule(sel, rulesStr, i); r = i; } return r; }, removeRule = function (sheet, index) { if (sheet.deleteRule) { sheet.deleteRule(index); } else { // IE < 9 sheet.removeRule(index); } }; return { setRule: function (sel, rulesString) { var i, existingRule, cssText; existingRule = findRule(sel); if (!!existingRule) { if (!!existingRule.rule.cssText) { cssText = existingRule.rule.cssText; } else { // IE < 9 cssText = existingRule.rule.style.cssText.toLowerCase(); } if (cssText === '.' + hyphenateClass + ' { visibility: hidden; }') { //browsers w/o IE < 9 and no additional style defs: //add to [changes] for later removal changes.push({sheet: existingRule.rule.parentStyleSheet, index: existingRule.index}); } else if (cssText.indexOf('visibility: hidden') !== -1) { // IE < 9 or additional style defs: // add new rule i = addRule(sel, rulesString); //add to [changes] for later removal changes.push({sheet: sheet, index: i}); // clear existing def existingRule.rule.style.visibility = ''; } else { addRule(sel, rulesString); } } else { i = addRule(sel, rulesString); changes.push({sheet: sheet, index: i}); } }, clearChanges: function () { var change = changes.pop(); while (!!change) { removeRule(change.sheet, change.index); change = changes.pop(); } } }; }, /** * @name Hyphenator-hyphen * @description * A string containing the character for in-word-hyphenation * @type {string} * @default the soft hyphen * @private * @see Hyphenator.config */ hyphen = String.fromCharCode(173), /** * @name Hyphenator-urlhyphen * @description * A string containing the character for url/mail-hyphenation * @type {string} * @default the zero width space * @private * @see Hyphenator.config * @see Hyphenator-zeroWidthSpace */ urlhyphen = zeroWidthSpace, /** * @name Hyphenator-safeCopy * @description * Defines wether work-around for copy issues is active or not * Not supported by Opera (no onCopy handler) * @type boolean * @default true * @private * @see Hyphenator.config * @see Hyphenator-registerOnCopy */ safeCopy = true, /* * runWhenLoaded is based od jQuery.bindReady() * see * jQuery JavaScript Library v1.3.2 * http://jquery.com/ * * Copyright (c) 2009 John Resig * Dual licensed under the MIT and GPL licenses. * http://docs.jquery.com/License * * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) * Revision: 6246 */ /** * @name Hyphenator-runWhenLoaded * @description * A crossbrowser solution for the DOMContentLoaded-Event based on jQuery * <a href = "http://jquery.com/</a> * I added some functionality: e.g. support for frames and iframes… * @param {Object} w the window-object * @param {function()} f the function to call onDOMContentLoaded * @private */ runWhenLoaded = function (w, f) { var toplevel, hyphRunForThis = {}, add = window.document.addEventListener ? 'addEventListener' : 'attachEvent', rem = window.document.addEventListener ? 'removeEventListener' : 'detachEvent', pre = window.document.addEventListener ? '' : 'on', init = function (context) { if (!hyphRunForThis[context.location.href]) { contextWindow = context || window; f(); hyphRunForThis[contextWindow.location.href] = true; } }, doScrollCheck = function () { try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ w.document.documentElement.doScroll("left"); } catch (error) { window.setTimeout(doScrollCheck, 1); return; } // and execute any waiting functions documentLoaded = true; init(w); }, doOnEvent = function (e) { var i, fl, haveAccess; if (!!e && e.type === 'readystatechange' && w.document.readyState !== 'interactive' && w.document.readyState !== 'complete') { return; } //DOM is ready/interactive, but frames may not be loaded yet! //cleanup events w.document[rem](pre + 'DOMContentLoaded', doOnEvent, false); w.document[rem](pre + 'readystatechange', doOnEvent, false); //check frames fl = w.frames.length; if (fl === 0) { //there are no frames! //cleanup events w[rem](pre + 'load', doOnEvent, false); documentLoaded = true; } else if (doFrames && fl > 0) { //we have frames, so wait for onload and then initiate runWhenLoaded recursevly for each frame: if (!!e && e.type === 'load') { //cleanup events w[rem](pre + 'load', doOnEvent, false); for (i = 0; i < fl; i += 1) { haveAccess = undefined; //try catch isn't enough for webkit try { //opera throws only on document.toString-access haveAccess = window.frames[i].document.toString(); } catch (err) { haveAccess = undefined; } if (!!haveAccess) { runWhenLoaded(w.frames[i], f); } } } } init(w); }; if (documentLoaded || w.document.readyState === 'complete') { //Hyphenator has run already (documentLoaded is true) or //it has been loaded after onLoad documentLoaded = true; doOnEvent({type: 'load'}); } else { //register events w.document[add](pre + 'DOMContentLoaded', doOnEvent, false); w.document[add](pre + 'readystatechange', doOnEvent, false); w[add](pre + 'load', doOnEvent, false); toplevel = false; try { toplevel = !window.frameElement; } catch (e) {} if (toplevel && w.document.documentElement.doScroll) { doScrollCheck(); //calls init() } } }, /** * @name Hyphenator-getLang * @description * Gets the language of an element. If no language is set, it may use the {@link Hyphenator-mainLanguage}. * @param {Object} el The first parameter is an DOM-Element-Object * @param {boolean} fallback The second parameter is a boolean to tell if the function should return the {@link Hyphenator-mainLanguage} * if there's no language found for the element. * @private */ getLang = function (el, fallback) { try { return !!el.getAttribute('lang') ? el.getAttribute('lang').toLowerCase() : !!el.getAttribute('xml:lang') ? el.getAttribute('xml:lang').toLowerCase() : el.tagName.toLowerCase() !== 'html' ? getLang(el.parentNode, fallback) : fallback ? mainLanguage : null; } catch (e) {} }, /** * @name Hyphenator-autoSetMainLanguage * @description * Retrieves the language of the document from the DOM. * The function looks in the following places: * <ul> * <li>lang-attribute in the html-tag</li> * <li>&lt;meta http-equiv = "content-language" content = "xy" /&gt;</li> * <li>&lt;meta name = "DC.Language" content = "xy" /&gt;</li> * <li>&lt;meta name = "language" content = "xy" /&gt;</li> * </li> * If nothing can be found a prompt using {@link Hyphenator-languageHint} and a prompt-string is displayed. * If the retrieved language is in the object {@link Hyphenator-supportedLangs} it is copied to {@link Hyphenator-mainLanguage} * @private */ autoSetMainLanguage = function (w) { w = w || contextWindow; var el = w.document.getElementsByTagName('html')[0], m = w.document.getElementsByTagName('meta'), i, getLangFromUser = function () { var mainLanguage, text = '', dH = 300, dW = 450, dX = Math.floor((w.outerWidth - dW) / 2) + window.screenX, dY = Math.floor((w.outerHeight - dH) / 2) + window.screenY, ul = '', languageHint; if (!!window.showModalDialog) { mainLanguage = window.showModalDialog(basePath + 'modalLangDialog.html', supportedLangs, "dialogWidth: " + dW + "px; dialogHeight: " + dH + "px; dialogtop: " + dY + "; dialogleft: " + dX + "; center: on; resizable: off; scroll: off;"); } else { languageHint = (function () { var k, r = ''; for (k in supportedLangs) { if (supportedLangs.hasOwnProperty(k)) { r += k + ', '; } } r = r.substring(0, r.length - 2); return r; }()); ul = window.navigator.language || window.navigator.userLanguage; ul = ul.substring(0, 2); if (!!supportedLangs[ul] && supportedLangs[ul].prompt !== '') { text = supportedLangs[ul].prompt; } else { text = supportedLangs.en.prompt; } text += ' (ISO 639-1)\n\n' + languageHint; mainLanguage = window.prompt(window.unescape(text), ul).toLowerCase(); } return mainLanguage; }; mainLanguage = getLang(el, false); if (!mainLanguage) { for (i = 0; i < m.length; i += 1) { //<meta http-equiv = "content-language" content="xy"> if (!!m[i].getAttribute('http-equiv') && (m[i].getAttribute('http-equiv').toLowerCase() === 'content-language')) { mainLanguage = m[i].getAttribute('content').toLowerCase(); } //<meta name = "DC.Language" content="xy"> if (!!m[i].getAttribute('name') && (m[i].getAttribute('name').toLowerCase() === 'dc.language')) { mainLanguage = m[i].getAttribute('content').toLowerCase(); } //<meta name = "language" content = "xy"> if (!!m[i].getAttribute('name') && (m[i].getAttribute('name').toLowerCase() === 'language')) { mainLanguage = m[i].getAttribute('content').toLowerCase(); } } } //get lang for frame from enclosing document if (!mainLanguage && doFrames && (!!contextWindow.frameElement)) { autoSetMainLanguage(window.parent); } //fallback to defaultLang if set if (!mainLanguage && defaultLanguage !== '') { mainLanguage = defaultLanguage; } //ask user for lang if (!mainLanguage) { mainLanguage = getLangFromUser(); } el.lang = mainLanguage; }, /** * @name Hyphenator-gatherDocumentInfos * @description * This method runs through the DOM and executes the process()-function on: * - every node returned by the {@link Hyphenator-selectorFunction}. * The process()-function copies the element to the elements-variable, sets its visibility * to intermediateState, retrieves its language and recursivly descends the DOM-tree until * the child-Nodes aren't of type 1 * @private */ gatherDocumentInfos = function () { var elToProcess, tmp, i = 0, process = function (el, lang) { var n, i = 0, hyphenate = true; if (el.lang && typeof (el.lang) === 'string') { lang = el.lang.toLowerCase(); //copy attribute-lang to internal lang } else if (lang) { lang = lang.toLowerCase(); } else { lang = getLang(el, true); } //if css3-hyphenation is supported: use it! if (css3 && css3_h9n.support && !!css3_h9n.checkLangSupport(lang)) { css3hyphenateClassHandle = new CSSEdit(contextWindow); css3hyphenateClassHandle.setRule('.' + css3hyphenateClass, css3_h9n.property + ': auto;'); css3hyphenateClassHandle.setRule('.' + dontHyphenateClass, css3_h9n.property + ': none;'); css3hyphenateClassHandle.setRule('.' + css3hyphenateClass, '-webkit-locale : ' + lang + ';'); el.className = el.className + ' ' + css3hyphenateClass; } else { if (supportedLangs.hasOwnProperty(lang)) { docLanguages[lang] = true; } else { if (supportedLangs.hasOwnProperty(lang.split('-')[0])) { //try subtag lang = lang.split('-')[0]; docLanguages[lang] = true; } else if (!isBookmarklet) { hyphenate = false; onError(new Error('Language "' + lang + '" is not yet supported.')); } } if (hyphenate) { if (intermediateState === 'hidden') { el.className = el.className + ' ' + hideClass; } elements.add(el, lang); } } n = el.childNodes[i]; while (!!n) { if (n.nodeType === 1 && !dontHyphenate[n.nodeName.toLowerCase()] && n.className.indexOf(dontHyphenateClass) === -1 && !elToProcess[n]) { process(n, lang); } i += 1; n = el.childNodes[i]; } }; if (css3) { css3_gethsupport(); } if (isBookmarklet) { elToProcess = contextWindow.document.getElementsByTagName('body')[0]; process(elToProcess, mainLanguage); } else { if (!css3 && intermediateState === 'hidden') { CSSEditors.push(new CSSEdit(contextWindow)); CSSEditors[CSSEditors.length - 1].setRule('.' + hyphenateClass, 'visibility: hidden;'); CSSEditors[CSSEditors.length - 1].setRule('.' + hideClass, 'visibility: hidden;'); CSSEditors[CSSEditors.length - 1].setRule('.' + unhideClass, 'visibility: visible;'); } elToProcess = selectElements(); tmp = elToProcess[i]; while (!!tmp) { process(tmp, ''); i += 1; tmp = elToProcess[i]; } } if (elements.count === 0) { //nothing to hyphenate or all hyphenated by css3 for (i = 0; i < CSSEditors.length; i += 1) { CSSEditors[i].clearChanges(); } state = 3; onHyphenationDone(); } }, /** * @name Hyphenator-createTrie * @description * converts patterns of the given language in a trie * @private * @param {string} lang the language whose patterns shall be converted */ convertPatterns = function (lang) { /** @license BSD licenced code * The following code is based on code from hypher.js and adapted for Hyphenator.js * Copyright (c) 2011, Bram Stein */ var size = 0, tree = { tpoints: [] }, patterns, pattern, i, j, k, patternObject = Hyphenator.languages[lang].patterns, c, chars, points, t, p, codePoint, test = 'in3se', rf, getPoints = (function () { //IE<9 doesn't act like other browsers: doesn't preserve the separators if (test.split(/\D/).length === 1) { rf = function (pattern) { pattern = pattern.replace(/\D/gi, ' '); return pattern.split(' '); }; } else { rf = function (pattern) { return pattern.split(/\D/); }; } return rf; }()); for (size in patternObject) { if (patternObject.hasOwnProperty(size)) { patterns = patternObject[size].match(new RegExp('.{1,' + (+size) + '}', 'g')); i = 0; pattern = patterns[i]; while (!!pattern) { chars = pattern.replace(/[\d]/g, '').split(''); points = getPoints(pattern); t = tree; j = 0; c = chars[j]; while (!!c) { codePoint = c.charCodeAt(0); if (!t[codePoint]) { t[codePoint] = {}; } t = t[codePoint]; j += 1; c = chars[j]; } t.tpoints = []; for (k = 0; k < points.length; k += 1) { p = points[k]; t.tpoints.push((p === "") ? 0 : p); } i += 1; pattern = patterns[i]; } } } Hyphenator.languages[lang].patterns = tree; /** * end of BSD licenced code from hypher.js */ }, /** * @name Hyphenator-recreatePattern * @description * Recreates the pattern for the reducedPatternSet * @private */ recreatePattern = function (pattern, nodePoints) { var r = [], c = pattern.split(''), i; for (i = 0; i < nodePoints.length; i += 1) { if (nodePoints[i] !== 0) { r.push(nodePoints[i]); } if (c[i]) { r.push(c[i]); } } return r.join(''); }, /** * @name Hyphenator-convertExceptionsToObject * @description * Converts a list of comma seprated exceptions to an object: * 'Fortran,Hy-phen-a-tion' -> {'Fortran':'Fortran','Hyphenation':'Hy-phen-a-tion'} * @private * @param {string} exc a comma separated string of exceptions (without spaces) */ convertExceptionsToObject = function (exc) { var w = exc.split(', '), r = {}, i, l, key; for (i = 0, l = w.length; i < l; i += 1) { key = w[i].replace(/-/g, ''); if (!r.hasOwnProperty(key)) { r[key] = w[i]; } } return r; }, /** * @name Hyphenator-loadPatterns * @description * Checks if the requested file is available in the network. * Adds a &lt;script&gt;-Tag to the DOM to load an externeal .js-file containing patterns and settings for the given language. * If the given language is not in the {@link Hyphenator-supportedLangs}-Object it returns. * One may ask why we are not using AJAX to load the patterns. The XMLHttpRequest-Object * has a same-origin-policy. This makes the Bookmarklet impossible. * @param {string} lang The language to load the patterns for * @private * @see Hyphenator-basePath */ loadPatterns = function (lang) { var url, xhr, head, script; if (supportedLangs.hasOwnProperty(lang) && !Hyphenator.languages[lang]) { url = basePath + 'patterns/' + supportedLangs[lang].file; } else { return; } if (isLocal && !isBookmarklet) { //check if 'url' is available: xhr = null; try { // Mozilla, Opera, Safari and Internet Explorer (ab v7) xhr = new window.XMLHttpRequest(); } catch (e) { try { //IE>=6 xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { try { //IE>=5 xhr = new window.ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) { xhr = null; } } } if (xhr) { xhr.open('HEAD', url, true); xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 404) { onError(new Error('Could not load\n' + url)); delete docLanguages[lang]; return; } } }; xhr.send(null); } } if (createElem) { head = window.document.getElementsByTagName('head').item(0); script = createElem('script', window); script.src = url; script.type = 'text/javascript'; head.appendChild(script); } }, /** * @name Hyphenator-prepareLanguagesObj * @description * Adds a cache to each language and converts the exceptions-list to an object. * If storage is active the object is stored there. * @private * @param {string} lang the language ob the lang-obj */ prepareLanguagesObj = function (lang) { var lo = Hyphenator.languages[lang], wrd; if (!lo.prepared) { if (enableCache) { lo.cache = {}; //Export //lo['cache'] = lo.cache; } if (enableReducedPatternSet) { lo.redPatSet = {}; } //add exceptions from the pattern file to the local 'exceptions'-obj if (lo.hasOwnProperty('exceptions')) { Hyphenator.addExceptions(lang, lo.exceptions); delete lo.exceptions; } //copy global exceptions to the language specific exceptions if (exceptions.hasOwnProperty('global')) { if (exceptions.hasOwnProperty(lang)) { exceptions[lang] += ', ' + exceptions.global; } else { exceptions[lang] = exceptions.global; } } //move exceptions from the the local 'exceptions'-obj to the 'language'-object if (exceptions.hasOwnProperty(lang)) { lo.exceptions = convertExceptionsToObject(exceptions[lang]); delete exceptions[lang]; } else { lo.exceptions = {}; } convertPatterns(lang); wrd = '[\\w' + lo.specialChars + '@' + String.fromCharCode(173) + String.fromCharCode(8204) + '-]{' + min + ',}'; lo.genRegExp = new RegExp('(' + url + ')|(' + mail + ')|(' + wrd + ')', 'gi'); lo.prepared = true; } if (!!storage) { try { storage.setItem(lang, window.JSON.stringify(lo)); } catch (e) { onError(e); } } }, /** * @name Hyphenator-prepare * @description * This funtion prepares the Hyphenator-Object: If RemoteLoading is turned off, it assumes * that the patternfiles are loaded, all conversions are made and the callback is called. * If storage is active the object is retrieved there. * If RemoteLoading is on (default), it loads the pattern files and waits until they are loaded, * by repeatedly checking Hyphenator.languages. If a patterfile is loaded the patterns are * converted to their object style and the lang-object extended. * Finally the callback is called. * @private */ prepare = function (callback) { var lang, interval, tmp1, tmp2; if (!enableRemoteLoading) { for (lang in Hyphenator.languages) { if (Hyphenator.languages.hasOwnProperty(lang)) { prepareLanguagesObj(lang); } } state = 2; callback('*'); return; } // get all languages that are used and preload the patterns for (lang in docLanguages) { if (docLanguages.hasOwnProperty(lang)) { if (!!storage && storage.test(lang)) { Hyphenator.languages[lang] = window.JSON.parse(storage.getItem(lang)); if (exceptions.hasOwnProperty('global')) { tmp1 = convertExceptionsToObject(exceptions.global); for (tmp2 in tmp1) { if (tmp1.hasOwnProperty(tmp2)) { Hyphenator.languages[lang].exceptions[tmp2] = tmp1[tmp2]; } } } //Replace exceptions since they may have been changed: if (exceptions.hasOwnProperty(lang)) { tmp1 = convertExceptionsToObject(exceptions[lang]); for (tmp2 in tmp1) { if (tmp1.hasOwnProperty(tmp2)) { Hyphenator.languages[lang].exceptions[tmp2] = tmp1[tmp2]; } } delete exceptions[lang]; } //Replace genRegExp since it may have been changed: tmp1 = '[\\w' + Hyphenator.languages[lang].specialChars + '@' + String.fromCharCode(173) + String.fromCharCode(8204) + '-]{' + min + ',}'; Hyphenator.languages[lang].genRegExp = new RegExp('(' + url + ')|(' + mail + ')|(' + tmp1 + ')', 'gi'); delete docLanguages[lang]; callback(lang); } else { loadPatterns(lang); } } } // else async wait until patterns are loaded, then hyphenate interval = window.setInterval(function () { var finishedLoading = true, lang; for (lang in docLanguages) { if (docLanguages.hasOwnProperty(lang)) { finishedLoading = false; if (!!Hyphenator.languages[lang]) { delete docLanguages[lang]; //do conversion while other patterns are loading: prepareLanguagesObj(lang); callback(lang); } } } if (finishedLoading) { window.clearInterval(interval); state = 2; } }, 100); }, /** * @name Hyphenator-switchToggleBox * @description * Creates or hides the toggleBox: a small button to turn off/on hyphenation on a page. * @see Hyphenator.config * @private */ toggleBox = function () { var bdy, myTextNode, text = (Hyphenator.doHyphenation ? 'Hy-phen-a-tion' : 'Hyphenation'), myBox = contextWindow.document.getElementById('HyphenatorToggleBox'); if (!!myBox) { myBox.firstChild.data = text; } else { bdy = contextWindow.document.getElementsByTagName('body')[0]; myBox = createElem('div', contextWindow); myBox.setAttribute('id', 'HyphenatorToggleBox'); myBox.setAttribute('class', dontHyphenateClass); myTextNode = contextWindow.document.createTextNode(text); myBox.appendChild(myTextNode); myBox.onclick = Hyphenator.toggleHyphenation; myBox.style.position = 'absolute'; myBox.style.top = '0px'; myBox.style.right = '0px'; myBox.style.margin = '0'; myBox.style.backgroundColor = '#AAAAAA'; myBox.style.color = '#FFFFFF'; myBox.style.font = '6pt Arial'; myBox.style.letterSpacing = '0.2em'; myBox.style.padding = '3px'; myBox.style.cursor = 'pointer'; myBox.style.WebkitBorderBottomLeftRadius = '4px'; myBox.style.MozBorderRadiusBottomleft = '4px'; myBox.style.borderBottomLeftRadius = '4px'; bdy.appendChild(myBox); } }, /** * @name Hyphenator-hyphenateWord * @description * This function is the heart of Hyphenator.js. It returns a hyphenated word. * * If there's already a {@link Hyphenator-hypen} in the word, the word is returned as it is. * If the word is in the exceptions list or in the cache, it is retrieved from it. * If there's a '-' put a zeroWidthSpace after the '-' and hyphenate the parts. * @param {string} lang The language of the word * @param {string} word The word * @returns string The hyphenated word * @public */ hyphenateWord = function (lang, word) { var lo = Hyphenator.languages[lang], parts, l, subst, w, characters, origWord, originalCharacters, wordLength, i, j, k, node, points = [], characterPoints = [], nodePoints, nodePointsLength, m = Math.max, trie, result = [''], pattern, r; word = onBeforeWordHyphenation(word, lang); if (word === '') { r = ''; } else if (enableCache && lo.cache.hasOwnProperty(word)) { //the word is in the cache r = lo.cache[word]; } else if (word.indexOf(hyphen) !== -1) { //word already contains shy; -> leave at it is! r = word; } else if (lo.exceptions.hasOwnProperty(word)) { //the word is in the exceptions list r = lo.exceptions[word].replace(/-/g, hyphen); } else if (word.indexOf('-') !== -1) { //word contains '-' -> hyphenate the parts separated with '-' parts = word.split('-'); for (i = 0, l = parts.length; i < l; i += 1) { parts[i] = hyphenateWord(lang, parts[i]); } r = parts.join('-'); } else { origWord = word; w = word = '_' + word + '_'; if (!!lo.charSubstitution) { for (subst in lo.charSubstitution) { if (lo.charSubstitution.hasOwnProperty(subst)) { w = w.replace(new RegExp(subst, 'g'), lo.charSubstitution[subst]); } } } if (origWord.indexOf("'") !== -1) { w = w.replace("'", "’"); //replace APOSTROPHE with RIGHT SINGLE QUOTATION MARK (since the latter is used in the patterns) } /** @license BSD licenced code * The following code is based on code from hypher.js * Copyright (c) 2011, Bram Stein */ characters = w.toLowerCase().split(''); originalCharacters = word.split(''); wordLength = characters.length; trie = lo.patterns; for (i = 0; i < wordLength; i += 1) { points[i] = 0; characterPoints[i] = characters[i].charCodeAt(0); } for (i = 0; i < wordLength; i += 1) { pattern = ''; node = trie; for (j = i; j < wordLength; j += 1) { node = node[characterPoints[j]]; if (node) { if (enableReducedPatternSet) { pattern += String.fromCharCode(characterPoints[j]); } nodePoints = node.tpoints; if (nodePoints) { if (enableReducedPatternSet) { if (!lo.redPatSet) { lo.redPatSet = {}; } lo.redPatSet[pattern] = recreatePattern(pattern, nodePoints); } for (k = 0, nodePointsLength = nodePoints.length; k < nodePointsLength; k += 1) { points[i + k] = m(points[i + k], nodePoints[k]); } } } else { break; } } } for (i = 1; i < wordLength - 1; i += 1) { if (i > lo.leftmin && i < (wordLength - lo.rightmin) && points[i] % 2) { result.push(originalCharacters[i]); } else { result[result.length - 1] += originalCharacters[i]; } } r = result.join(hyphen); /** * end of BSD licenced code from hypher.js */ } r = onAfterWordHyphenation(r, lang); if (enableCache) { //put the word in the cache lo.cache[origWord] = r; } return r; }, /** * @name Hyphenator-hyphenateURL * @description * Puts {@link Hyphenator-urlhyphen} after each no-alphanumeric char that my be in a URL. * @param {string} url to hyphenate * @returns string the hyphenated URL * @public */ hyphenateURL = function (url) { return url.replace(/([:\/\.\?#&_,;!@]+)/gi, '$&' + urlhyphen); }, /** * @name Hyphenator-removeHyphenationFromElement * @description * Removes all hyphens from the element. If there are other elements, the function is * called recursively. * Removing hyphens is usefull if you like to copy text. Some browsers are buggy when the copy hyphenated texts. * @param {Object} el The element where to remove hyphenation. * @public */ removeHyphenationFromElement = function (el) { var h, i = 0, n; switch (hyphen) { case '|': h = '\\|'; break; case '+': h = '\\+'; break; case '*': h = '\\*'; break; default: h = hyphen; } n = el.childNodes[i]; while (!!n) { if (n.nodeType === 3) { n.data = n.data.replace(new RegExp(h, 'g'), ''); n.data = n.data.replace(new RegExp(zeroWidthSpace, 'g'), ''); } else if (n.nodeType === 1) { removeHyphenationFromElement(n); } i += 1; n = el.childNodes[i]; } }, /** * @name Hyphenator-oncopyHandler * @description * The function called by registerOnCopy * @private */ oncopyHandler, /** * @name Hyphenator-removeOnCopy * @description * Method to remove copy event handler from the given element * @param object a html object from witch we remove the event * @private */ removeOnCopy = function (el) { var body = el.ownerDocument.getElementsByTagName('body')[0]; if (!body) { return; } el = el || body; if (window.removeEventListener) { el.removeEventListener("copy", oncopyHandler, true); } else { el.detachEvent("oncopy", oncopyHandler); } }, /** * @name Hyphenator-registerOnCopy * @description * Huge work-around for browser-inconsistency when it comes to * copying of hyphenated text. * The idea behind this code has been provided by http://github.com/aristus/sweet-justice * sweet-justice is under BSD-License * @param object an HTML element where the copy event will be registered to * @private */ registerOnCopy = function (el) { var body = el.ownerDocument.getElementsByTagName('body')[0], shadow, selection, range, rangeShadow, restore; oncopyHandler = function (e) { e = e || window.event; var target = e.target || e.srcElement, currDoc = target.ownerDocument, body = currDoc.getElementsByTagName('body')[0], targetWindow = currDoc.defaultView || currDoc.parentWindow; if (target.tagName && dontHyphenate[target.tagName.toLowerCase()]) { //Safari needs this return; } //create a hidden shadow element shadow = currDoc.createElement('div'); //Moving the element out of the screen doesn't work for IE9 (https://connect.microsoft.com/IE/feedback/details/663981/) //shadow.style.overflow = 'hidden'; //shadow.style.position = 'absolute'; //shadow.style.top = '-5000px'; //shadow.style.height = '1px'; //doing this instead: shadow.style.color = window.getComputedStyle ? targetWindow.getComputedStyle(body, null).backgroundColor : '#FFFFFF'; shadow.style.fontSize = '0px'; body.appendChild(shadow); if (!!window.getSelection) { //FF3, Webkit, IE9 e.stopPropagation(); selection = targetWindow.getSelection(); range = selection.getRangeAt(0); shadow.appendChild(range.cloneContents()); removeHyphenationFromElement(shadow); selection.selectAllChildren(shadow); restore = function () { shadow.parentNode.removeChild(shadow); selection.removeAllRanges(); //IE9 needs that selection.addRange(range); }; } else { // IE<9 e.cancelBubble = true; selection = targetWindow.document.selection; range = selection.createRange(); shadow.innerHTML = range.htmlText; removeHyphenationFromElement(shadow); rangeShadow = body.createTextRange(); rangeShadow.moveToElementText(shadow); rangeShadow.select(); restore = function () { shadow.parentNode.removeChild(shadow); if (range.text !== "") { range.select(); } }; } window.setTimeout(restore, 0); }; if (!body) { return; } el = el || body; if (window.addEventListener) { el.addEventListener("copy", oncopyHandler, true); } else { el.attachEvent("oncopy", oncopyHandler); } }, /** * @name Hyphenator-checkIfAllDone * @description * Checks if all Elements are hyphenated, unhides them and fires onHyphenationDone() * @private */ checkIfAllDone = function () { var allDone = true, i; elements.each(function (ellist) { var i, l = ellist.length; for (i = 0; i < l; i += 1) { allDone = allDone && ellist[i].hyphenated; } }); if (allDone) { if (intermediateState === 'hidden' && unhide === 'progressive') { elements.each(function (ellist) { var i, l = ellist.length, el; for (i = 0; i < l; i += 1) { el = ellist[i].element; el.className = el.className.replace(unhideClassRegExp, ''); if (el.className === '') { el.removeAttribute('class'); } } }); } for (i = 0; i < CSSEditors.length; i += 1) { CSSEditors[i].clearChanges(); } state = 3; onHyphenationDone(); } }, /** * @name Hyphenator-hyphenateElement * @description * Takes the content of the given element and - if there's text - replaces the words * by hyphenated words. If there's another element, the function is called recursively. * When all words are hyphenated, the visibility of the element is set to 'visible'. * @param {Object} el The element to hyphenate * @private */ hyphenateElement = function (lang, elo) { var el = elo.element, hyphenate, n, i, r, controlOrphans = function (part) { var h, r; switch (hyphen) { case '|': h = '\\|'; break; case '+': h = '\\+'; break; case '*': h = '\\*'; break; default: h = hyphen; } if (orphanControl >= 2) { //remove hyphen points from last word r = part.split(' '); r[1] = r[1].replace(new RegExp(h, 'g'), ''); r[1] = r[1].replace(new RegExp(zeroWidthSpace, 'g'), ''); r = r.join(' '); } if (orphanControl === 3) { //replace spaces by non breaking spaces r = r.replace(/[ ]+/g, String.fromCharCode(160)); } return r; }; if (Hyphenator.languages.hasOwnProperty(lang)) { hyphenate = function (word) { if (!Hyphenator.doHyphenation) { r = word; } else if (urlOrMailRE.test(word)) { r = hyphenateURL(word); } else { r = hyphenateWord(lang, word); } return r; }; if (safeCopy && (el.tagName.toLowerCase() !== 'body')) { registerOnCopy(el); } i = 0; n = el.childNodes[i]; while (!!n) { if (n.nodeType === 3 && n.data.length >= min) { //type 3 = #text -> hyphenate! n.data = n.data.replace(Hyphenator.languages[lang].genRegExp, hyphenate); if (orphanControl !== 1) { n.data = n.data.replace(/[\S]+ [\S]+$/, controlOrphans); } } i += 1; n = el.childNodes[i]; } } if (intermediateState === 'hidden' && unhide === 'wait') { el.className = el.className.replace(hideClassRegExp, ''); if (el.className === '') { el.removeAttribute('class'); } } if (intermediateState === 'hidden' && unhide === 'progressive') { el.className = el.className.replace(hideClassRegExp, ' ' + unhideClass); } elo.hyphenated = true; elements.hyCount += 1; if (elements.count <= elements.hyCount) { checkIfAllDone(); } }, /** * @name Hyphenator-hyphenateLanguageElements * @description * Calls hyphenateElement() for all elements of the specified language. * If the language is '*' then all elements are hyphenated. * This is done with a setTimout * to prevent a "long running Script"-alert when hyphenating large pages. * Therefore a tricky bind()-function was necessary. * @private */ hyphenateLanguageElements = function (lang) { function bind(fun, arg1, arg2) { return function () { return fun(arg1, arg2); }; } var i, l; if (lang === '*') { elements.each(function (lang, ellist) { var i, l = ellist.length; for (i = 0; i < l; i += 1) { window.setTimeout(bind(hyphenateElement, lang, ellist[i]), 0); } }); } else { if (elements.list.hasOwnProperty(lang)) { l = elements.list[lang].length; for (i = 0; i < l; i += 1) { window.setTimeout(bind(hyphenateElement, lang, elements.list[lang][i]), 0); } } } }, /** * @name Hyphenator-removeHyphenationFromDocument * @description * Does what it says ;-) * @private */ removeHyphenationFromDocument = function () { elements.each(function (ellist) { var i, l = ellist.length; for (i = 0; i < l; i += 1) { removeHyphenationFromElement(ellist[i].element); if (safeCopy) { removeOnCopy(ellist[i].element); } ellist[i].hyphenated = false; } }); state = 4; }, /** * @name Hyphenator-createStorage * @description * inits the private var storage depending of the setting in storageType * and the supported features of the system. * @private */ createStorage = function () { var s; try { if (storageType !== 'none' && window.localStorage !== undefined && window.sessionStorage !== undefined && window.JSON.stringify !== undefined && window.JSON.parse !== undefined) { switch (storageType) { case 'session': s = window.sessionStorage; break; case 'local': s = window.localStorage; break; default: s = undefined; break; } } } catch (f) { //FF throws an error if DOM.storage.enabled is set to false } if (s) { storage = { prefix: 'Hyphenator_' + Hyphenator.version + '_', store: s, test: function (name) { var val = this.store.getItem(this.prefix + name); return (!!val) ? true : false; }, getItem: function (name) { return this.store.getItem(this.prefix + name); }, setItem: function (name, value) { this.store.setItem(this.prefix + name, value); } }; } else { storage = undefined; } }, /** * @name Hyphenator-storeConfiguration * @description * Stores the current config-options in DOM-Storage * @private */ storeConfiguration = function () { if (!storage) { return; } var settings = { 'STORED': true, 'classname': hyphenateClass, 'donthyphenateclassname': dontHyphenateClass, 'minwordlength': min, 'hyphenchar': hyphen, 'urlhyphenchar': urlhyphen, 'togglebox': toggleBox, 'displaytogglebox': displayToggleBox, 'remoteloading': enableRemoteLoading, 'enablecache': enableCache, 'onhyphenationdonecallback': onHyphenationDone, 'onerrorhandler': onError, 'intermediatestate': intermediateState, 'selectorfunction': selectorFunction || mySelectorFunction, 'safecopy': safeCopy, 'doframes': doFrames, 'storagetype': storageType, 'orphancontrol': orphanControl, 'dohyphenation': Hyphenator.doHyphenation, 'persistentconfig': persistentConfig, 'defaultlanguage': defaultLanguage, 'useCSS3hyphenation': css3, 'unhide': unhide, 'onbeforewordhyphenation': onBeforeWordHyphenation, 'onafterwordhyphenation': onAfterWordHyphenation }; storage.setItem('config', window.JSON.stringify(settings)); }, /** * @name Hyphenator-restoreConfiguration * @description * Retrieves config-options from DOM-Storage and does configuration accordingly * @private */ restoreConfiguration = function () { var settings; if (storage.test('config')) { settings = window.JSON.parse(storage.getItem('config')); Hyphenator.config(settings); } }; return { /** * @name Hyphenator.version * @memberOf Hyphenator * @description * String containing the actual version of Hyphenator.js * [major release].[minor releas].[bugfix release] * major release: new API, new Features, big changes * minor release: new languages, improvements * @public */ version: 'X.Y.Z', /** * @name Hyphenator.doHyphenation * @description * If doHyphenation is set to false (defaults to true), hyphenateDocument() isn't called. * All other actions are performed. */ doHyphenation: true, /** * @name Hyphenator.languages * @memberOf Hyphenator * @description * Objects that holds key-value pairs, where key is the language and the value is the * language-object loaded from (and set by) the pattern file. * The language object holds the following members: * <table> * <tr><th>key</th><th>desc></th></tr> * <tr><td>leftmin</td><td>The minimum of chars to remain on the old line</td></tr> * <tr><td>rightmin</td><td>The minimum of chars to go on the new line</td></tr> * <tr><td>shortestPattern</td><td>The shortes pattern (numbers don't count!)</td></tr> * <tr><td>longestPattern</td><td>The longest pattern (numbers don't count!)</td></tr> * <tr><td>specialChars</td><td>Non-ASCII chars in the alphabet.</td></tr> * <tr><td>patterns</td><td>the patterns</td></tr> * </table> * And optionally (or after prepareLanguagesObj() has been called): * <table> * <tr><td>exceptions</td><td>Excpetions for the secified language</td></tr> * </table> * @public */ languages: {}, /** * @name Hyphenator.config * @description * Config function that takes an object as an argument. The object contains key-value-pairs * containig Hyphenator-settings. This is a shortcut for calling Hyphenator.set...-Methods. * @param {Object} obj <table> * <tr><th>key</th><th>values</th><th>default</th></tr> * <tr><td>classname</td><td>string</td><td>'hyphenate'</td></tr> * <tr><td>donthyphenateclassname</td><td>string</td><td>''</td></tr> * <tr><td>minwordlength</td><td>integer</td><td>6</td></tr> * <tr><td>hyphenchar</td><td>string</td><td>'&amp;shy;'</td></tr> * <tr><td>urlhyphenchar</td><td>string</td><td>'zero with space'</td></tr> * <tr><td>togglebox</td><td>function</td><td>see code</td></tr> * <tr><td>displaytogglebox</td><td>boolean</td><td>false</td></tr> * <tr><td>remoteloading</td><td>boolean</td><td>true</td></tr> * <tr><td>enablecache</td><td>boolean</td><td>true</td></tr> * <tr><td>enablereducedpatternset</td><td>boolean</td><td>false</td></tr> * <tr><td>onhyphenationdonecallback</td><td>function</td><td>empty function</td></tr> * <tr><td>onerrorhandler</td><td>function</td><td>alert(onError)</td></tr> * <tr><td>intermediatestate</td><td>string</td><td>'hidden'</td></tr> * <tr><td>selectorfunction</td><td>function</td><td>[…]</td></tr> * <tr><td>safecopy</td><td>boolean</td><td>true</td></tr> * <tr><td>doframes</td><td>boolean</td><td>false</td></tr> * <tr><td>storagetype</td><td>string</td><td>'none'</td></tr> * </table> * @public * @example &lt;script src = "Hyphenator.js" type = "text/javascript"&gt;&lt;/script&gt;  * &lt;script type = "text/javascript"&gt;  * Hyphenator.config({'minwordlength':4,'hyphenchar':'|'}); * Hyphenator.run();  * &lt;/script&gt; */ config: function (obj) { var assert = function (name, type) { var r, t; t = typeof obj[name]; if (t === type) { r = true; } else { onError(new Error('Config onError: ' + name + ' must be of type ' + type)); r = false; } return r; }, key; if (obj.hasOwnProperty('storagetype')) { if (assert('storagetype', 'string')) { storageType = obj.storagetype; } if (!storage) { createStorage(); } } if (!obj.hasOwnProperty('STORED') && storage && obj.hasOwnProperty('persistentconfig') && obj.persistentconfig === true) { restoreConfiguration(); } for (key in obj) { if (obj.hasOwnProperty(key)) { switch (key) { case 'STORED': break; case 'classname': if (assert('classname', 'string')) { hyphenateClass = obj[key]; } break; case 'donthyphenateclassname': if (assert('donthyphenateclassname', 'string')) { dontHyphenateClass = obj[key]; } break; case 'minwordlength': if (assert('minwordlength', 'number')) { min = obj[key]; } break; case 'hyphenchar': if (assert('hyphenchar', 'string')) { if (obj.hyphenchar === '&shy;') { obj.hyphenchar = String.fromCharCode(173); } hyphen = obj[key]; } break; case 'urlhyphenchar': if (obj.hasOwnProperty('urlhyphenchar')) { if (assert('urlhyphenchar', 'string')) { urlhyphen = obj[key]; } } break; case 'togglebox': if (assert('togglebox', 'function')) { toggleBox = obj[key]; } break; case 'displaytogglebox': if (assert('displaytogglebox', 'boolean')) { displayToggleBox = obj[key]; } break; case 'remoteloading': if (assert('remoteloading', 'boolean')) { enableRemoteLoading = obj[key]; } break; case 'enablecache': if (assert('enablecache', 'boolean')) { enableCache = obj[key]; } break; case 'enablereducedpatternset': if (assert('enablereducedpatternset', 'boolean')) { enableReducedPatternSet = obj[key]; } break; case 'onhyphenationdonecallback': if (assert('onhyphenationdonecallback', 'function')) { onHyphenationDone = obj[key]; } break; case 'onerrorhandler': if (assert('onerrorhandler', 'function')) { onError = obj[key]; } break; case 'intermediatestate': if (assert('intermediatestate', 'string')) { intermediateState = obj[key]; } break; case 'selectorfunction': if (assert('selectorfunction', 'function')) { selectorFunction = obj[key]; } break; case 'safecopy': if (assert('safecopy', 'boolean')) { safeCopy = obj[key]; } break; case 'doframes': if (assert('doframes', 'boolean')) { doFrames = obj[key]; } break; case 'storagetype': if (assert('storagetype', 'string')) { storageType = obj[key]; } break; case 'orphancontrol': if (assert('orphancontrol', 'number')) { orphanControl = obj[key]; } break; case 'dohyphenation': if (assert('dohyphenation', 'boolean')) { Hyphenator.doHyphenation = obj[key]; } break; case 'persistentconfig': if (assert('persistentconfig', 'boolean')) { persistentConfig = obj[key]; } break; case 'defaultlanguage': if (assert('defaultlanguage', 'string')) { defaultLanguage = obj[key]; } break; case 'useCSS3hyphenation': if (assert('useCSS3hyphenation', 'boolean')) { css3 = obj[key]; } break; case 'unhide': if (assert('unhide', 'string')) { unhide = obj[key]; } break; case 'onbeforewordhyphenation': if (assert('onbeforewordhyphenation', 'function')) { onBeforeWordHyphenation = obj[key]; } break; case 'onafterwordhyphenation': if (assert('onafterwordhyphenation', 'function')) { onAfterWordHyphenation = obj[key]; } break; default: onError(new Error('Hyphenator.config: property ' + key + ' not known.')); } } } if (storage && persistentConfig) { storeConfiguration(); } }, /** * @name Hyphenator.run * @description * Bootstrap function that starts all hyphenation processes when called. * @public * @example &lt;script src = "Hyphenator.js" type = "text/javascript"&gt;&lt;/script&gt;  * &lt;script type = "text/javascript"&gt;  *   Hyphenator.run();  * &lt;/script&gt; */ run: function () { var process = function () { try { if (contextWindow.document.getElementsByTagName('frameset').length > 0) { return; //we are in a frameset } autoSetMainLanguage(undefined); gatherDocumentInfos(); prepare(hyphenateLanguageElements); if (displayToggleBox) { toggleBox(); } } catch (e) { onError(e); } }; if (!storage) { createStorage(); } runWhenLoaded(window, process); }, /** * @name Hyphenator.addExceptions * @description * Adds the exceptions from the string to the appropriate language in the * {@link Hyphenator-languages}-object * @param {string} lang The language * @param {string} words A comma separated string of hyphenated words WITH spaces. * @public * @example &lt;script src = "Hyphenator.js" type = "text/javascript"&gt;&lt;/script&gt;  * &lt;script type = "text/javascript"&gt;  *   Hyphenator.addExceptions('de','ziem-lich, Wach-stube'); * Hyphenator.run();  * &lt;/script&gt; */ addExceptions: function (lang, words) { if (lang === '') { lang = 'global'; } if (exceptions.hasOwnProperty(lang)) { exceptions[lang] += ", " + words; } else { exceptions[lang] = words; } }, /** * @name Hyphenator.hyphenate * @public * @description * Hyphenates the target. The language patterns must be loaded. * If the target is a string, the hyphenated string is returned, * if it's an object, the values are hyphenated directly. * @param {string|Object} target the target to be hyphenated * @param {string} lang the language of the target * @returns string * @example &lt;script src = "Hyphenator.js" type = "text/javascript"&gt;&lt;/script&gt; * &lt;script src = "patterns/en.js" type = "text/javascript"&gt;&lt;/script&gt;  * &lt;script type = "text/javascript"&gt; * var t = Hyphenator.hyphenate('Hyphenation', 'en'); //Hy|phen|ation * &lt;/script&gt; */ hyphenate: function (target, lang) { var hyphenate, n, i; if (Hyphenator.languages.hasOwnProperty(lang)) { if (!Hyphenator.languages[lang].prepared) { prepareLanguagesObj(lang); } hyphenate = function (word) { var r; if (urlOrMailRE.test(word)) { r = hyphenateURL(word); } else { r = hyphenateWord(lang, word); } return r; }; if (typeof target === 'object' && !(typeof target === 'string' || target.constructor === String)) { i = 0; n = target.childNodes[i]; while (!!n) { if (n.nodeType === 3 && n.data.length >= min) { //type 3 = #text -> hyphenate! n.data = n.data.replace(Hyphenator.languages[lang].genRegExp, hyphenate); } else if (n.nodeType === 1) { if (n.lang !== '') { Hyphenator.hyphenate(n, n.lang); } else { Hyphenator.hyphenate(n, lang); } } i += 1; n = target.childNodes[i]; } } else if (typeof target === 'string' || target.constructor === String) { return target.replace(Hyphenator.languages[lang].genRegExp, hyphenate); } } else { onError(new Error('Language "' + lang + '" is not loaded.')); } }, /** * @name Hyphenator.getRedPatternSet * @description * Returns {@link Hyphenator-isBookmarklet}. * @param {string} lang the language patterns are stored for * @returns object {'patk': pat} * @public */ getRedPatternSet: function (lang) { return Hyphenator.languages[lang].redPatSet; }, /** * @name Hyphenator.isBookmarklet * @description * Returns {@link Hyphenator-isBookmarklet}. * @returns boolean * @public */ isBookmarklet: function () { return isBookmarklet; }, getConfigFromURI: function () { /*jslint evil: true*/ var loc = null, re = {}, jsArray = contextWindow.document.getElementsByTagName('script'), i, j, l, s, gp, option; for (i = 0, l = jsArray.length; i < l; i += 1) { if (!!jsArray[i].getAttribute('src')) { loc = jsArray[i].getAttribute('src'); } if (loc && (loc.indexOf('Hyphenator.js?') !== -1)) { s = loc.indexOf('Hyphenator.js?'); gp = loc.substring(s + 14).split('&'); for (j = 0; j < gp.length; j += 1) { option = gp[j].split('='); if (option[0] !== 'bm') { if (option[1] === 'true') { option[1] = true; } else if (option[1] === 'false') { option[1] = false; } else if (isFinite(option[1])) { option[1] = parseInt(option[1], 10); } if (option[0] === 'onhyphenationdonecallback') { option[1] = new Function('', option[1]); } re[option[0]] = option[1]; } } break; } } return re; }, /** * @name Hyphenator.toggleHyphenation * @description * Checks the current state of the ToggleBox and removes or does hyphenation. * @public */ toggleHyphenation: function () { if (Hyphenator.doHyphenation) { if (!!css3hyphenateClassHandle) { css3hyphenateClassHandle.setRule('.' + css3hyphenateClass, css3_h9n.property + ': none;'); } removeHyphenationFromDocument(); Hyphenator.doHyphenation = false; storeConfiguration(); toggleBox(); } else { if (!!css3hyphenateClassHandle) { css3hyphenateClassHandle.setRule('.' + css3hyphenateClass, css3_h9n.property + ': auto;'); } hyphenateLanguageElements('*'); Hyphenator.doHyphenation = true; storeConfiguration(); toggleBox(); } } }; }(window)); //Export properties/methods (for google closure compiler) /* to be moved to external file Hyphenator['languages'] = Hyphenator.languages; Hyphenator['config'] = Hyphenator.config; Hyphenator['run'] = Hyphenator.run; Hyphenator['addExceptions'] = Hyphenator.addExceptions; Hyphenator['hyphenate'] = Hyphenator.hyphenate; Hyphenator['getRedPatternSet'] = Hyphenator.getRedPatternSet; Hyphenator['isBookmarklet'] = Hyphenator.isBookmarklet; Hyphenator['getConfigFromURI'] = Hyphenator.getConfigFromURI; Hyphenator['toggleHyphenation'] = Hyphenator.toggleHyphenation; window['Hyphenator'] = Hyphenator; */ if (Hyphenator.isBookmarklet()) { Hyphenator.config({displaytogglebox: true, intermediatestate: 'visible', doframes: true, useCSS3hyphenation: true}); Hyphenator.config(Hyphenator.getConfigFromURI()); Hyphenator.run(); }
025003b-rss
ttrss-reader/assets/Hyphenator.js
JavaScript
gpl3
116,973
Hyphenator.languages['it'] = { leftmin : 2, rightmin : 2, specialChars : "àéèìòù’'", // The italian hyphenation patterns are retrieved from // http://www.ctan.org/tex-archive/language/hyphenation/ithyph.tex patterns : { 2 : "1b1c1d1f1g1h1j1k1l1m1n1p1q1r1t1v1w1x1z", 3 : "2’2e2w2bb2bc2bd2bf2bm2bn2bp2bs2bt2bvb2lb2r2b_2b’2cb2cc2cd2cf2ck2cm2cn2cq2cs2ct2czc2hc2lc2r2c_2c’_c22db2dd2dg2dl2dm2dn2dpd2r2ds2dt2dv2dw2d_2d’_d22fb2fg2ff2fnf2lf2r2fs2ft2f_2f’2gb2gd2gf2ggg2hg2l2gmg2n2gpg2r2gs2gt2gv2gw2gz2g_2g’2hb2hd2hhh2l2hm2hn2hr2hv2h_2h’2j_2j’2kg2kfk2h2kkk2l2kmk2r2ks2kt2k_2k’2lb2lc2ld2lgl2h2lk2ll2lm2ln2lp2lq2lr2ls2lt2lv2lw2lz2l_2mb2mc2mf2ml2mm2mn2mp2mq2mr2ms2mt2mv2mw2m_2m’2nb2nc2nd2nf2ng2nk2nl2nm2nn2np2nq2nr2ns2nt2nv2nz2n_2n’2pdp2hp2l2pn2ppp2r2ps2pt2pz2p_2p’2qq2q_2q’2rb2rc2rd2rfr2h2rg2rk2rl2rm2rn2rp2rq2rr2rs2rt2rv2rx2rw2rz2r_2r’1s22sz4s_2tb2tc2td2tf2tgt2ht2l2tm2tn2tpt2rt2s2tt2tv2twt2z2t_2vcv2lv2r2vv2v_w2h2w_2w’2xb2xc2xf2xh2xm2xp2xt2xw2x_2x’y1i2zb2zd2zl2zn2zp2zt2zs2zv2zz2z_", 4 : "_p2sa1iaa1iea1ioa1iua1uoa1ya2at_e1iuo1iao1ieo1ioo1iu2chh2chbch2r2chn2l’_2l’’2shm2sh_2sh’2s3s2stb2stc2std2stf2stg2stm2stn2stp2sts2stt2stv4s’_4s’’2tzktz2s2t’_2t’’2v’_2v’’wa2r2w1yy1ou2z’_2z’’_z2", 5 : "_bio1_pre12gh2t2l3f2n2g3n3p2nes4s3mt2t3s", 6 : "_a3p2n_anti1_free3_opto1_para1hi3p2n2nheit3p2sicr2t2s32s3p2n3t2sch", 7 : "_ca4p3s_e2x1eu_narco1_su2b3r_wa2g3n_wel2t1n2s3fer", 8 : "_contro1_fran2k3_li3p2sa_orto3p2_poli3p2_sha2re3_su2b3lu", 9 : "_anti3m2n_circu2m1_re1i2scr_tran2s3c_tran2s3d_tran2s3l_tran2s3n_tran2s3p_tran2s3r_tran2s3t", 10 : "_di2s3cine" } };
025003b-rss
ttrss-reader/assets/patterns/it.js
JavaScript
gpl3
1,636
// For questions about the Oriya hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['or'] = { leftmin : 2, rightmin : 2, specialChars : unescape("ଆଅଇଈଉଊଋଏଐଔକଗଖଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଵଶଷସହଳିୀାୁୂୃୋୋୈୌୗ୍ଃଂ%u200D"), patterns : { 2 : "ଅ1ଆ1ଇ1ଈ1ଉ1ଊ1ଋ1ଏ1ଐ1ଔ1ି1ା1ୀ1ୁ1ୂ1ୃ1େ1ୋ1ୌ1ୗ1୍2ଃ1ଂ11କ1ଖ1ଘ1ଙ1ଚ1ଛ1ଜ1ଝ1ଞ1ଟ1ଠ1ଡ1ଢ1ଣ1ତ1ଥ1ଦ1ଧ1ନ1ପ1ଫ1ବ1ଭ1ମ1ଯ1ର1ଲ1ଵ1ଶ1ଷ1ସ1ହ1ଳ", 3 : "1ଗ1", 4 : unescape("2ନ୍%u200D2ର୍%u200D2ଲ୍%u200D2ଳ୍%u200D2ଣ୍%u200D") } };
025003b-rss
ttrss-reader/assets/patterns/or.js
JavaScript
gpl3
752
// For questions about the Kannada hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['kn'] = { leftmin : 2, rightmin : 2, specialChars : "ಆಅಇಈಉಊಋಎಏಐಒಔಕಗಖಘಙಚಛಜಝಞಟಠಡಢಣತಥದಧನಪಫಬಭಮಯರಲವಶಷಸಹಳಱಿೀಾುೂೃೆೇೊಾೋೈೌ್ಃಂ", patterns : { 2 : "ಅ1ಆ1ಇ1ಈ1ಉ1ಊ1ಋ1ಎ1ಏ1ಐ1ಒ1ಔ1ೀ1ು1ೂ1ೃ1ೆ1ೇ1ೊ1ೋ1ೌ1್2ಃ1ಂ11ಕ1ಗ1ಖ1ಘ1ಙ1ಚ1ಛ1ಜ1ಝ1ಞ1ಟ1ಠ1ಡ1ಢ1ಣ1ತ1ಥ1ದ1ಧ1ನ1ಪ1ಫ1ಬ1ಭ1ಮ1ಯ1ರ1ಲ1ವ1ಶ1ಷ1ಸ1ಹ1ಳ1ಱ", 3 : "2ಃ12ಂ1" } };
025003b-rss
ttrss-reader/assets/patterns/kn.js
JavaScript
gpl3
683
// For questions about the Panjabi hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['pa'] = { leftmin : 2, rightmin : 2, specialChars : unescape("ਆਅਇਈਉਊਏਐਔਕਗਖਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਵਸ਼ਸਹਲ਼ਿੀਾੁੂੇਾੋੈੌ੍ਃ%u0A02%u200D"), patterns : { 2 : unescape("ਅ1ਆ1ਇ1ਈ1ਉ1ਊ1ਏ1ਐ1ਔ1ਿ1ਾ1ੀ1ੁ1ੂ1ੇ1ੋ1ੌ1੍2ਃ1%u0A0211ਕ1ਗ1ਖ1ਘ1ਙ1ਚ1ਛ1ਜ1ਝ1ਞ1ਟ1ਠ1ਡ1ਢ1ਣ1ਤ1ਥ1ਦ1ਧ1ਨ1ਪ1ਫ1ਬ1ਭ1ਮ1ਯ1ਰ1ਲ1ਵ1ਸ਼1ਸ1ਹ1ਲ਼") } };
025003b-rss
ttrss-reader/assets/patterns/pa.js
JavaScript
gpl3
648
// For questions about the Malayalam hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['ml'] = { leftmin : 2, rightmin : 2, specialChars : unescape("അആഇഈഉഊഋൠഌൡഎഏഐഒഓഔാിീുൂൃെേൈൊോൌൗകഖഗഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമയരറലളഴവശഷസഹഃം്ൺൻർൽൾൿ%u200D"), patterns : { 2 : "ാ1ി1ീ1ു1ൂ1ൃ1െ1േ1ൈ1ൊ1ോ1ൌ1ൗ11ക1ഖ1ഗ1ഘ1ങ1ച1ഛ1ജ1ഝ1ഞ1ട1ഠ1ഡ1ഢ1ണ1ത1ഥ1ദ1ധ1ന1പ1ഫ1ബ1ഭ1മ1യ1ര1റ1ല1ള1ഴ1വ1ശ1ഷ1സ1ഹ2ൺ2ൻ2ർ2ൽ2ൾ2ൿ", 3 : "1അ11ആ11ഇ11ഈ11ഉ11ഊ11ഋ11ൠ11ഌ11ൡ11എ11ഏ11ഐ11ഒ11ഓ11ഔ12ഃ12ം12്2ന്2ര്2ള്2ല്2ക്2ണ്2", 4 : unescape("2ന്%u200D2ര്%u200D2ല്%u200D2ള്%u200D2ണ്%u200D2ക്%u200D") } };
025003b-rss
ttrss-reader/assets/patterns/ml.js
JavaScript
gpl3
949
// For questions about the Telugu hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['te'] = { leftmin : 2, rightmin : 2, specialChars : "ఆఅఇఈఉఊఋఎఏఐఒఔకగఖఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరలవశషసహళఱిీాుూృెేొాోైౌ్ఃం", patterns : { 2 : "అ1ఆ1ఇ1ఈ1ఉ1ఊ1ఋ1ఎ1ఏ1ఐ1ఒ1ఔ1ి1ా1ీ1ు1ూ1ృ1ె1ే1ొ1ో1ౌ1్2ః1ం11క1గ1ఖ1ఘ1ఙ1చ1ఛ1జ1ఝ1ఞ1ట1ఠ1డ1ఢ1ణ1త1థ1ద1ధ1న1ప1ఫ1బ1భ1మ1య1ర1ల1వ1శ1ష1స1హ1ళ1ఱ" } };
025003b-rss
ttrss-reader/assets/patterns/te.js
JavaScript
gpl3
670
// For questions about the Bengali hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['bn'] = { leftmin : 2, rightmin : 2, specialChars : unescape("আঅইঈউঊঋএঐঔকগখঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহিীাুূৃোোৈৌৗ্ঃং%u200D"), patterns : { 2 : "অ1আ1ই1ঈ1উ1ঊ1ঋ1এ1ঐ1ঔ1ি1া1ী1ু1ৃ1ে1ো1ৌ1ৗ1্2ঃ1ং11ক1গ1খ1ঘ1ঙ1চ1ছ1জ1ঝ1ঞ1ট1ঠ1ড1ঢ1ণ1ত1থ1দ1ধ1ন1প1ফ1ব1ভ1ম1য1র1ল1শ1ষ1স1হ", 3 : "2ঃ12ং1" } };
025003b-rss
ttrss-reader/assets/patterns/bn.js
JavaScript
gpl3
661
Hyphenator.languages['fi'] = { leftmin : 2, rightmin : 2, specialChars : "öäå", patterns : { 3 : "1ba1be1bi1bo1bu1by1da1de1di1do1du1dy1dä1dö1fa1fe1fi1fo1fu1fy1ga1ge1gi1go1gu1gy1gä1gö1ha1he1hi1ho1hu1hy1hä1hö1ja1je1ji1jo1ju1jy1jä1jö1ka1ke1ki1ko1ku1ky1kä1kö1la1le1li1lo1lu1ly1lä1lö1ma1me1mi1mo1mu1my1mä1mö1na1ne1ni1no1nu1ny1nä1nö1pa1pe1pi1po1pu1py1pä1pö1ra1re1ri1ro1ru1ry1rä1rö1sa1se1si1so1su1sy1sä1sö1ta1te1ti1to1tu1ty1tä1tö1va1ve1vi1vo1vu1vy1vä1vöä2yo1yö2ya1äa1öo1äo1öä2äö2öä2öö2ä_ä2u2sb2lb2rd2rf2lf2rg2lg2rk2lp2lp2rc2lq2v", 4 : "y1a2y1o2u1y2y1u2ö3a2ö3o2ä3a2ä3o2ä1u2ö1u2u1ä2u1ö2e1aai1aao1aau1aau1eea1uui1uue1uuo1uuää1iää1eää3yi1ääe1ääy1ääi1ööa1eia1oie1aii1auy1eiai1aai1eai1oai1uau1aau1eeu1aie1aie1oie1yiu1aiu1eiu1ooi1aoi1eoi1ooi1uo1uiou1eou1oue1aui1euo1auo1ue1ö2ö1e2r2asl2as1k2vsc2hts2h", 5 : "1st2raa1i2aa1e2aa1o2aa1u2ee1a2ee1i2ee1u2ee1y2ii1a2ii1e2ii1o2uu1a2uu1e2uu1o2uu1i2io1a2io1e2keus11b2lo1b2ri1b2ro1b2ru1d2ra1f2la1f2ra1f2re1g2lo1g2ra1k2ra1k2re1k2ri1k2va1p2ro1q2vich2r", 6 : "1sp2lialous1rtaus1perus12s1ase2s1apuulo2s1bib3li", 7 : "yli1o2pali1a2v2s1ohje1a2sian1a2siat1a2sioi2s1o2sa2n1o2sa_ydi2n12n1otto2n1oton2n1anto2n1anno2n1aika2n1a2jo2s1a2jo", 8 : "2s1a2sia2n1o2pet2s1a2loialkei2s12n1e2dus2s1ajatu2s1y2rit2s1y2hti2n1a2jan2n1o2mai2n1y2lit2s1a2len2n1a2len", 9 : "2s1o2pisk2n1o2pist2s1o2pist2s1i2dea_2s1i2dean2s1e2sity_suu2r1a2", 11 : "1a2siaka2s1" } };
025003b-rss
ttrss-reader/assets/patterns/fi.js
JavaScript
gpl3
1,449
// For questions about the Hindi hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['hi'] = { leftmin : 2, rightmin : 2, specialChars : unescape("आअइईउऊऋऎएऐऒऔकगखघङचछजझञटठडढणतथदधनपफबभमयरलवशषसहळऴऱिीाुूृॆेॊाोैौ्ःं%u200D"), patterns : { 2 : "अ1आ1इ1ई1उ1ऊ1ऋ1ऎ1ए1ऐ1ऒ1औ1ि1ा1ी1ु1ू1ृ1ॆ1े1ॊ1ो1ौ1्2ः1ं11क1ग1ख1घ1ङ1च1छ1ज1झ1ञ1ट1ठ1ड1ढ1ण1त1थ1द1ध1न1प1फ1ब1भ1म1य1र1ल1व1श1ष1स1ह1ळ1ऴ1ऱ" } };
025003b-rss
ttrss-reader/assets/patterns/hi.js
JavaScript
gpl3
692
// Latin hyphenation patterns converted by // Pablo Rodríguez (hyphenator at pragmata dot tk) // based on LaTeX Latin hyphenation patterns by Claudio Beccari // (http://tug.ctan.org/tex-archive/language/hyphenation/lahyph.tex) Hyphenator.languages['la'] = { leftmin : 2, rightmin : 2, specialChars : "æœ", patterns : { 2 : "æ1œ11b1c1d1f1g1h1j1k1l1m1n1p1r1t1v1x1z", 3 : "2bb2bdb2l2bm2bnb2r2bt2bs2b_2ccc2l2cm2cn2cqc2r2cs2ct2cz2c_2dd2dg2dmd2r2ds2dv2d_2fff2l2fnf2r2ft2f_2gg2gd2gfg2l2gmg2ng2r2gs2gv2g_2hp2ht2h_2kk2lb2lc2ld2lf2lg2lk2ll2lm2ln2lp2lq2lr2ls2lt2lv2l_2mm2mb2mp2ml2mn2mq2mr2mv2m_2nb2nc2nd2nf2ng2nl2nm2nn2np2nq2nr2ns2nt2nv2nx2n_p2hp2l2pn2ppp2r2ps2pt2pz2p_2rb2rc2rd2rf2rgr2h2rl2rm2rn2rp2rq2rr2rs2rt2rv2rz2r_1s22s_2tb2tc2td2tf2tgt2ht2lt2r2tm2tn2tp2tq2tt2tv2t_v2lv2r2vv2xt2xx2x_2z_", 4 : "a1iaa1iea1ioa1iuae1aae1oae1ue1iuio1io1iao1ieo1ioo1iuuo3uc2h2k2h22php2pht1qu22s3s2stb2stc2std2stf2stg2stm2stn2stp2stq2sts2stt2stv2st_a1uaa1uea1uia1uoa1uue1uae1uee1uie1uoe1uui1uai1uei1uii1uoi1uuo1uao1ueo1uio1uoo1uuu1uau1ueu1uiu1uou1uu", 5 : "_e2x1_o2b3l3f2tn2s3mn2s3f2s3ph2st3l", 6 : "_a2b3l_anti13p2sic3p2neua2l1uaa2l1uea2l1uia2l1uoa2l1uue2l1uae2l1uee2l1uie2l1uoe2l1uui2l1uai2l1uei2l1uii2l1uoi2l1uuo2l1uao2l1ueo2l1uio2l1uoo2l1uuu2l1uau2l1ueu2l1uiu2l1uou2l1uua2m1uaa2m1uea2m1uia2m1uoa2m1uue2m1uae2m1uee2m1uie2m1uoe2m1uui2m1uai2m1uei2m1uii2m1uoi2m1uuo2m1uao2m1ueo2m1uio2m1uoo2m1uuu2m1uau2m1ueu2m1uiu2m1uou2m1uua2n1uaa2n1uea2n1uia2n1uoa2n1uue2n1uae2n1uee2n1uie2n1uoe2n1uui2n1uai2n1uei2n1uii2n1uoi2n1uuo2n1uao2n1ueo2n1uio2n1uoo2n1uuu2n1uau2n1ueu2n1uiu2n1uou2n1uua2r1uaa2r1uea2r1uia2r1uoa2r1uue2r1uae2r1uee2r1uie2r1uoe2r1uui2r1uai2r1uei2r1uii2r1uoi2r1uuo2r1uao2r1ueo2r1uio2r1uoo2r1uuu2r1uau2r1ueu2r1uiu2r1uou2r1uu", 7 : "_para1i_para1u_su2b3r2s3que_2s3dem_", 8 : "_su2b3lu", 9 : "_anti3m2n_circu2m1_co2n1iun", 10 : "_di2s3cine" } };
025003b-rss
ttrss-reader/assets/patterns/la.js
JavaScript
gpl3
1,847
// For questions about the Gujarati hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['gu'] = { leftmin : 2, rightmin : 2, specialChars : unescape("આઅઇઈઉઊઋએઐઔકગખઘઙચછજઝઞટઠડઢણતથદધનપફબભમયરલવશષસહળિીાુૂૃેાોૈૌ્ઃં%u200D"), patterns : { 2 : "અ1આ1ઇ1ઈ1ઉ1ઊ1ઋ1એ1ઐ1ઔ1િ1ા1ી1ુ1ૂ1ૃ1ે1ો1ૌ1્2ઃ1ં11ક1ગ1ખ1ઘ1ઙ1ચ1છ1જ1ઝ1ઞ1ટ1ઠ1ડ1ઢ1ણ1ત1થ1દ1ધ1ન1પ1ફ1બ1ભ1મ1ય1ર1લ1વ1શ1ષ1સ1હ1ળ" } };
025003b-rss
ttrss-reader/assets/patterns/gu.js
JavaScript
gpl3
653
// For questions about the Tamil hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages['ta'] = { leftmin : 2, rightmin : 2, specialChars : "அஆஇஈஉஊஎஏஐஒஓஔாிீுூெேைொோௌகஙசஜஞடணதநபமயரறலளழவஷஸஹ்னஂஃௗ", patterns : { 2 : "ா1ி1ீ1ு1ூ1ெ1ே1ை1ொ1ோ1ௌ11க1ங1ச1ஜ1ஞ1ட1ண1த1ந1ப1ம1ய1ர1ற1ல1ள1ழ1வ1ஷ1ஸ1ஹ", 3 : "1அ11ஆ11இ11ஈ11உ11ஊ11எ11ஏ11ஐ11ஒ11ஓ11ஔ12ஂ12ஃ12ௗ12்1", 4 : "2க்12ங்12ச்12ஞ்12ட்12ண்12த்12ன்12ந்12ப்12ம்12ய்12ர்12ற்12ல்12ள்12ழ்12வ்12ஷ்12ஸ்12ஹ்1" } };
025003b-rss
ttrss-reader/assets/patterns/ta.js
JavaScript
gpl3
779
#import "DAVConnection.h" #import "HTTPMessage.h" #import "HTTPFileResponse.h" #import "HTTPAsyncFileResponse.h" #import "PUTResponse.h" #import "DELETEResponse.h" #import "DAVResponse.h" #import "HTTPLogging.h" #define HTTP_BODY_MAX_MEMORY_SIZE (1024 * 1024) #define HTTP_ASYNC_FILE_RESPONSE_THRESHOLD (16 * 1024 * 1024) static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; @implementation DAVConnection - (void) dealloc { [requestContentStream close]; [requestContentStream release]; [requestContentBody release]; [super dealloc]; } - (BOOL) supportsMethod:(NSString*)method atPath:(NSString*)path { // HTTPFileResponse & HTTPAsyncFileResponse if ([method isEqualToString:@"GET"]) return YES; if ([method isEqualToString:@"HEAD"]) return YES; // PUTResponse if ([method isEqualToString:@"PUT"]) return YES; // DELETEResponse if ([method isEqualToString:@"DELETE"]) return YES; // DAVResponse if ([method isEqualToString:@"OPTIONS"]) return YES; if ([method isEqualToString:@"PROPFIND"]) return YES; if ([method isEqualToString:@"MKCOL"]) return YES; if ([method isEqualToString:@"MOVE"]) return YES; if ([method isEqualToString:@"COPY"]) return YES; if ([method isEqualToString:@"LOCK"]) return YES; if ([method isEqualToString:@"UNLOCK"]) return YES; return NO; } - (BOOL) expectsRequestBodyFromMethod:(NSString*)method atPath:(NSString*)path { // PUTResponse if ([method isEqualToString:@"PUT"]) { return YES; } // DAVResponse if ([method isEqual:@"PROPFIND"] || [method isEqual:@"MKCOL"]) { return [request headerField:@"Content-Length"] ? YES : NO; } if ([method isEqual:@"LOCK"]) { return YES; } return NO; } - (void) prepareForBodyWithSize:(UInt64)contentLength { NSAssert(requestContentStream == nil, @"requestContentStream should be nil"); NSAssert(requestContentBody == nil, @"requestContentBody should be nil"); if (contentLength > HTTP_BODY_MAX_MEMORY_SIZE) { requestContentBody = [[NSTemporaryDirectory() stringByAppendingString:[[NSProcessInfo processInfo] globallyUniqueString]] copy]; requestContentStream = [[NSOutputStream alloc] initToFileAtPath:requestContentBody append:NO]; [requestContentStream open]; } else { requestContentBody = [[NSMutableData alloc] initWithCapacity:(NSUInteger)contentLength]; requestContentStream = nil; } } - (void) processBodyData:(NSData*)postDataChunk { NSAssert(requestContentBody != nil, @"requestContentBody should not be nil"); if (requestContentStream) { [requestContentStream write:[postDataChunk bytes] maxLength:[postDataChunk length]]; } else { [(NSMutableData*)requestContentBody appendData:postDataChunk]; } } - (void) finishBody { NSAssert(requestContentBody != nil, @"requestContentBody should not be nil"); if (requestContentStream) { [requestContentStream close]; [requestContentStream release]; requestContentStream = nil; } } - (void)finishResponse { NSAssert(requestContentStream == nil, @"requestContentStream should be nil"); [requestContentBody release]; requestContentBody = nil; [super finishResponse]; } - (NSObject<HTTPResponse>*) httpResponseForMethod:(NSString*)method URI:(NSString*)path { if ([method isEqualToString:@"HEAD"] || [method isEqualToString:@"GET"]) { NSString* filePath = [self filePathForURI:path allowDirectory:NO]; if (filePath) { NSDictionary* fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL]; if (fileAttributes) { if ([[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue] > HTTP_ASYNC_FILE_RESPONSE_THRESHOLD) { return [[[HTTPAsyncFileResponse alloc] initWithFilePath:filePath forConnection:self] autorelease]; } else { return [[[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self] autorelease]; } } } } if ([method isEqualToString:@"PUT"]) { NSString* filePath = [self filePathForURI:path allowDirectory:YES]; if (filePath) { if ([requestContentBody isKindOfClass:[NSString class]]) { return [[[PUTResponse alloc] initWithFilePath:filePath headers:[request allHeaderFields] bodyFile:requestContentBody] autorelease]; } else if ([requestContentBody isKindOfClass:[NSData class]]) { return [[[PUTResponse alloc] initWithFilePath:filePath headers:[request allHeaderFields] bodyData:requestContentBody] autorelease]; } else { HTTPLogError(@"Internal error"); } } } if ([method isEqualToString:@"DELETE"]) { NSString* filePath = [self filePathForURI:path allowDirectory:YES]; if (filePath) { return [[[DELETEResponse alloc] initWithFilePath:filePath] autorelease]; } } if ([method isEqualToString:@"OPTIONS"] || [method isEqualToString:@"PROPFIND"] || [method isEqualToString:@"MKCOL"] || [method isEqualToString:@"MOVE"] || [method isEqualToString:@"COPY"] || [method isEqualToString:@"LOCK"] || [method isEqualToString:@"UNLOCK"]) { NSString* filePath = [self filePathForURI:path allowDirectory:YES]; if (filePath) { NSString* rootPath = [config documentRoot]; NSString* resourcePath = [filePath substringFromIndex:([rootPath length] + 1)]; if (requestContentBody) { if ([requestContentBody isKindOfClass:[NSString class]]) { requestContentBody = [NSData dataWithContentsOfFile:requestContentBody]; } else if (![requestContentBody isKindOfClass:[NSData class]]) { HTTPLogError(@"Internal error"); return nil; } } return [[[DAVResponse alloc] initWithMethod:method headers:[request allHeaderFields] bodyData:requestContentBody resourcePath:resourcePath rootPath:rootPath] autorelease]; } } return nil; } @end
007xsq-sadsad
Extensions/WebDAV/DAVConnection.m
Objective-C
bsd
5,995
#import <libxml/parser.h> #import "DAVResponse.h" #import "HTTPLogging.h" // WebDAV specifications: http://webdav.org/specs/rfc4918.html typedef enum { kDAVProperty_ResourceType = (1 << 0), kDAVProperty_CreationDate = (1 << 1), kDAVProperty_LastModified = (1 << 2), kDAVProperty_ContentLength = (1 << 3), kDAVAllProperties = kDAVProperty_ResourceType | kDAVProperty_CreationDate | kDAVProperty_LastModified | kDAVProperty_ContentLength } DAVProperties; #define kXMLParseOptions (XML_PARSE_NONET | XML_PARSE_RECOVER | XML_PARSE_NOBLANKS | XML_PARSE_COMPACT | XML_PARSE_NOWARNING | XML_PARSE_NOERROR) static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; @implementation DAVResponse static void _AddPropertyResponse(NSString* itemPath, NSString* resourcePath, DAVProperties properties, NSMutableString* xmlString) { CFStringRef escapedPath = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)resourcePath, NULL, CFSTR("<&>?+"), kCFStringEncodingUTF8); if (escapedPath) { NSDictionary* attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:itemPath error:NULL]; BOOL isDirectory = [[attributes fileType] isEqualToString:NSFileTypeDirectory]; [xmlString appendString:@"<D:response>"]; [xmlString appendFormat:@"<D:href>%@</D:href>", escapedPath]; [xmlString appendString:@"<D:propstat>"]; [xmlString appendString:@"<D:prop>"]; if (properties & kDAVProperty_ResourceType) { if (isDirectory) { [xmlString appendString:@"<D:resourcetype><D:collection/></D:resourcetype>"]; } else { [xmlString appendString:@"<D:resourcetype/>"]; } } if ((properties & kDAVProperty_CreationDate) && [attributes objectForKey:NSFileCreationDate]) { NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; formatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]; formatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"]; formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'+00:00'"; [xmlString appendFormat:@"<D:creationdate>%@</D:creationdate>", [formatter stringFromDate:[attributes fileCreationDate]]]; [formatter release]; } if ((properties & kDAVProperty_LastModified) && [attributes objectForKey:NSFileModificationDate]) { NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; formatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]; formatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"]; formatter.dateFormat = @"EEE', 'd' 'MMM' 'yyyy' 'HH:mm:ss' GMT'"; [xmlString appendFormat:@"<D:getlastmodified>%@</D:getlastmodified>", [formatter stringFromDate:[attributes fileModificationDate]]]; [formatter release]; } if ((properties & kDAVProperty_ContentLength) && !isDirectory && [attributes objectForKey:NSFileSize]) { [xmlString appendFormat:@"<D:getcontentlength>%qu</D:getcontentlength>", [attributes fileSize]]; } [xmlString appendString:@"</D:prop>"]; [xmlString appendString:@"<D:status>HTTP/1.1 200 OK</D:status>"]; [xmlString appendString:@"</D:propstat>"]; [xmlString appendString:@"</D:response>\n"]; CFRelease(escapedPath); } } static xmlNodePtr _XMLChildWithName(xmlNodePtr child, const xmlChar* name) { while (child) { if ((child->type == XML_ELEMENT_NODE) && !xmlStrcmp(child->name, name)) { return child; } child = child->next; } return NULL; } - (id) initWithMethod:(NSString*)method headers:(NSDictionary*)headers bodyData:(NSData*)body resourcePath:(NSString*)resourcePath rootPath:(NSString*)rootPath { if ((self = [super init])) { _status = 200; _headers = [[NSMutableDictionary alloc] init]; // 10.1 DAV Header if ([method isEqualToString:@"OPTIONS"]) { if ([[headers objectForKey:@"User-Agent"] hasPrefix:@"WebDAVFS/"]) { // Mac OS X WebDAV support [_headers setObject:@"1, 2" forKey:@"DAV"]; } else { [_headers setObject:@"1" forKey:@"DAV"]; } } // 9.1 PROPFIND Method if ([method isEqualToString:@"PROPFIND"]) { NSInteger depth; NSString* depthHeader = [headers objectForKey:@"Depth"]; if ([depthHeader isEqualToString:@"0"]) { depth = 0; } else if ([depthHeader isEqualToString:@"1"]) { depth = 1; } else { HTTPLogError(@"Unsupported DAV depth \"%@\"", depthHeader); [self release]; return nil; } DAVProperties properties = 0; xmlDocPtr document = xmlReadMemory(body.bytes, (int)body.length, NULL, NULL, kXMLParseOptions); if (document) { xmlNodePtr node = _XMLChildWithName(document->children, (const xmlChar*)"propfind"); if (node) { node = _XMLChildWithName(node->children, (const xmlChar*)"prop"); } if (node) { node = node->children; while (node) { if (!xmlStrcmp(node->name, (const xmlChar*)"resourcetype")) { properties |= kDAVProperty_ResourceType; } else if (!xmlStrcmp(node->name, (const xmlChar*)"creationdate")) { properties |= kDAVProperty_CreationDate; } else if (!xmlStrcmp(node->name, (const xmlChar*)"getlastmodified")) { properties |= kDAVProperty_LastModified; } else if (!xmlStrcmp(node->name, (const xmlChar*)"getcontentlength")) { properties |= kDAVProperty_ContentLength; } else { HTTPLogWarn(@"Unknown DAV property requested \"%s\"", node->name); } node = node->next; } } else { HTTPLogWarn(@"HTTP Server: Invalid DAV properties\n%@", [[[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] autorelease]); } xmlFreeDoc(document); } if (!properties) { properties = kDAVAllProperties; } NSString* basePath = [rootPath stringByAppendingPathComponent:resourcePath]; if (![basePath hasPrefix:rootPath] || ![[NSFileManager defaultManager] fileExistsAtPath:basePath]) { [self release]; return nil; } NSMutableString* xmlString = [NSMutableString stringWithString:@"<?xml version=\"1.0\" encoding=\"utf-8\" ?>"]; [xmlString appendString:@"<D:multistatus xmlns:D=\"DAV:\">\n"]; if (![resourcePath hasPrefix:@"/"]) { resourcePath = [@"/" stringByAppendingString:resourcePath]; } _AddPropertyResponse(basePath, resourcePath, properties, xmlString); if (depth == 1) { if (![resourcePath hasSuffix:@"/"]) { resourcePath = [resourcePath stringByAppendingString:@"/"]; } NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:basePath]; NSString* path; while ((path = [enumerator nextObject])) { _AddPropertyResponse([basePath stringByAppendingPathComponent:path], [resourcePath stringByAppendingString:path], properties, xmlString); [enumerator skipDescendents]; } } [xmlString appendString:@"</D:multistatus>"]; [_headers setObject:@"application/xml; charset=\"utf-8\"" forKey:@"Content-Type"]; _data = [[xmlString dataUsingEncoding:NSUTF8StringEncoding] retain]; _status = 207; } // 9.3 MKCOL Method if ([method isEqualToString:@"MKCOL"]) { NSString* path = [rootPath stringByAppendingPathComponent:resourcePath]; if (![path hasPrefix:rootPath]) { [self release]; return nil; } if (![[NSFileManager defaultManager] fileExistsAtPath:[path stringByDeletingLastPathComponent]]) { HTTPLogError(@"Missing intermediate collection(s) at \"%@\"", path); _status = 409; } else if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:NULL]) { HTTPLogError(@"Failed creating collection at \"%@\"", path); _status = 405; } } // 9.8 COPY Method // 9.9 MOVE Method if ([method isEqualToString:@"MOVE"] || [method isEqualToString:@"COPY"]) { if ([method isEqualToString:@"COPY"] && ![[headers objectForKey:@"Depth"] isEqualToString:@"infinity"]) { HTTPLogError(@"Unsupported DAV depth \"%@\"", [headers objectForKey:@"Depth"]); [self release]; return nil; } NSString* sourcePath = [rootPath stringByAppendingPathComponent:resourcePath]; if (![sourcePath hasPrefix:rootPath] || ![[NSFileManager defaultManager] fileExistsAtPath:sourcePath]) { [self release]; return nil; } NSString* destination = [headers objectForKey:@"Destination"]; NSRange range = [destination rangeOfString:[headers objectForKey:@"Host"]]; if (range.location == NSNotFound) { [self release]; return nil; } NSString* destinationPath = [rootPath stringByAppendingPathComponent: [[destination substringFromIndex:(range.location + range.length)] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; if (![destinationPath hasPrefix:rootPath] || [[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) { [self release]; return nil; } BOOL isDirectory; if (![[NSFileManager defaultManager] fileExistsAtPath:[destinationPath stringByDeletingLastPathComponent] isDirectory:&isDirectory] || !isDirectory) { HTTPLogError(@"Invalid destination path \"%@\"", destinationPath); _status = 409; } else { BOOL existing = [[NSFileManager defaultManager] fileExistsAtPath:destinationPath]; if (existing && [[headers objectForKey:@"Overwrite"] isEqualToString:@"F"]) { HTTPLogError(@"Pre-existing destination path \"%@\"", destinationPath); _status = 412; } else { if ([method isEqualToString:@"COPY"]) { if ([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:NULL]) { _status = existing ? 204 : 201; } else { HTTPLogError(@"Failed copying \"%@\" to \"%@\"", sourcePath, destinationPath); _status = 403; } } else { if ([[NSFileManager defaultManager] moveItemAtPath:sourcePath toPath:destinationPath error:NULL]) { _status = existing ? 204 : 201; } else { HTTPLogError(@"Failed moving \"%@\" to \"%@\"", sourcePath, destinationPath); _status = 403; } } } } } // 9.10 LOCK Method - TODO: Actually lock the resource if ([method isEqualToString:@"LOCK"]) { NSString* path = [rootPath stringByAppendingPathComponent:resourcePath]; if (![path hasPrefix:rootPath]) { [self release]; return nil; } NSString* depth = [headers objectForKey:@"Depth"]; NSString* scope = nil; NSString* type = nil; NSString* owner = nil; xmlDocPtr document = xmlReadMemory(body.bytes, (int)body.length, NULL, NULL, kXMLParseOptions); if (document) { xmlNodePtr node = _XMLChildWithName(document->children, (const xmlChar*)"lockinfo"); if (node) { xmlNodePtr scopeNode = _XMLChildWithName(node->children, (const xmlChar*)"lockscope"); if (scopeNode && scopeNode->children && scopeNode->children->name) { scope = [NSString stringWithUTF8String:(const char*)scopeNode->children->name]; } xmlNodePtr typeNode = _XMLChildWithName(node->children, (const xmlChar*)"locktype"); if (typeNode && typeNode->children && typeNode->children->name) { type = [NSString stringWithUTF8String:(const char*)typeNode->children->name]; } xmlNodePtr ownerNode = _XMLChildWithName(node->children, (const xmlChar*)"owner"); if (ownerNode) { ownerNode = _XMLChildWithName(ownerNode->children, (const xmlChar*)"href"); if (ownerNode && ownerNode->children && ownerNode->children->content) { owner = [NSString stringWithUTF8String:(const char*)ownerNode->children->content]; } } } else { HTTPLogWarn(@"HTTP Server: Invalid DAV properties\n%@", [[[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] autorelease]); } xmlFreeDoc(document); } if ([scope isEqualToString:@"exclusive"] && [type isEqualToString:@"write"] && [depth isEqualToString:@"0"] && ([[NSFileManager defaultManager] fileExistsAtPath:path] || [[NSData data] writeToFile:path atomically:YES])) { NSString* timeout = [headers objectForKey:@"Timeout"]; CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault); NSString* token = [NSString stringWithFormat:@"urn:uuid:%@", [(id)CFUUIDCreateString(kCFAllocatorDefault, uuid) autorelease]]; CFRelease(uuid); NSMutableString* xmlString = [NSMutableString stringWithString:@"<?xml version=\"1.0\" encoding=\"utf-8\" ?>"]; [xmlString appendString:@"<D:prop xmlns:D=\"DAV:\">\n"]; [xmlString appendString:@"<D:lockdiscovery>\n<D:activelock>\n"]; [xmlString appendFormat:@"<D:locktype><D:%@/></D:locktype>\n", type]; [xmlString appendFormat:@"<D:lockscope><D:%@/></D:lockscope>\n", scope]; [xmlString appendFormat:@"<D:depth>%@</D:depth>\n", depth]; if (owner) { [xmlString appendFormat:@"<D:owner><D:href>%@</D:href></D:owner>\n", owner]; } if (timeout) { [xmlString appendFormat:@"<D:timeout>%@</D:timeout>\n", timeout]; } [xmlString appendFormat:@"<D:locktoken><D:href>%@</D:href></D:locktoken>\n", token]; // [xmlString appendFormat:@"<D:lockroot><D:href>%@</D:href></D:lockroot>\n", root]; [xmlString appendString:@"</D:activelock>\n</D:lockdiscovery>\n"]; [xmlString appendString:@"</D:prop>"]; [_headers setObject:@"application/xml; charset=\"utf-8\"" forKey:@"Content-Type"]; _data = [[xmlString dataUsingEncoding:NSUTF8StringEncoding] retain]; _status = 200; HTTPLogVerbose(@"Pretending to lock \"%@\"", resourcePath); } else { HTTPLogError(@"Locking request \"%@/%@/%@\" for \"%@\" is not allowed", scope, type, depth, resourcePath); _status = 403; } } // 9.11 UNLOCK Method - TODO: Actually unlock the resource if ([method isEqualToString:@"UNLOCK"]) { NSString* path = [rootPath stringByAppendingPathComponent:resourcePath]; if (![path hasPrefix:rootPath] || ![[NSFileManager defaultManager] fileExistsAtPath:path]) { [self release]; return nil; } NSString* token = [headers objectForKey:@"Lock-Token"]; _status = token ? 204 : 400; HTTPLogVerbose(@"Pretending to unlock \"%@\"", resourcePath); } } return self; } - (void) dealloc { [_headers release]; [_data release]; [super dealloc]; } - (UInt64) contentLength { return _data ? _data.length : 0; } - (UInt64) offset { return _offset; } - (void) setOffset:(UInt64)offset { _offset = offset; } - (NSData*) readDataOfLength:(NSUInteger)lengthParameter { if (_data) { NSUInteger remaining = _data.length - (NSUInteger)_offset; NSUInteger length = lengthParameter < remaining ? lengthParameter : remaining; void* bytes = (void*)(_data.bytes + _offset); _offset += length; return [NSData dataWithBytesNoCopy:bytes length:length freeWhenDone:NO]; } return nil; } - (BOOL) isDone { return _data ? _offset == _data.length : YES; } - (NSInteger) status { return _status; } - (NSDictionary*) httpHeaders { return _headers; } @end
007xsq-sadsad
Extensions/WebDAV/DAVResponse.m
Objective-C
bsd
16,166
#import "DELETEResponse.h" #import "HTTPLogging.h" // HTTP methods: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html // HTTP headers: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // HTTP status codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; @implementation DELETEResponse - (id) initWithFilePath:(NSString*)path { if ((self = [super init])) { BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path]; if ([[NSFileManager defaultManager] removeItemAtPath:path error:NULL]) { _status = exists ? 200 : 204; } else { HTTPLogError(@"Failed deleting \"%@\"", path); _status = 404; } } return self; } - (UInt64) contentLength { return 0; } - (UInt64) offset { return 0; } - (void)setOffset:(UInt64)offset { ; } - (NSData*) readDataOfLength:(NSUInteger)length { return nil; } - (BOOL) isDone { return YES; } - (NSInteger) status { return _status; } @end
007xsq-sadsad
Extensions/WebDAV/DELETEResponse.m
Objective-C
bsd
1,004
#import "PUTResponse.h" #import "HTTPLogging.h" // HTTP methods: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html // HTTP headers: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html // HTTP status codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; @implementation PUTResponse - (id) initWithFilePath:(NSString*)path headers:(NSDictionary*)headers body:(id)body { if ((self = [super init])) { if ([headers objectForKey:@"Content-Range"]) { HTTPLogError(@"Content-Range not supported for upload to \"%@\"", path); _status = 400; } else { BOOL overwrite = [[NSFileManager defaultManager] fileExistsAtPath:path]; BOOL success; if ([body isKindOfClass:[NSString class]]) { [[NSFileManager defaultManager] removeItemAtPath:path error:NULL]; success = [[NSFileManager defaultManager] moveItemAtPath:body toPath:path error:NULL]; } else { success = [body writeToFile:path atomically:YES]; } if (success) { _status = overwrite ? 200 : 201; } else { HTTPLogError(@"Failed writing upload to \"%@\"", path); _status = 403; } } } return self; } - (id) initWithFilePath:(NSString*)path headers:(NSDictionary*)headers bodyData:(NSData*)body { return [self initWithFilePath:path headers:headers body:body]; } - (id) initWithFilePath:(NSString*)path headers:(NSDictionary*)headers bodyFile:(NSString*)body { return [self initWithFilePath:path headers:headers body:body]; } - (UInt64) contentLength { return 0; } - (UInt64) offset { return 0; } - (void) setOffset:(UInt64)offset { ; } - (NSData*) readDataOfLength:(NSUInteger)length { return nil; } - (BOOL) isDone { return YES; } - (NSInteger) status { return _status; } @end
007xsq-sadsad
Extensions/WebDAV/PUTResponse.m
Objective-C
bsd
1,837
#import "HTTPConnection.h" @interface DAVConnection : HTTPConnection { id requestContentBody; NSOutputStream* requestContentStream; } @end
007xsq-sadsad
Extensions/WebDAV/DAVConnection.h
Objective-C
bsd
143
#import "HTTPResponse.h" @interface DELETEResponse : NSObject <HTTPResponse> { NSInteger _status; } - (id) initWithFilePath:(NSString*)path; @end
007xsq-sadsad
Extensions/WebDAV/DELETEResponse.h
Objective-C
bsd
149
#import "HTTPResponse.h" @interface DAVResponse : NSObject <HTTPResponse> { @private UInt64 _offset; NSMutableDictionary* _headers; NSData* _data; NSInteger _status; } - (id) initWithMethod:(NSString*)method headers:(NSDictionary*)headers bodyData:(NSData*)body resourcePath:(NSString*)resourcePath rootPath:(NSString*)rootPath; @end
007xsq-sadsad
Extensions/WebDAV/DAVResponse.h
Objective-C
bsd
343
#import "HTTPResponse.h" @interface PUTResponse : NSObject <HTTPResponse> { NSInteger _status; } - (id) initWithFilePath:(NSString*)path headers:(NSDictionary*)headers bodyData:(NSData*)body; - (id) initWithFilePath:(NSString*)path headers:(NSDictionary*)headers bodyFile:(NSString*)body; @end
007xsq-sadsad
Extensions/WebDAV/PUTResponse.h
Objective-C
bsd
297
#import "GCDAsyncSocket.h" #import "HTTPServer.h" #import "HTTPConnection.h" #import "HTTPMessage.h" #import "HTTPResponse.h" #import "HTTPAuthenticationRequest.h" #import "DDNumber.h" #import "DDRange.h" #import "DDData.h" #import "HTTPFileResponse.h" #import "HTTPAsyncFileResponse.h" #import "WebSocket.h" #import "HTTPLogging.h" // Log levels: off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; // Define chunk size used to read in data for responses // This is how much data will be read from disk into RAM at a time #if TARGET_OS_IPHONE #define READ_CHUNKSIZE (1024 * 128) #else #define READ_CHUNKSIZE (1024 * 512) #endif // Define chunk size used to read in POST upload data #if TARGET_OS_IPHONE #define POST_CHUNKSIZE (1024 * 32) #else #define POST_CHUNKSIZE (1024 * 128) #endif // Define the various timeouts (in seconds) for various parts of the HTTP process #define TIMEOUT_READ_FIRST_HEADER_LINE 30 #define TIMEOUT_READ_SUBSEQUENT_HEADER_LINE 30 #define TIMEOUT_READ_BODY -1 #define TIMEOUT_WRITE_HEAD 30 #define TIMEOUT_WRITE_BODY -1 #define TIMEOUT_WRITE_ERROR 30 #define TIMEOUT_NONCE 300 // Define the various limits // MAX_HEADER_LINE_LENGTH: Max length (in bytes) of any single line in a header (including \r\n) // MAX_HEADER_LINES : Max number of lines in a single header (including first GET line) #define MAX_HEADER_LINE_LENGTH 8190 #define MAX_HEADER_LINES 100 // MAX_CHUNK_LINE_LENGTH : For accepting chunked transfer uploads, max length of chunk size line (including \r\n) #define MAX_CHUNK_LINE_LENGTH 200 // Define the various tags we'll use to differentiate what it is we're currently doing #define HTTP_REQUEST_HEADER 10 #define HTTP_REQUEST_BODY 11 #define HTTP_REQUEST_CHUNK_SIZE 12 #define HTTP_REQUEST_CHUNK_DATA 13 #define HTTP_REQUEST_CHUNK_TRAILER 14 #define HTTP_REQUEST_CHUNK_FOOTER 15 #define HTTP_PARTIAL_RESPONSE 20 #define HTTP_PARTIAL_RESPONSE_HEADER 21 #define HTTP_PARTIAL_RESPONSE_BODY 22 #define HTTP_CHUNKED_RESPONSE_HEADER 30 #define HTTP_CHUNKED_RESPONSE_BODY 31 #define HTTP_CHUNKED_RESPONSE_FOOTER 32 #define HTTP_PARTIAL_RANGE_RESPONSE_BODY 40 #define HTTP_PARTIAL_RANGES_RESPONSE_BODY 50 #define HTTP_RESPONSE 90 #define HTTP_FINAL_RESPONSE 91 // A quick note about the tags: // // The HTTP_RESPONSE and HTTP_FINAL_RESPONSE are designated tags signalling that the response is completely sent. // That is, in the onSocket:didWriteDataWithTag: method, if the tag is HTTP_RESPONSE or HTTP_FINAL_RESPONSE, // it is assumed that the response is now completely sent. // Use HTTP_RESPONSE if it's the end of a response, and you want to start reading more requests afterwards. // Use HTTP_FINAL_RESPONSE if you wish to terminate the connection after sending the response. // // If you are sending multiple data segments in a custom response, make sure that only the last segment has // the HTTP_RESPONSE tag. For all other segments prior to the last segment use HTTP_PARTIAL_RESPONSE, or some other // tag of your own invention. @interface HTTPConnection (PrivateAPI) - (void)startReadingRequest; - (void)sendResponseHeadersAndBody; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation HTTPConnection static NSMutableArray *recentNonces; /** * This method is automatically called (courtesy of Cocoa) before the first instantiation of this class. * We use it to initialize any static variables. **/ + (void)initialize { static BOOL initialized = NO; if(!initialized) { // Initialize class variables recentNonces = [[NSMutableArray alloc] initWithCapacity:5]; initialized = YES; } } /** * This method is designed to be called by a scheduled timer, and will remove a nonce from the recent nonce list. * The nonce to remove should be set as the timer's userInfo. **/ + (void)removeRecentNonce:(NSTimer *)aTimer { [recentNonces removeObject:[aTimer userInfo]]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Init, Dealloc: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Sole Constructor. * Associates this new HTTP connection with the given AsyncSocket. * This HTTP connection object will become the socket's delegate and take over responsibility for the socket. **/ - (id)initWithAsyncSocket:(GCDAsyncSocket *)newSocket configuration:(HTTPConfig *)aConfig { if ((self = [super init])) { HTTPLogTrace(); if (aConfig.queue) { connectionQueue = aConfig.queue; dispatch_retain(connectionQueue); } else { connectionQueue = dispatch_queue_create("HTTPConnection", NULL); } // Take over ownership of the socket asyncSocket = [newSocket retain]; [asyncSocket setDelegate:self delegateQueue:connectionQueue]; // Store configuration config = [aConfig retain]; // Initialize lastNC (last nonce count). // Used with digest access authentication. // These must increment for each request from the client. lastNC = 0; // Create a new HTTP message request = [[HTTPMessage alloc] initEmptyRequest]; numHeaderLines = 0; responseDataSizes = [[NSMutableArray alloc] initWithCapacity:5]; } return self; } /** * Standard Deconstructor. **/ - (void)dealloc { HTTPLogTrace(); dispatch_release(connectionQueue); [asyncSocket setDelegate:nil delegateQueue:NULL]; [asyncSocket disconnect]; [asyncSocket release]; [config release]; [request release]; [nonce release]; if ([httpResponse respondsToSelector:@selector(connectionDidClose)]) { [httpResponse connectionDidClose]; } [httpResponse release]; [ranges release]; [ranges_headers release]; [ranges_boundry release]; [responseDataSizes release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Method Support //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns whether or not the server will accept messages of a given method * at a particular URI. **/ - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path { HTTPLogTrace(); // Override me to support methods such as POST. // // Things you may want to consider: // - Does the given path represent a resource that is designed to accept this method? // - If accepting an upload, is the size of the data being uploaded too big? // To do this you can check the requestContentLength variable. // // For more information, you can always access the HTTPMessage request variable. // // You should fall through with a call to [super supportsMethod:method atPath:path] // // See also: expectsRequestBodyFromMethod:atPath: if ([method isEqualToString:@"GET"]) return YES; if ([method isEqualToString:@"HEAD"]) return YES; return NO; } /** * Returns whether or not the server expects a body from the given method. * * In other words, should the server expect a content-length header and associated body from this method. * This would be true in the case of a POST, where the client is sending data, * or for something like PUT where the client is supposed to be uploading a file. **/ - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path { HTTPLogTrace(); // Override me to add support for other methods that expect the client // to send a body along with the request header. // // You should fall through with a call to [super expectsRequestBodyFromMethod:method atPath:path] // // See also: supportsMethod:atPath: if ([method isEqualToString:@"POST"]) return YES; if ([method isEqualToString:@"PUT"]) return YES; return NO; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark HTTPS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns whether or not the server is configured to be a secure server. * In other words, all connections to this server are immediately secured, thus only secure connections are allowed. * This is the equivalent of having an https server, where it is assumed that all connections must be secure. * If this is the case, then unsecure connections will not be allowed on this server, and a separate unsecure server * would need to be run on a separate port in order to support unsecure connections. * * Note: In order to support secure connections, the sslIdentityAndCertificates method must be implemented. **/ - (BOOL)isSecureServer { HTTPLogTrace(); // Override me to create an https server... return NO; } /** * This method is expected to returns an array appropriate for use in kCFStreamSSLCertificates SSL Settings. * It should be an array of SecCertificateRefs except for the first element in the array, which is a SecIdentityRef. **/ - (NSArray *)sslIdentityAndCertificates { HTTPLogTrace(); // Override me to provide the proper required SSL identity. return nil; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Password Protection //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns whether or not the requested resource is password protected. * In this generic implementation, nothing is password protected. **/ - (BOOL)isPasswordProtected:(NSString *)path { HTTPLogTrace(); // Override me to provide password protection... // You can configure it for the entire server, or based on the current request return NO; } /** * Returns whether or not the authentication challenge should use digest access authentication. * The alternative is basic authentication. * * If at all possible, digest access authentication should be used because it's more secure. * Basic authentication sends passwords in the clear and should be avoided unless using SSL/TLS. **/ - (BOOL)useDigestAccessAuthentication { HTTPLogTrace(); // Override me to customize the authentication scheme // Make sure you understand the security risks of using the weaker basic authentication return YES; } /** * Returns the authentication realm. * In this generic implmentation, a default realm is used for the entire server. **/ - (NSString *)realm { HTTPLogTrace(); // Override me to provide a custom realm... // You can configure it for the entire server, or based on the current request return @"defaultRealm@host.com"; } /** * Returns the password for the given username. **/ - (NSString *)passwordForUser:(NSString *)username { HTTPLogTrace(); // Override me to provide proper password authentication // You can configure a password for the entire server, or custom passwords for users and/or resources // Security Note: // A nil password means no access at all. (Such as for user doesn't exist) // An empty string password is allowed, and will be treated as any other password. (To support anonymous access) return nil; } /** * Generates and returns an authentication nonce. * A nonce is a server-specified string uniquely generated for each 401 response. * The default implementation uses a single nonce for each session. **/ - (NSString *)generateNonce { HTTPLogTrace(); // We use the Core Foundation UUID class to generate a nonce value for us // UUIDs (Universally Unique Identifiers) are 128-bit values guaranteed to be unique. CFUUIDRef theUUID = CFUUIDCreate(NULL); NSString *newNonce = [NSMakeCollectable(CFUUIDCreateString(NULL, theUUID)) autorelease]; CFRelease(theUUID); // We have to remember that the HTTP protocol is stateless. // Even though with version 1.1 persistent connections are the norm, they are not guaranteed. // Thus if we generate a nonce for this connection, // it should be honored for other connections in the near future. // // In fact, this is absolutely necessary in order to support QuickTime. // When QuickTime makes it's initial connection, it will be unauthorized, and will receive a nonce. // It then disconnects, and creates a new connection with the nonce, and proper authentication. // If we don't honor the nonce for the second connection, QuickTime will repeat the process and never connect. [recentNonces addObject:newNonce]; [NSTimer scheduledTimerWithTimeInterval:TIMEOUT_NONCE target:[HTTPConnection class] selector:@selector(removeRecentNonce:) userInfo:newNonce repeats:NO]; return newNonce; } /** * Returns whether or not the user is properly authenticated. **/ - (BOOL)isAuthenticated { HTTPLogTrace(); // Extract the authentication information from the Authorization header HTTPAuthenticationRequest *auth = [[[HTTPAuthenticationRequest alloc] initWithRequest:request] autorelease]; if ([self useDigestAccessAuthentication]) { // Digest Access Authentication (RFC 2617) if(![auth isDigest]) { // User didn't send proper digest access authentication credentials return NO; } if ([auth username] == nil) { // The client didn't provide a username // Most likely they didn't provide any authentication at all return NO; } NSString *password = [self passwordForUser:[auth username]]; if (password == nil) { // No access allowed (username doesn't exist in system) return NO; } NSString *url = [[request url] relativeString]; if (![url isEqualToString:[auth uri]]) { // Requested URL and Authorization URI do not match // This could be a replay attack // IE - attacker provides same authentication information, but requests a different resource return NO; } // The nonce the client provided will most commonly be stored in our local (cached) nonce variable if (![nonce isEqualToString:[auth nonce]]) { // The given nonce may be from another connection // We need to search our list of recent nonce strings that have been recently distributed if ([recentNonces containsObject:[auth nonce]]) { // Store nonce in local (cached) nonce variable to prevent array searches in the future [nonce release]; nonce = [[auth nonce] copy]; // The client has switched to using a different nonce value // This may happen if the client tries to get a file in a directory with different credentials. // The previous credentials wouldn't work, and the client would receive a 401 error // along with a new nonce value. The client then uses this new nonce value and requests the file again. // Whatever the case may be, we need to reset lastNC, since that variable is on a per nonce basis. lastNC = 0; } else { // We have no knowledge of ever distributing such a nonce. // This could be a replay attack from a previous connection in the past. return NO; } } long authNC = strtol([[auth nc] UTF8String], NULL, 16); if (authNC <= lastNC) { // The nc value (nonce count) hasn't been incremented since the last request. // This could be a replay attack. return NO; } lastNC = authNC; NSString *HA1str = [NSString stringWithFormat:@"%@:%@:%@", [auth username], [auth realm], password]; NSString *HA2str = [NSString stringWithFormat:@"%@:%@", [request method], [auth uri]]; NSString *HA1 = [[[HA1str dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue]; NSString *HA2 = [[[HA2str dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue]; NSString *responseStr = [NSString stringWithFormat:@"%@:%@:%@:%@:%@:%@", HA1, [auth nonce], [auth nc], [auth cnonce], [auth qop], HA2]; NSString *response = [[[responseStr dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue]; return [response isEqualToString:[auth response]]; } else { // Basic Authentication if (![auth isBasic]) { // User didn't send proper base authentication credentials return NO; } // Decode the base 64 encoded credentials NSString *base64Credentials = [auth base64Credentials]; NSData *temp = [[base64Credentials dataUsingEncoding:NSUTF8StringEncoding] base64Decoded]; NSString *credentials = [[[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding] autorelease]; // The credentials should be of the form "username:password" // The username is not allowed to contain a colon NSRange colonRange = [credentials rangeOfString:@":"]; if (colonRange.length == 0) { // Malformed credentials return NO; } NSString *credUsername = [credentials substringToIndex:colonRange.location]; NSString *credPassword = [credentials substringFromIndex:(colonRange.location + colonRange.length)]; NSString *password = [self passwordForUser:credUsername]; if (password == nil) { // No access allowed (username doesn't exist in system) return NO; } return [password isEqualToString:credPassword]; } } /** * Adds a digest access authentication challenge to the given response. **/ - (void)addDigestAuthChallenge:(HTTPMessage *)response { HTTPLogTrace(); NSString *authFormat = @"Digest realm=\"%@\", qop=\"auth\", nonce=\"%@\""; NSString *authInfo = [NSString stringWithFormat:authFormat, [self realm], [self generateNonce]]; [response setHeaderField:@"WWW-Authenticate" value:authInfo]; } /** * Adds a basic authentication challenge to the given response. **/ - (void)addBasicAuthChallenge:(HTTPMessage *)response { HTTPLogTrace(); NSString *authFormat = @"Basic realm=\"%@\""; NSString *authInfo = [NSString stringWithFormat:authFormat, [self realm]]; [response setHeaderField:@"WWW-Authenticate" value:authInfo]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Core //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Starting point for the HTTP connection after it has been fully initialized (including subclasses). * This method is called by the HTTP server. **/ - (void)start { dispatch_async(connectionQueue, ^{ if (started) return; started = YES; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self startConnection]; [pool drain]; }); } /** * This method is called by the HTTPServer if it is asked to stop. * The server, in turn, invokes stop on each HTTPConnection instance. **/ - (void)stop { dispatch_async(connectionQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Disconnect the socket. // The socketDidDisconnect delegate method will handle everything else. [asyncSocket disconnect]; [pool drain]; }); } /** * Starting point for the HTTP connection. **/ - (void)startConnection { // Override me to do any custom work before the connection starts. // // Be sure to invoke [super startConnection] when you're done. HTTPLogTrace(); if ([self isSecureServer]) { // We are configured to be an HTTPS server. // That is, we secure via SSL/TLS the connection prior to any communication. NSArray *certificates = [self sslIdentityAndCertificates]; if ([certificates count] > 0) { // All connections are assumed to be secure. Only secure connections are allowed on this server. NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3]; // Configure this connection as the server [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLIsServer]; [settings setObject:certificates forKey:(NSString *)kCFStreamSSLCertificates]; // Configure this connection to use the highest possible SSL level [settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString *)kCFStreamSSLLevel]; [asyncSocket startTLS:settings]; } } [self startReadingRequest]; } /** * Starts reading an HTTP request. **/ - (void)startReadingRequest { HTTPLogTrace(); [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:TIMEOUT_READ_FIRST_HEADER_LINE maxLength:MAX_HEADER_LINE_LENGTH tag:HTTP_REQUEST_HEADER]; } /** * Parses the given query string. * * For example, if the query is "q=John%20Mayer%20Trio&num=50" * then this method would return the following dictionary: * { * q = "John Mayer Trio" * num = "50" * } **/ - (NSDictionary *)parseParams:(NSString *)query { NSArray *components = [query componentsSeparatedByString:@"&"]; NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:[components count]]; NSUInteger i; for (i = 0; i < [components count]; i++) { NSString *component = [components objectAtIndex:i]; if ([component length] > 0) { NSRange range = [component rangeOfString:@"="]; if (range.location != NSNotFound) { NSString *escapedKey = [component substringToIndex:(range.location + 0)]; NSString *escapedValue = [component substringFromIndex:(range.location + 1)]; if ([escapedKey length] > 0) { CFStringRef k, v; k = CFURLCreateStringByReplacingPercentEscapes(NULL, (CFStringRef)escapedKey, CFSTR("")); v = CFURLCreateStringByReplacingPercentEscapes(NULL, (CFStringRef)escapedValue, CFSTR("")); NSString *key, *value; key = [NSMakeCollectable(k) autorelease]; value = [NSMakeCollectable(v) autorelease]; if (key) { if (value) [result setObject:value forKey:key]; else [result setObject:[NSNull null] forKey:key]; } } } } } return result; } /** * Parses the query variables in the request URI. * * For example, if the request URI was "/search.html?q=John%20Mayer%20Trio&num=50" * then this method would return the following dictionary: * { * q = "John Mayer Trio" * num = "50" * } **/ - (NSDictionary *)parseGetParams { if(![request isHeaderComplete]) return nil; NSDictionary *result = nil; NSURL *url = [request url]; if(url) { NSString *query = [url query]; if (query) { result = [self parseParams:query]; } } return result; } /** * Attempts to parse the given range header into a series of sequential non-overlapping ranges. * If successfull, the variables 'ranges' and 'rangeIndex' will be updated, and YES will be returned. * Otherwise, NO is returned, and the range request should be ignored. **/ - (BOOL)parseRangeRequest:(NSString *)rangeHeader withContentLength:(UInt64)contentLength { HTTPLogTrace(); // Examples of byte-ranges-specifier values (assuming an entity-body of length 10000): // // - The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-499 // // - The second 500 bytes (byte offsets 500-999, inclusive): bytes=500-999 // // - The final 500 bytes (byte offsets 9500-9999, inclusive): bytes=-500 // // - Or bytes=9500- // // - The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1 // // - Several legal but not canonical specifications of the second 500 bytes (byte offsets 500-999, inclusive): // bytes=500-600,601-999 // bytes=500-700,601-999 // NSRange eqsignRange = [rangeHeader rangeOfString:@"="]; if(eqsignRange.location == NSNotFound) return NO; NSUInteger tIndex = eqsignRange.location; NSUInteger fIndex = eqsignRange.location + eqsignRange.length; NSString *rangeType = [[[rangeHeader substringToIndex:tIndex] mutableCopy] autorelease]; NSString *rangeValue = [[[rangeHeader substringFromIndex:fIndex] mutableCopy] autorelease]; CFStringTrimWhitespace((CFMutableStringRef)rangeType); CFStringTrimWhitespace((CFMutableStringRef)rangeValue); if([rangeType caseInsensitiveCompare:@"bytes"] != NSOrderedSame) return NO; NSArray *rangeComponents = [rangeValue componentsSeparatedByString:@","]; if([rangeComponents count] == 0) return NO; [ranges release]; ranges = [[NSMutableArray alloc] initWithCapacity:[rangeComponents count]]; rangeIndex = 0; // Note: We store all range values in the form of DDRange structs, wrapped in NSValue objects. // Since DDRange consists of UInt64 values, the range extends up to 16 exabytes. NSUInteger i; for (i = 0; i < [rangeComponents count]; i++) { NSString *rangeComponent = [rangeComponents objectAtIndex:i]; NSRange dashRange = [rangeComponent rangeOfString:@"-"]; if (dashRange.location == NSNotFound) { // We're dealing with an individual byte number UInt64 byteIndex; if(![NSNumber parseString:rangeComponent intoUInt64:&byteIndex]) return NO; if(byteIndex >= contentLength) return NO; [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(byteIndex, 1)]]; } else { // We're dealing with a range of bytes tIndex = dashRange.location; fIndex = dashRange.location + dashRange.length; NSString *r1str = [rangeComponent substringToIndex:tIndex]; NSString *r2str = [rangeComponent substringFromIndex:fIndex]; UInt64 r1, r2; BOOL hasR1 = [NSNumber parseString:r1str intoUInt64:&r1]; BOOL hasR2 = [NSNumber parseString:r2str intoUInt64:&r2]; if (!hasR1) { // We're dealing with a "-[#]" range // // r2 is the number of ending bytes to include in the range if(!hasR2) return NO; if(r2 > contentLength) return NO; UInt64 startIndex = contentLength - r2; [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(startIndex, r2)]]; } else if (!hasR2) { // We're dealing with a "[#]-" range // // r1 is the starting index of the range, which goes all the way to the end if(r1 >= contentLength) return NO; [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(r1, contentLength - r1)]]; } else { // We're dealing with a normal "[#]-[#]" range // // Note: The range is inclusive. So 0-1 has a length of 2 bytes. if(r1 > r2) return NO; if(r2 >= contentLength) return NO; [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(r1, r2 - r1 + 1)]]; } } } if([ranges count] == 0) return NO; // Now make sure none of the ranges overlap for (i = 0; i < [ranges count] - 1; i++) { DDRange range1 = [[ranges objectAtIndex:i] ddrangeValue]; NSUInteger j; for (j = i+1; j < [ranges count]; j++) { DDRange range2 = [[ranges objectAtIndex:j] ddrangeValue]; DDRange iRange = DDIntersectionRange(range1, range2); if(iRange.length != 0) { return NO; } } } // Sort the ranges [ranges sortUsingSelector:@selector(ddrangeCompare:)]; return YES; } - (NSString *)requestURI { if(request == nil) return nil; return [[request url] relativeString]; } /** * This method is called after a full HTTP request has been received. * The current request is in the HTTPMessage request variable. **/ - (void)replyToHTTPRequest { HTTPLogTrace(); if (HTTP_LOG_VERBOSE) { NSData *tempData = [request messageData]; NSString *tempStr = [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding]; HTTPLogVerbose(@"%@[%p]: Received HTTP request:\n%@", THIS_FILE, self, tempStr); [tempStr release]; } // Check the HTTP version // We only support version 1.0 and 1.1 NSString *version = [request version]; if (![version isEqualToString:HTTPVersion1_1] && ![version isEqualToString:HTTPVersion1_0]) { [self handleVersionNotSupported:version]; return; } // Extract requested URI NSString *uri = [self requestURI]; // Check for WebSocket request if ([WebSocket isWebSocketRequest:request]) { HTTPLogVerbose(@"isWebSocket"); WebSocket *ws = [self webSocketForURI:uri]; if (ws == nil) { [self handleResourceNotFound]; } else { [ws start]; [[config server] addWebSocket:ws]; // The WebSocket should now be the delegate of the underlying socket. // But gracefully handle the situation if it forgot. if ([asyncSocket delegate] == self) { HTTPLogWarn(@"%@[%p]: WebSocket forgot to set itself as socket delegate", THIS_FILE, self); // Disconnect the socket. // The socketDidDisconnect delegate method will handle everything else. [asyncSocket disconnect]; } else { // The WebSocket is using the socket, // so make sure we don't disconnect it in the dealloc method. [asyncSocket release]; asyncSocket = nil; [self die]; // Note: There is a timing issue here that should be pointed out. // // A bug that existed in previous versions happend like so: // - We invoked [self die] // - This caused us to get released, and our dealloc method to start executing // - Meanwhile, AsyncSocket noticed a disconnect, and began to dispatch a socketDidDisconnect at us // - The dealloc method finishes execution, and our instance gets freed // - The socketDidDisconnect gets run, and a crash occurs // // So the issue we want to avoid is releasing ourself when there is a possibility // that AsyncSocket might be gearing up to queue a socketDidDisconnect for us. // // In this particular situation notice that we invoke [asyncSocket delegate]. // This method is synchronous concerning AsyncSocket's internal socketQueue. // Which means we can be sure, when it returns, that AsyncSocket has already // queued any delegate methods for us if it was going to. // And if the delegate methods are queued, then we've been properly retained. // Meaning we won't get released / dealloc'd until the delegate method has finished executing. // // In this rare situation, the die method will get invoked twice. } } return; } // Check Authentication (if needed) // If not properly authenticated for resource, issue Unauthorized response if ([self isPasswordProtected:uri] && ![self isAuthenticated]) { [self handleAuthenticationFailed]; return; } // Extract the method NSString *method = [request method]; // Note: We already checked to ensure the method was supported in onSocket:didReadData:withTag: // Respond properly to HTTP 'GET' and 'HEAD' commands httpResponse = [[self httpResponseForMethod:method URI:uri] retain]; if (httpResponse == nil) { [self handleResourceNotFound]; return; } [self sendResponseHeadersAndBody]; } /** * Prepares a single-range response. * * Note: The returned HTTPMessage is owned by the sender, who is responsible for releasing it. **/ - (HTTPMessage *)newUniRangeResponse:(UInt64)contentLength { HTTPLogTrace(); // Status Code 206 - Partial Content HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:206 description:nil version:HTTPVersion1_1]; DDRange range = [[ranges objectAtIndex:0] ddrangeValue]; NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", range.length]; [response setHeaderField:@"Content-Length" value:contentLengthStr]; NSString *rangeStr = [NSString stringWithFormat:@"%qu-%qu", range.location, DDMaxRange(range) - 1]; NSString *contentRangeStr = [NSString stringWithFormat:@"bytes %@/%qu", rangeStr, contentLength]; [response setHeaderField:@"Content-Range" value:contentRangeStr]; return response; } /** * Prepares a multi-range response. * * Note: The returned HTTPMessage is owned by the sender, who is responsible for releasing it. **/ - (HTTPMessage *)newMultiRangeResponse:(UInt64)contentLength { HTTPLogTrace(); // Status Code 206 - Partial Content HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:206 description:nil version:HTTPVersion1_1]; // We have to send each range using multipart/byteranges // So each byterange has to be prefix'd and suffix'd with the boundry // Example: // // HTTP/1.1 206 Partial Content // Content-Length: 220 // Content-Type: multipart/byteranges; boundary=4554d24e986f76dd6 // // // --4554d24e986f76dd6 // Content-Range: bytes 0-25/4025 // // [...] // --4554d24e986f76dd6 // Content-Range: bytes 3975-4024/4025 // // [...] // --4554d24e986f76dd6-- ranges_headers = [[NSMutableArray alloc] initWithCapacity:[ranges count]]; CFUUIDRef theUUID = CFUUIDCreate(NULL); ranges_boundry = NSMakeCollectable(CFUUIDCreateString(NULL, theUUID)); CFRelease(theUUID); NSString *startingBoundryStr = [NSString stringWithFormat:@"\r\n--%@\r\n", ranges_boundry]; NSString *endingBoundryStr = [NSString stringWithFormat:@"\r\n--%@--\r\n", ranges_boundry]; UInt64 actualContentLength = 0; NSUInteger i; for (i = 0; i < [ranges count]; i++) { DDRange range = [[ranges objectAtIndex:i] ddrangeValue]; NSString *rangeStr = [NSString stringWithFormat:@"%qu-%qu", range.location, DDMaxRange(range) - 1]; NSString *contentRangeVal = [NSString stringWithFormat:@"bytes %@/%qu", rangeStr, contentLength]; NSString *contentRangeStr = [NSString stringWithFormat:@"Content-Range: %@\r\n\r\n", contentRangeVal]; NSString *fullHeader = [startingBoundryStr stringByAppendingString:contentRangeStr]; NSData *fullHeaderData = [fullHeader dataUsingEncoding:NSUTF8StringEncoding]; [ranges_headers addObject:fullHeaderData]; actualContentLength += [fullHeaderData length]; actualContentLength += range.length; } NSData *endingBoundryData = [endingBoundryStr dataUsingEncoding:NSUTF8StringEncoding]; actualContentLength += [endingBoundryData length]; NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", actualContentLength]; [response setHeaderField:@"Content-Length" value:contentLengthStr]; NSString *contentTypeStr = [NSString stringWithFormat:@"multipart/byteranges; boundary=%@", ranges_boundry]; [response setHeaderField:@"Content-Type" value:contentTypeStr]; return response; } /** * Returns the chunk size line that must precede each chunk of data when using chunked transfer encoding. * This consists of the size of the data, in hexadecimal, followed by a CRLF. **/ - (NSData *)chunkedTransferSizeLineForLength:(NSUInteger)length { return [[NSString stringWithFormat:@"%lx\r\n", (unsigned long)length] dataUsingEncoding:NSUTF8StringEncoding]; } /** * Returns the data that signals the end of a chunked transfer. **/ - (NSData *)chunkedTransferFooter { // Each data chunk is preceded by a size line (in hex and including a CRLF), // followed by the data itself, followed by another CRLF. // After every data chunk has been sent, a zero size line is sent, // followed by optional footer (which are just more headers), // and followed by a CRLF on a line by itself. return [@"\r\n0\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]; } - (void)sendResponseHeadersAndBody { if ([httpResponse respondsToSelector:@selector(delayResponeHeaders)]) { if ([httpResponse delayResponeHeaders]) { return; } } BOOL isChunked = NO; if ([httpResponse respondsToSelector:@selector(isChunked)]) { isChunked = [httpResponse isChunked]; } // If a response is "chunked", this simply means the HTTPResponse object // doesn't know the content-length in advance. UInt64 contentLength = 0; if (!isChunked) { contentLength = [httpResponse contentLength]; } // Check for specific range request NSString *rangeHeader = [request headerField:@"Range"]; BOOL isRangeRequest = NO; // If the response is "chunked" then we don't know the exact content-length. // This means we'll be unable to process any range requests. // This is because range requests might include a range like "give me the last 100 bytes" if (!isChunked && rangeHeader) { if ([self parseRangeRequest:rangeHeader withContentLength:contentLength]) { isRangeRequest = YES; } } HTTPMessage *response; if (!isRangeRequest) { // Create response // Default status code: 200 - OK NSInteger status = 200; if ([httpResponse respondsToSelector:@selector(status)]) { status = [httpResponse status]; } response = [[HTTPMessage alloc] initResponseWithStatusCode:status description:nil version:HTTPVersion1_1]; if (isChunked) { [response setHeaderField:@"Transfer-Encoding" value:@"chunked"]; } else { NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", contentLength]; [response setHeaderField:@"Content-Length" value:contentLengthStr]; } } else { if ([ranges count] == 1) { response = [self newUniRangeResponse:contentLength]; } else { response = [self newMultiRangeResponse:contentLength]; } } BOOL isZeroLengthResponse = !isChunked && (contentLength == 0); // If they issue a 'HEAD' command, we don't have to include the file // If they issue a 'GET' command, we need to include the file if ([[request method] isEqualToString:@"HEAD"] || isZeroLengthResponse) { NSData *responseData = [self preprocessResponse:response]; [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE]; sentResponseHeaders = YES; } else { // Write the header response NSData *responseData = [self preprocessResponse:response]; [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_PARTIAL_RESPONSE_HEADER]; sentResponseHeaders = YES; // Now we need to send the body of the response if (!isRangeRequest) { // Regular request NSData *data = [httpResponse readDataOfLength:READ_CHUNKSIZE]; if ([data length] > 0) { [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]]; if (isChunked) { NSData *chunkSize = [self chunkedTransferSizeLineForLength:[data length]]; [asyncSocket writeData:chunkSize withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_HEADER]; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_CHUNKED_RESPONSE_BODY]; if ([httpResponse isDone]) { NSData *footer = [self chunkedTransferFooter]; [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE]; } else { NSData *footer = [GCDAsyncSocket CRLFData]; [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_FOOTER]; } } else { long tag = [httpResponse isDone] ? HTTP_RESPONSE : HTTP_PARTIAL_RESPONSE_BODY; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag]; } } } else { // Client specified a byte range in request if ([ranges count] == 1) { // Client is requesting a single range DDRange range = [[ranges objectAtIndex:0] ddrangeValue]; [httpResponse setOffset:range.location]; NSUInteger bytesToRead = range.length < READ_CHUNKSIZE ? (NSUInteger)range.length : READ_CHUNKSIZE; NSData *data = [httpResponse readDataOfLength:bytesToRead]; if ([data length] > 0) { [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]]; long tag = [data length] == range.length ? HTTP_RESPONSE : HTTP_PARTIAL_RANGE_RESPONSE_BODY; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag]; } } else { // Client is requesting multiple ranges // We have to send each range using multipart/byteranges // Write range header NSData *rangeHeaderData = [ranges_headers objectAtIndex:0]; [asyncSocket writeData:rangeHeaderData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_PARTIAL_RESPONSE_HEADER]; // Start writing range body DDRange range = [[ranges objectAtIndex:0] ddrangeValue]; [httpResponse setOffset:range.location]; NSUInteger bytesToRead = range.length < READ_CHUNKSIZE ? (NSUInteger)range.length : READ_CHUNKSIZE; NSData *data = [httpResponse readDataOfLength:bytesToRead]; if ([data length] > 0) { [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]]; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_PARTIAL_RANGES_RESPONSE_BODY]; } } } } [response release]; } /** * Returns the number of bytes of the http response body that are sitting in asyncSocket's write queue. * * We keep track of this information in order to keep our memory footprint low while * working with asynchronous HTTPResponse objects. **/ - (NSUInteger)writeQueueSize { NSUInteger result = 0; NSUInteger i; for(i = 0; i < [responseDataSizes count]; i++) { result += [[responseDataSizes objectAtIndex:i] unsignedIntegerValue]; } return result; } /** * Sends more data, if needed, without growing the write queue over its approximate size limit. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE. * * This method should only be called for standard (non-range) responses. **/ - (void)continueSendingStandardResponseBody { HTTPLogTrace(); // This method is called when either asyncSocket has finished writing one of the response data chunks, // or when an asynchronous HTTPResponse object informs us that it has more available data for us to send. // In the case of the asynchronous HTTPResponse, we don't want to blindly grab the new data, // and shove it onto asyncSocket's write queue. // Doing so could negatively affect the memory footprint of the application. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue. // // Note that this does not affect the rate at which the HTTPResponse object may generate data. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely // use the calls to readDataOfLength as an indication to start generating more data. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate // at which the socket is able to send it. NSUInteger writeQueueSize = [self writeQueueSize]; if(writeQueueSize >= READ_CHUNKSIZE) return; NSUInteger available = READ_CHUNKSIZE - writeQueueSize; NSData *data = [httpResponse readDataOfLength:available]; if ([data length] > 0) { [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]]; BOOL isChunked = NO; if ([httpResponse respondsToSelector:@selector(isChunked)]) { isChunked = [httpResponse isChunked]; } if (isChunked) { NSData *chunkSize = [self chunkedTransferSizeLineForLength:[data length]]; [asyncSocket writeData:chunkSize withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_HEADER]; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_CHUNKED_RESPONSE_BODY]; if([httpResponse isDone]) { NSData *footer = [self chunkedTransferFooter]; [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE]; } else { NSData *footer = [GCDAsyncSocket CRLFData]; [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_FOOTER]; } } else { long tag = [httpResponse isDone] ? HTTP_RESPONSE : HTTP_PARTIAL_RESPONSE_BODY; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag]; } } } /** * Sends more data, if needed, without growing the write queue over its approximate size limit. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE. * * This method should only be called for single-range responses. **/ - (void)continueSendingSingleRangeResponseBody { HTTPLogTrace(); // This method is called when either asyncSocket has finished writing one of the response data chunks, // or when an asynchronous response informs us that is has more available data for us to send. // In the case of the asynchronous response, we don't want to blindly grab the new data, // and shove it onto asyncSocket's write queue. // Doing so could negatively affect the memory footprint of the application. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue. // // Note that this does not affect the rate at which the HTTPResponse object may generate data. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely // use the calls to readDataOfLength as an indication to start generating more data. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate // at which the socket is able to send it. NSUInteger writeQueueSize = [self writeQueueSize]; if(writeQueueSize >= READ_CHUNKSIZE) return; DDRange range = [[ranges objectAtIndex:0] ddrangeValue]; UInt64 offset = [httpResponse offset]; UInt64 bytesRead = offset - range.location; UInt64 bytesLeft = range.length - bytesRead; if (bytesLeft > 0) { NSUInteger available = READ_CHUNKSIZE - writeQueueSize; NSUInteger bytesToRead = bytesLeft < available ? (NSUInteger)bytesLeft : available; NSData *data = [httpResponse readDataOfLength:bytesToRead]; if ([data length] > 0) { [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]]; long tag = [data length] == bytesLeft ? HTTP_RESPONSE : HTTP_PARTIAL_RANGE_RESPONSE_BODY; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag]; } } } /** * Sends more data, if needed, without growing the write queue over its approximate size limit. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE. * * This method should only be called for multi-range responses. **/ - (void)continueSendingMultiRangeResponseBody { HTTPLogTrace(); // This method is called when either asyncSocket has finished writing one of the response data chunks, // or when an asynchronous HTTPResponse object informs us that is has more available data for us to send. // In the case of the asynchronous HTTPResponse, we don't want to blindly grab the new data, // and shove it onto asyncSocket's write queue. // Doing so could negatively affect the memory footprint of the application. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue. // // Note that this does not affect the rate at which the HTTPResponse object may generate data. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely // use the calls to readDataOfLength as an indication to start generating more data. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate // at which the socket is able to send it. NSUInteger writeQueueSize = [self writeQueueSize]; if(writeQueueSize >= READ_CHUNKSIZE) return; DDRange range = [[ranges objectAtIndex:rangeIndex] ddrangeValue]; UInt64 offset = [httpResponse offset]; UInt64 bytesRead = offset - range.location; UInt64 bytesLeft = range.length - bytesRead; if (bytesLeft > 0) { NSUInteger available = READ_CHUNKSIZE - writeQueueSize; NSUInteger bytesToRead = bytesLeft < available ? (NSUInteger)bytesLeft : available; NSData *data = [httpResponse readDataOfLength:bytesToRead]; if ([data length] > 0) { [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]]; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_PARTIAL_RANGES_RESPONSE_BODY]; } } else { if (++rangeIndex < [ranges count]) { // Write range header NSData *rangeHeader = [ranges_headers objectAtIndex:rangeIndex]; [asyncSocket writeData:rangeHeader withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_PARTIAL_RESPONSE_HEADER]; // Start writing range body range = [[ranges objectAtIndex:rangeIndex] ddrangeValue]; [httpResponse setOffset:range.location]; NSUInteger available = READ_CHUNKSIZE - writeQueueSize; NSUInteger bytesToRead = range.length < available ? (NSUInteger)range.length : available; NSData *data = [httpResponse readDataOfLength:bytesToRead]; if ([data length] > 0) { [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]]; [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_PARTIAL_RANGES_RESPONSE_BODY]; } } else { // We're not done yet - we still have to send the closing boundry tag NSString *endingBoundryStr = [NSString stringWithFormat:@"\r\n--%@--\r\n", ranges_boundry]; NSData *endingBoundryData = [endingBoundryStr dataUsingEncoding:NSUTF8StringEncoding]; [asyncSocket writeData:endingBoundryData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE]; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Responses //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns an array of possible index pages. * For example: {"index.html", "index.htm"} **/ - (NSArray *)directoryIndexFileNames { HTTPLogTrace(); // Override me to support other index pages. return [NSArray arrayWithObjects:@"index.html", @"index.htm", nil]; } - (NSString *)filePathForURI:(NSString *)path { return [self filePathForURI:path allowDirectory:NO]; } /** * Converts relative URI path into full file-system path. **/ - (NSString *)filePathForURI:(NSString *)path allowDirectory:(BOOL)allowDirectory { HTTPLogTrace(); // Override me to perform custom path mapping. // For example you may want to use a default file other than index.html, or perhaps support multiple types. NSString *documentRoot = [config documentRoot]; // Part 0: Validate document root setting. // // If there is no configured documentRoot, // then it makes no sense to try to return anything. if (documentRoot == nil) { HTTPLogWarn(@"%@[%p]: No configured document root", THIS_FILE, self); return nil; } // Part 1: Strip parameters from the url // // E.g.: /page.html?q=22&var=abc -> /page.html NSURL *docRoot = [NSURL fileURLWithPath:documentRoot isDirectory:YES]; if (docRoot == nil) { HTTPLogWarn(@"%@[%p]: Document root is invalid file path", THIS_FILE, self); return nil; } NSString *relativePath = [[NSURL URLWithString:path relativeToURL:docRoot] relativePath]; // Part 2: Append relative path to document root (base path) // // E.g.: relativePath="/images/icon.png" // documentRoot="/Users/robbie/Sites" // fullPath="/Users/robbie/Sites/images/icon.png" // // We also standardize the path. // // E.g.: "Users/robbie/Sites/images/../index.html" -> "/Users/robbie/Sites/index.html" NSString *fullPath = [[documentRoot stringByAppendingPathComponent:relativePath] stringByStandardizingPath]; if ([relativePath isEqualToString:@"/"]) { fullPath = [fullPath stringByAppendingString:@"/"]; } // Part 3: Prevent serving files outside the document root. // // Sneaky requests may include ".." in the path. // // E.g.: relativePath="../Documents/TopSecret.doc" // documentRoot="/Users/robbie/Sites" // fullPath="/Users/robbie/Documents/TopSecret.doc" // // E.g.: relativePath="../Sites_Secret/TopSecret.doc" // documentRoot="/Users/robbie/Sites" // fullPath="/Users/robbie/Sites_Secret/TopSecret" if (![documentRoot hasSuffix:@"/"]) { documentRoot = [documentRoot stringByAppendingString:@"/"]; } if (![fullPath hasPrefix:documentRoot]) { HTTPLogWarn(@"%@[%p]: Request for file outside document root", THIS_FILE, self); return nil; } // Part 4: Search for index page if path is pointing to a directory if (!allowDirectory) { BOOL isDir = NO; if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) { NSArray *indexFileNames = [self directoryIndexFileNames]; for (NSString *indexFileName in indexFileNames) { NSString *indexFilePath = [fullPath stringByAppendingPathComponent:indexFileName]; if ([[NSFileManager defaultManager] fileExistsAtPath:indexFilePath isDirectory:&isDir] && !isDir) { return indexFilePath; } } // No matching index files found in directory return nil; } } return fullPath; } /** * This method is called to get a response for a request. * You may return any object that adopts the HTTPResponse protocol. * The HTTPServer comes with two such classes: HTTPFileResponse and HTTPDataResponse. * HTTPFileResponse is a wrapper for an NSFileHandle object, and is the preferred way to send a file response. * HTTPDataResponse is a wrapper for an NSData object, and may be used to send a custom response. **/ - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path { HTTPLogTrace(); // Override me to provide custom responses. NSString *filePath = [self filePathForURI:path allowDirectory:NO]; BOOL isDir = NO; if (filePath && [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir] && !isDir) { return [[[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self] autorelease]; // Use me instead for asynchronous file IO. // Generally better for larger files. // return [[[HTTPAsyncFileResponse alloc] initWithFilePath:filePath forConnection:self] autorelease]; } return nil; } - (WebSocket *)webSocketForURI:(NSString *)path { HTTPLogTrace(); // Override me to provide custom WebSocket responses. // To do so, simply override the base WebSocket implementation, and add your custom functionality. // Then return an instance of your custom WebSocket here. // // For example: // // if ([path isEqualToString:@"/myAwesomeWebSocketStream"]) // { // return [[[MyWebSocket alloc] initWithRequest:request socket:asyncSocket] autorelease]; // } // // return [super webSocketForURI:path]; return nil; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Uploads //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method is called after receiving all HTTP headers, but before reading any of the request body. **/ - (void)prepareForBodyWithSize:(UInt64)contentLength { // Override me to allocate buffers, file handles, etc. } /** * This method is called to handle data read from a POST / PUT. * The given data is part of the request body. **/ - (void)processBodyData:(NSData *)postDataChunk { // Override me to do something useful with a POST / PUT. // If the post is small, such as a simple form, you may want to simply append the data to the request. // If the post is big, such as a file upload, you may want to store the file to disk. // // Remember: In order to support LARGE POST uploads, the data is read in chunks. // This prevents a 50 MB upload from being stored in RAM. // The size of the chunks are limited by the POST_CHUNKSIZE definition. // Therefore, this method may be called multiple times for the same POST request. } /** * This method is called after the request body has been fully read but before the HTTP request is processed. **/ - (void)finishBody { // Override me to perform any final operations on an upload. // For example, if you were saving the upload to disk this would be // the hook to flush any pending data to disk and maybe close the file. } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Errors //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Called if the HTML version is other than what is supported **/ - (void)handleVersionNotSupported:(NSString *)version { // Override me for custom error handling of unsupported http version responses // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method. // You can also use preprocessErrorResponse: to add an optional HTML body. HTTPLogWarn(@"HTTP Server: Error 505 - Version Not Supported: %@ (%@)", version, [self requestURI]); HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:505 description:nil version:HTTPVersion1_1]; [response setHeaderField:@"Content-Length" value:@"0"]; NSData *responseData = [self preprocessErrorResponse:response]; [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_RESPONSE]; [response release]; } /** * Called if the authentication information was required and absent, or if authentication failed. **/ - (void)handleAuthenticationFailed { // Override me for custom handling of authentication challenges // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method. // You can also use preprocessErrorResponse: to add an optional HTML body. HTTPLogInfo(@"HTTP Server: Error 401 - Unauthorized (%@)", [self requestURI]); // Status Code 401 - Unauthorized HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:401 description:nil version:HTTPVersion1_1]; [response setHeaderField:@"Content-Length" value:@"0"]; if ([self useDigestAccessAuthentication]) { [self addDigestAuthChallenge:response]; } else { [self addBasicAuthChallenge:response]; } NSData *responseData = [self preprocessErrorResponse:response]; [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_RESPONSE]; [response release]; } /** * Called if we receive some sort of malformed HTTP request. * The data parameter is the invalid HTTP header line, including CRLF, as read from GCDAsyncSocket. * The data parameter may also be nil if the request as a whole was invalid, such as a POST with no Content-Length. **/ - (void)handleInvalidRequest:(NSData *)data { // Override me for custom error handling of invalid HTTP requests // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method. // You can also use preprocessErrorResponse: to add an optional HTML body. HTTPLogWarn(@"HTTP Server: Error 400 - Bad Request (%@)", [self requestURI]); // Status Code 400 - Bad Request HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:400 description:nil version:HTTPVersion1_1]; [response setHeaderField:@"Content-Length" value:@"0"]; [response setHeaderField:@"Connection" value:@"close"]; NSData *responseData = [self preprocessErrorResponse:response]; [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_FINAL_RESPONSE]; [response release]; // Note: We used the HTTP_FINAL_RESPONSE tag to disconnect after the response is sent. // We do this because we couldn't parse the request, // so we won't be able to recover and move on to another request afterwards. // In other words, we wouldn't know where the first request ends and the second request begins. } /** * Called if we receive a HTTP request with a method other than GET or HEAD. **/ - (void)handleUnknownMethod:(NSString *)method { // Override me for custom error handling of 405 method not allowed responses. // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method. // You can also use preprocessErrorResponse: to add an optional HTML body. // // See also: supportsMethod:atPath: HTTPLogWarn(@"HTTP Server: Error 405 - Method Not Allowed: %@ (%@)", method, [self requestURI]); // Status code 405 - Method Not Allowed HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:405 description:nil version:HTTPVersion1_1]; [response setHeaderField:@"Content-Length" value:@"0"]; [response setHeaderField:@"Connection" value:@"close"]; NSData *responseData = [self preprocessErrorResponse:response]; [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_FINAL_RESPONSE]; [response release]; // Note: We used the HTTP_FINAL_RESPONSE tag to disconnect after the response is sent. // We do this because the method may include an http body. // Since we can't be sure, we should close the connection. } /** * Called if we're unable to find the requested resource. **/ - (void)handleResourceNotFound { // Override me for custom error handling of 404 not found responses // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method. // You can also use preprocessErrorResponse: to add an optional HTML body. HTTPLogInfo(@"HTTP Server: Error 404 - Not Found (%@)", [self requestURI]); // Status Code 404 - Not Found HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:404 description:nil version:HTTPVersion1_1]; [response setHeaderField:@"Content-Length" value:@"0"]; NSData *responseData = [self preprocessErrorResponse:response]; [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_RESPONSE]; [response release]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Headers //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Gets the current date and time, formatted properly (according to RFC) for insertion into an HTTP header. **/ - (NSString *)dateAsString:(NSDate *)date { // From Apple's Documentation (Data Formatting Guide -> Date Formatters -> Cache Formatters for Efficiency): // // "Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, // it is typically more efficient to cache a single instance than to create and dispose of multiple instances. // One approach is to use a static variable." // // This was discovered to be true in massive form via issue #46: // // "Was doing some performance benchmarking using instruments and httperf. Using this single optimization // I got a 26% speed improvement - from 1000req/sec to 3800req/sec. Not insignificant. // The culprit? Why, NSDateFormatter, of course!" // // Thus, we are using a static NSDateFormatter here. static NSDateFormatter *df; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ // Example: Sun, 06 Nov 1994 08:49:37 GMT df = [[NSDateFormatter alloc] init]; [df setFormatterBehavior:NSDateFormatterBehavior10_4]; [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; [df setDateFormat:@"EEE, dd MMM y HH:mm:ss 'GMT'"]; [df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]]; // For some reason, using zzz in the format string produces GMT+00:00 }); return [df stringFromDate:date]; } /** * This method is called immediately prior to sending the response headers. * This method adds standard header fields, and then converts the response to an NSData object. **/ - (NSData *)preprocessResponse:(HTTPMessage *)response { HTTPLogTrace(); // Override me to customize the response headers // You'll likely want to add your own custom headers, and then return [super preprocessResponse:response] // Add standard headers NSString *now = [self dateAsString:[NSDate date]]; [response setHeaderField:@"Date" value:now]; // Add server capability headers [response setHeaderField:@"Accept-Ranges" value:@"bytes"]; // Add optional response headers if ([httpResponse respondsToSelector:@selector(httpHeaders)]) { NSDictionary *responseHeaders = [httpResponse httpHeaders]; NSEnumerator *keyEnumerator = [responseHeaders keyEnumerator]; NSString *key; while ((key = [keyEnumerator nextObject])) { NSString *value = [responseHeaders objectForKey:key]; [response setHeaderField:key value:value]; } } return [response messageData]; } /** * This method is called immediately prior to sending the response headers (for an error). * This method adds standard header fields, and then converts the response to an NSData object. **/ - (NSData *)preprocessErrorResponse:(HTTPMessage *)response; { HTTPLogTrace(); // Override me to customize the error response headers // You'll likely want to add your own custom headers, and then return [super preprocessErrorResponse:response] // // Notes: // You can use [response statusCode] to get the type of error. // You can use [response setBody:data] to add an optional HTML body. // If you add a body, don't forget to update the Content-Length. // // if ([response statusCode] == 404) // { // NSString *msg = @"<html><body>Error 404 - Not Found</body></html>"; // NSData *msgData = [msg dataUsingEncoding:NSUTF8StringEncoding]; // // [response setBody:msgData]; // // NSString *contentLengthStr = [NSString stringWithFormat:@"%lu", (unsigned long)[msgData length]]; // [response setHeaderField:@"Content-Length" value:contentLengthStr]; // } // Add standard headers NSString *now = [self dateAsString:[NSDate date]]; [response setHeaderField:@"Date" value:now]; // Add server capability headers [response setHeaderField:@"Accept-Ranges" value:@"bytes"]; // Add optional response headers if ([httpResponse respondsToSelector:@selector(httpHeaders)]) { NSDictionary *responseHeaders = [httpResponse httpHeaders]; NSEnumerator *keyEnumerator = [responseHeaders keyEnumerator]; NSString *key; while((key = [keyEnumerator nextObject])) { NSString *value = [responseHeaders objectForKey:key]; [response setHeaderField:key value:value]; } } return [response messageData]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark GCDAsyncSocket Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method is called after the socket has successfully read data from the stream. * Remember that this method will only be called after the socket reaches a CRLF, or after it's read the proper length. **/ - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData*)data withTag:(long)tag { if (tag == HTTP_REQUEST_HEADER) { // Append the header line to the http message BOOL result = [request appendData:data]; if (!result) { HTTPLogWarn(@"%@[%p]: Malformed request", THIS_FILE, self); [self handleInvalidRequest:data]; } else if (![request isHeaderComplete]) { // We don't have a complete header yet // That is, we haven't yet received a CRLF on a line by itself, indicating the end of the header if (++numHeaderLines > MAX_HEADER_LINES) { // Reached the maximum amount of header lines in a single HTTP request // This could be an attempted DOS attack [asyncSocket disconnect]; // Explictly return to ensure we don't do anything after the socket disconnect return; } else { [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:TIMEOUT_READ_SUBSEQUENT_HEADER_LINE maxLength:MAX_HEADER_LINE_LENGTH tag:HTTP_REQUEST_HEADER]; } } else { // We have an entire HTTP request header from the client // Extract the method (such as GET, HEAD, POST, etc) NSString *method = [request method]; // Extract the uri (such as "/index.html") NSString *uri = [self requestURI]; // Check for a Transfer-Encoding field NSString *transferEncoding = [request headerField:@"Transfer-Encoding"]; // Check for a Content-Length field NSString *contentLength = [request headerField:@"Content-Length"]; // Content-Length MUST be present for upload methods (such as POST or PUT) // and MUST NOT be present for other methods. BOOL expectsUpload = [self expectsRequestBodyFromMethod:method atPath:uri]; if (expectsUpload) { if (transferEncoding && ![transferEncoding caseInsensitiveCompare:@"Chunked"]) { requestContentLength = -1; } else { if (contentLength == nil) { HTTPLogWarn(@"%@[%p]: Method expects request body, but had no specified Content-Length", THIS_FILE, self); [self handleInvalidRequest:nil]; return; } if (![NSNumber parseString:(NSString *)contentLength intoUInt64:&requestContentLength]) { HTTPLogWarn(@"%@[%p]: Unable to parse Content-Length header into a valid number", THIS_FILE, self); [self handleInvalidRequest:nil]; return; } } } else { if (contentLength != nil) { // Received Content-Length header for method not expecting an upload. // This better be zero... if (![NSNumber parseString:(NSString *)contentLength intoUInt64:&requestContentLength]) { HTTPLogWarn(@"%@[%p]: Unable to parse Content-Length header into a valid number", THIS_FILE, self); [self handleInvalidRequest:nil]; return; } if (requestContentLength > 0) { HTTPLogWarn(@"%@[%p]: Method not expecting request body had non-zero Content-Length", THIS_FILE, self); [self handleInvalidRequest:nil]; return; } } requestContentLength = 0; requestContentLengthReceived = 0; } // Check to make sure the given method is supported if (![self supportsMethod:method atPath:uri]) { // The method is unsupported - either in general, or for this specific request // Send a 405 - Method not allowed response [self handleUnknownMethod:method]; return; } if (expectsUpload) { // Reset the total amount of data received for the upload requestContentLengthReceived = 0; // Prepare for the upload [self prepareForBodyWithSize:requestContentLength]; if (requestContentLength > 0) { // Start reading the request body if (requestContentLength == -1) { // Chunked transfer [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:TIMEOUT_READ_BODY maxLength:MAX_CHUNK_LINE_LENGTH tag:HTTP_REQUEST_CHUNK_SIZE]; } else { NSUInteger bytesToRead; if (requestContentLength < POST_CHUNKSIZE) bytesToRead = (NSUInteger)requestContentLength; else bytesToRead = POST_CHUNKSIZE; [asyncSocket readDataToLength:bytesToRead withTimeout:TIMEOUT_READ_BODY tag:HTTP_REQUEST_BODY]; } } else { // Empty upload [self finishBody]; [self replyToHTTPRequest]; } } else { // Now we need to reply to the request [self replyToHTTPRequest]; } } } else { BOOL doneReadingRequest = NO; // A chunked message body contains a series of chunks, // followed by a line with "0" (zero), // followed by optional footers (just like headers), // and a blank line. // // Each chunk consists of two parts: // // 1. A line with the size of the chunk data, in hex, // possibly followed by a semicolon and extra parameters you can ignore (none are currently standard), // and ending with CRLF. // 2. The data itself, followed by CRLF. // // Part 1 is represented by HTTP_REQUEST_CHUNK_SIZE // Part 2 is represented by HTTP_REQUEST_CHUNK_DATA and HTTP_REQUEST_CHUNK_TRAILER // where the trailer is the CRLF that follows the data. // // The optional footers and blank line are represented by HTTP_REQUEST_CHUNK_FOOTER. if (tag == HTTP_REQUEST_CHUNK_SIZE) { // We have just read in a line with the size of the chunk data, in hex, // possibly followed by a semicolon and extra parameters that can be ignored, // and ending with CRLF. NSString *sizeLine = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; requestChunkSize = (UInt64)strtoull([sizeLine UTF8String], NULL, 16); requestChunkSizeReceived = 0; if (errno != 0) { HTTPLogWarn(@"%@[%p]: Method expects chunk size, but received something else", THIS_FILE, self); [self handleInvalidRequest:nil]; return; } if (requestChunkSize > 0) { NSUInteger bytesToRead; bytesToRead = (requestChunkSize < POST_CHUNKSIZE) ? (NSUInteger)requestChunkSize : POST_CHUNKSIZE; [asyncSocket readDataToLength:bytesToRead withTimeout:TIMEOUT_READ_BODY tag:HTTP_REQUEST_CHUNK_DATA]; } else { // This is the "0" (zero) line, // which is to be followed by optional footers (just like headers) and finally a blank line. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:TIMEOUT_READ_BODY maxLength:MAX_HEADER_LINE_LENGTH tag:HTTP_REQUEST_CHUNK_FOOTER]; } return; } else if (tag == HTTP_REQUEST_CHUNK_DATA) { // We just read part of the actual data. requestContentLengthReceived += [data length]; requestChunkSizeReceived += [data length]; [self processBodyData:data]; UInt64 bytesLeft = requestChunkSize - requestChunkSizeReceived; if (bytesLeft > 0) { NSUInteger bytesToRead = (bytesLeft < POST_CHUNKSIZE) ? (NSUInteger)bytesLeft : POST_CHUNKSIZE; [asyncSocket readDataToLength:bytesToRead withTimeout:TIMEOUT_READ_BODY tag:HTTP_REQUEST_CHUNK_DATA]; } else { // We've read in all the data for this chunk. // The data is followed by a CRLF, which we need to read (and basically ignore) [asyncSocket readDataToLength:2 withTimeout:TIMEOUT_READ_BODY tag:HTTP_REQUEST_CHUNK_TRAILER]; } return; } else if (tag == HTTP_REQUEST_CHUNK_TRAILER) { // This should be the CRLF following the data. // Just ensure it's a CRLF. if (![data isEqualToData:[GCDAsyncSocket CRLFData]]) { HTTPLogWarn(@"%@[%p]: Method expects chunk trailer, but is missing", THIS_FILE, self); [self handleInvalidRequest:nil]; return; } // Now continue with the next chunk [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:TIMEOUT_READ_BODY maxLength:MAX_CHUNK_LINE_LENGTH tag:HTTP_REQUEST_CHUNK_SIZE]; } else if (tag == HTTP_REQUEST_CHUNK_FOOTER) { if (++numHeaderLines > MAX_HEADER_LINES) { // Reached the maximum amount of header lines in a single HTTP request // This could be an attempted DOS attack [asyncSocket disconnect]; // Explictly return to ensure we don't do anything after the socket disconnect return; } if ([data length] > 2) { // We read in a footer. // In the future we may want to append these to the request. // For now we ignore, and continue reading the footers, waiting for the final blank line. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:TIMEOUT_READ_BODY maxLength:MAX_HEADER_LINE_LENGTH tag:HTTP_REQUEST_CHUNK_FOOTER]; } else { doneReadingRequest = YES; } } else // HTTP_REQUEST_BODY { // Handle a chunk of data from the POST body requestContentLengthReceived += [data length]; [self processBodyData:data]; if (requestContentLengthReceived < requestContentLength) { // We're not done reading the post body yet... UInt64 bytesLeft = requestContentLength - requestContentLengthReceived; NSUInteger bytesToRead = bytesLeft < POST_CHUNKSIZE ? (NSUInteger)bytesLeft : POST_CHUNKSIZE; [asyncSocket readDataToLength:bytesToRead withTimeout:TIMEOUT_READ_BODY tag:HTTP_REQUEST_BODY]; } else { doneReadingRequest = YES; } } // Now that the entire body has been received, we need to reply to the request if (doneReadingRequest) { [self finishBody]; [self replyToHTTPRequest]; } } } /** * This method is called after the socket has successfully written data to the stream. **/ - (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag { BOOL doneSendingResponse = NO; if (tag == HTTP_PARTIAL_RESPONSE_BODY) { // Update the amount of data we have in asyncSocket's write queue [responseDataSizes removeObjectAtIndex:0]; // We only wrote a part of the response - there may be more [self continueSendingStandardResponseBody]; } else if (tag == HTTP_CHUNKED_RESPONSE_BODY) { // Update the amount of data we have in asyncSocket's write queue. // This will allow asynchronous responses to continue sending more data. [responseDataSizes removeObjectAtIndex:0]; // Don't continue sending the response yet. // The chunked footer that was sent after the body will tell us if we have more data to send. } else if (tag == HTTP_CHUNKED_RESPONSE_FOOTER) { // Normal chunked footer indicating we have more data to send (non final footer). [self continueSendingStandardResponseBody]; } else if (tag == HTTP_PARTIAL_RANGE_RESPONSE_BODY) { // Update the amount of data we have in asyncSocket's write queue [responseDataSizes removeObjectAtIndex:0]; // We only wrote a part of the range - there may be more [self continueSendingSingleRangeResponseBody]; } else if (tag == HTTP_PARTIAL_RANGES_RESPONSE_BODY) { // Update the amount of data we have in asyncSocket's write queue [responseDataSizes removeObjectAtIndex:0]; // We only wrote part of the range - there may be more, or there may be more ranges [self continueSendingMultiRangeResponseBody]; } else if (tag == HTTP_RESPONSE || tag == HTTP_FINAL_RESPONSE) { // Update the amount of data we have in asyncSocket's write queue if ([responseDataSizes count] > 0) { [responseDataSizes removeObjectAtIndex:0]; } doneSendingResponse = YES; } if (doneSendingResponse) { // Inform the http response that we're done if ([httpResponse respondsToSelector:@selector(connectionDidClose)]) { [httpResponse connectionDidClose]; } // Cleanup after the last request [self finishResponse]; if (tag == HTTP_FINAL_RESPONSE) { // Terminate the connection [asyncSocket disconnect]; // Explictly return to ensure we don't do anything after the socket disconnect return; } else { if ([self shouldDie]) { // The only time we should invoke [self die] is from socketDidDisconnect, // or if the socket gets taken over by someone else like a WebSocket. [asyncSocket disconnect]; } else { // Prepare for the next request // If this assertion fails, it likely means you overrode the // finishBody method and forgot to call [super finishBody]. NSAssert(request == nil, @"Request not properly released in finishBody"); request = [[HTTPMessage alloc] initEmptyRequest]; numHeaderLines = 0; sentResponseHeaders = NO; // And start listening for more requests [self startReadingRequest]; } } } } /** * Sent after the socket has been disconnected. **/ - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err; { HTTPLogTrace(); [asyncSocket release]; asyncSocket = nil; [self die]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark HTTPResponse Notifications //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method may be called by asynchronous HTTPResponse objects. * That is, HTTPResponse objects that return YES in their "- (BOOL)isAsynchronous" method. * * This informs us that the response object has generated more data that we may be able to send. **/ - (void)responseHasAvailableData:(NSObject<HTTPResponse> *)sender { HTTPLogTrace(); // We always dispatch this asynchronously onto our connectionQueue, // even if the connectionQueue is the current queue. // // We do this to give the HTTPResponse classes the flexibility to call // this method whenever they want, even from within a readDataOfLength method. dispatch_async(connectionQueue, ^{ if (sender != httpResponse) { HTTPLogWarn(@"%@[%p]: %@ - Sender is not current httpResponse", THIS_FILE, self, THIS_METHOD); return; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (!sentResponseHeaders) { [self sendResponseHeadersAndBody]; } else { if (ranges == nil) { [self continueSendingStandardResponseBody]; } else { if ([ranges count] == 1) [self continueSendingSingleRangeResponseBody]; else [self continueSendingMultiRangeResponseBody]; } } [pool drain]; }); } /** * This method is called if the response encounters some critical error, * and it will be unable to fullfill the request. **/ - (void)responseDidAbort:(NSObject<HTTPResponse> *)sender { HTTPLogTrace(); // We always dispatch this asynchronously onto our connectionQueue, // even if the connectionQueue is the current queue. // // We do this to give the HTTPResponse classes the flexibility to call // this method whenever they want, even from within a readDataOfLength method. dispatch_async(connectionQueue, ^{ if (sender != httpResponse) { HTTPLogWarn(@"%@[%p]: %@ - Sender is not current httpResponse", THIS_FILE, self, THIS_METHOD); return; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [asyncSocket disconnectAfterWriting]; [pool drain]; }); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Post Request //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method is called after each response has been fully sent. * Since a single connection may handle multiple request/responses, this method may be called multiple times. * That is, it will be called after completion of each response. **/ - (void)finishResponse { HTTPLogTrace(); // Override me if you want to perform any custom actions after a response has been fully sent. // This is the place to release memory or resources associated with the last request. // // If you override this method, you should take care to invoke [super finishResponse] at some point. [request release]; request = nil; [httpResponse release]; httpResponse = nil; [ranges release]; [ranges_headers release]; [ranges_boundry release]; ranges = nil; ranges_headers = nil; ranges_boundry = nil; } /** * This method is called after each successful response has been fully sent. * It determines whether the connection should stay open and handle another request. **/ - (BOOL)shouldDie { HTTPLogTrace(); // Override me if you have any need to force close the connection. // You may do so by simply returning YES. // // If you override this method, you should take care to fall through with [super shouldDie] // instead of returning NO. BOOL shouldDie = NO; NSString *version = [request version]; if ([version isEqualToString:HTTPVersion1_1]) { // HTTP version 1.1 // Connection should only be closed if request included "Connection: close" header NSString *connection = [request headerField:@"Connection"]; shouldDie = (connection && ([connection caseInsensitiveCompare:@"close"] == NSOrderedSame)); } else if ([version isEqualToString:HTTPVersion1_0]) { // HTTP version 1.0 // Connection should be closed unless request included "Connection: Keep-Alive" header NSString *connection = [request headerField:@"Connection"]; if (connection == nil) shouldDie = YES; else shouldDie = [connection caseInsensitiveCompare:@"Keep-Alive"] != NSOrderedSame; } return shouldDie; } - (void)die { HTTPLogTrace(); // Override me if you want to perform any custom actions when a connection is closed. // Then call [super die] when you're done. // // See also the finishResponse method. // // Important: There is a rare timing condition where this method might get invoked twice. // If you override this method, you should be prepared for this situation. // Inform the http response that we're done if ([httpResponse respondsToSelector:@selector(connectionDidClose)]) { [httpResponse connectionDidClose]; } // Release the http response so we don't call it's connectionDidClose method again in our dealloc method [httpResponse release]; httpResponse = nil; // Post notification of dead connection // This will allow our server to release us from its array of connections [[NSNotificationCenter defaultCenter] postNotificationName:HTTPConnectionDidDieNotification object:self]; } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation HTTPConfig @synthesize server; @synthesize documentRoot; @synthesize queue; - (id)initWithServer:(HTTPServer *)aServer documentRoot:(NSString *)aDocumentRoot { if ((self = [super init])) { server = [aServer retain]; documentRoot = [aDocumentRoot retain]; } return self; } - (id)initWithServer:(HTTPServer *)aServer documentRoot:(NSString *)aDocumentRoot queue:(dispatch_queue_t)q { if ((self = [super init])) { server = [aServer retain]; documentRoot = [aDocumentRoot stringByStandardizingPath]; if ([documentRoot hasSuffix:@"/"]) { documentRoot = [documentRoot stringByAppendingString:@"/"]; } [documentRoot retain]; if (q) { dispatch_retain(q); queue = q; } } return self; } - (void)dealloc { [server release]; [documentRoot release]; if (queue) dispatch_release(queue); [super dealloc]; } @end
007xsq-sadsad
Core/HTTPConnection.m
Objective-C
bsd
87,256
#import <Foundation/Foundation.h> @class GCDAsyncSocket; @class HTTPMessage; @class HTTPServer; @class WebSocket; @protocol HTTPResponse; #define HTTPConnectionDidDieNotification @"HTTPConnectionDidDie" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @interface HTTPConfig : NSObject { HTTPServer *server; NSString *documentRoot; dispatch_queue_t queue; } - (id)initWithServer:(HTTPServer *)server documentRoot:(NSString *)documentRoot; - (id)initWithServer:(HTTPServer *)server documentRoot:(NSString *)documentRoot queue:(dispatch_queue_t)q; @property (nonatomic, readonly) HTTPServer *server; @property (nonatomic, readonly) NSString *documentRoot; @property (nonatomic, readonly) dispatch_queue_t queue; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @interface HTTPConnection : NSObject { dispatch_queue_t connectionQueue; GCDAsyncSocket *asyncSocket; HTTPConfig *config; BOOL started; HTTPMessage *request; unsigned int numHeaderLines; BOOL sentResponseHeaders; NSString *nonce; long lastNC; NSObject<HTTPResponse> *httpResponse; NSMutableArray *ranges; NSMutableArray *ranges_headers; NSString *ranges_boundry; int rangeIndex; UInt64 requestContentLength; UInt64 requestContentLengthReceived; UInt64 requestChunkSize; UInt64 requestChunkSizeReceived; NSMutableArray *responseDataSizes; } - (id)initWithAsyncSocket:(GCDAsyncSocket *)newSocket configuration:(HTTPConfig *)aConfig; - (void)start; - (void)stop; - (void)startConnection; - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path; - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path; - (BOOL)isSecureServer; - (NSArray *)sslIdentityAndCertificates; - (BOOL)isPasswordProtected:(NSString *)path; - (BOOL)useDigestAccessAuthentication; - (NSString *)realm; - (NSString *)passwordForUser:(NSString *)username; - (NSDictionary *)parseParams:(NSString *)query; - (NSDictionary *)parseGetParams; - (NSString *)requestURI; - (NSArray *)directoryIndexFileNames; - (NSString *)filePathForURI:(NSString *)path; - (NSString *)filePathForURI:(NSString *)path allowDirectory:(BOOL)allowDirectory; - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path; - (WebSocket *)webSocketForURI:(NSString *)path; - (void)prepareForBodyWithSize:(UInt64)contentLength; - (void)processBodyData:(NSData *)postDataChunk; - (void)finishBody; - (void)handleVersionNotSupported:(NSString *)version; - (void)handleAuthenticationFailed; - (void)handleResourceNotFound; - (void)handleInvalidRequest:(NSData *)data; - (void)handleUnknownMethod:(NSString *)method; - (NSData *)preprocessResponse:(HTTPMessage *)response; - (NSData *)preprocessErrorResponse:(HTTPMessage *)response; - (void)finishResponse; - (BOOL)shouldDie; - (void)die; @end @interface HTTPConnection (AsynchronousHTTPResponse) - (void)responseHasAvailableData:(NSObject<HTTPResponse> *)sender; - (void)responseDidAbort:(NSObject<HTTPResponse> *)sender; @end
007xsq-sadsad
Core/HTTPConnection.h
Objective-C
bsd
3,419
#import <Foundation/Foundation.h> @interface NSData (DDData) - (NSData *)md5Digest; - (NSData *)sha1Digest; - (NSString *)hexStringValue; - (NSString *)base64Encoded; - (NSData *)base64Decoded; @end
007xsq-sadsad
Core/Categories/DDData.h
Objective-C
bsd
205
#import "DDRange.h" #import "DDNumber.h" DDRange DDUnionRange(DDRange range1, DDRange range2) { DDRange result; result.location = MIN(range1.location, range2.location); result.length = MAX(DDMaxRange(range1), DDMaxRange(range2)) - result.location; return result; } DDRange DDIntersectionRange(DDRange range1, DDRange range2) { DDRange result; if((DDMaxRange(range1) < range2.location) || (DDMaxRange(range2) < range1.location)) { return DDMakeRange(0, 0); } result.location = MAX(range1.location, range2.location); result.length = MIN(DDMaxRange(range1), DDMaxRange(range2)) - result.location; return result; } NSString *DDStringFromRange(DDRange range) { return [NSString stringWithFormat:@"{%qu, %qu}", range.location, range.length]; } DDRange DDRangeFromString(NSString *aString) { DDRange result = DDMakeRange(0, 0); // NSRange will ignore '-' characters, but not '+' characters NSCharacterSet *cset = [NSCharacterSet characterSetWithCharactersInString:@"+0123456789"]; NSScanner *scanner = [NSScanner scannerWithString:aString]; [scanner setCharactersToBeSkipped:[cset invertedSet]]; NSString *str1 = nil; NSString *str2 = nil; BOOL found1 = [scanner scanCharactersFromSet:cset intoString:&str1]; BOOL found2 = [scanner scanCharactersFromSet:cset intoString:&str2]; if(found1) [NSNumber parseString:str1 intoUInt64:&result.location]; if(found2) [NSNumber parseString:str2 intoUInt64:&result.length]; return result; } NSInteger DDRangeCompare(DDRangePointer pDDRange1, DDRangePointer pDDRange2) { // Comparison basis: // Which range would you encouter first if you started at zero, and began walking towards infinity. // If you encouter both ranges at the same time, which range would end first. if(pDDRange1->location < pDDRange2->location) { return NSOrderedAscending; } if(pDDRange1->location > pDDRange2->location) { return NSOrderedDescending; } if(pDDRange1->length < pDDRange2->length) { return NSOrderedAscending; } if(pDDRange1->length > pDDRange2->length) { return NSOrderedDescending; } return NSOrderedSame; } @implementation NSValue (NSValueDDRangeExtensions) + (NSValue *)valueWithDDRange:(DDRange)range { return [NSValue valueWithBytes:&range objCType:@encode(DDRange)]; } - (DDRange)ddrangeValue { DDRange result; [self getValue:&result]; return result; } - (NSInteger)ddrangeCompare:(NSValue *)other { DDRange r1 = [self ddrangeValue]; DDRange r2 = [other ddrangeValue]; return DDRangeCompare(&r1, &r2); } @end
007xsq-sadsad
Core/Categories/DDRange.m
Objective-C
bsd
2,531
#import <Foundation/Foundation.h> @interface NSNumber (DDNumber) + (BOOL)parseString:(NSString *)str intoSInt64:(SInt64 *)pNum; + (BOOL)parseString:(NSString *)str intoUInt64:(UInt64 *)pNum; + (BOOL)parseString:(NSString *)str intoNSInteger:(NSInteger *)pNum; + (BOOL)parseString:(NSString *)str intoNSUInteger:(NSUInteger *)pNum; @end
007xsq-sadsad
Core/Categories/DDNumber.h
Objective-C
bsd
341
/** * DDRange is the functional equivalent of a 64 bit NSRange. * The HTTP Server is designed to support very large files. * On 32 bit architectures (ppc, i386) NSRange uses unsigned 32 bit integers. * This only supports a range of up to 4 gigabytes. * By defining our own variant, we can support a range up to 16 exabytes. * * All effort is given such that DDRange functions EXACTLY the same as NSRange. **/ #import <Foundation/NSValue.h> #import <Foundation/NSObjCRuntime.h> @class NSString; typedef struct _DDRange { UInt64 location; UInt64 length; } DDRange; typedef DDRange *DDRangePointer; NS_INLINE DDRange DDMakeRange(UInt64 loc, UInt64 len) { DDRange r; r.location = loc; r.length = len; return r; } NS_INLINE UInt64 DDMaxRange(DDRange range) { return (range.location + range.length); } NS_INLINE BOOL DDLocationInRange(UInt64 loc, DDRange range) { return (loc - range.location < range.length); } NS_INLINE BOOL DDEqualRanges(DDRange range1, DDRange range2) { return ((range1.location == range2.location) && (range1.length == range2.length)); } FOUNDATION_EXPORT DDRange DDUnionRange(DDRange range1, DDRange range2); FOUNDATION_EXPORT DDRange DDIntersectionRange(DDRange range1, DDRange range2); FOUNDATION_EXPORT NSString *DDStringFromRange(DDRange range); FOUNDATION_EXPORT DDRange DDRangeFromString(NSString *aString); NSInteger DDRangeCompare(DDRangePointer pDDRange1, DDRangePointer pDDRange2); @interface NSValue (NSValueDDRangeExtensions) + (NSValue *)valueWithDDRange:(DDRange)range; - (DDRange)ddrangeValue; - (NSInteger)ddrangeCompare:(NSValue *)ddrangeValue; @end
007xsq-sadsad
Core/Categories/DDRange.h
Objective-C
bsd
1,642
#import "DDNumber.h" @implementation NSNumber (DDNumber) + (BOOL)parseString:(NSString *)str intoSInt64:(SInt64 *)pNum { if(str == nil) { *pNum = 0; return NO; } errno = 0; // On both 32-bit and 64-bit machines, long long = 64 bit *pNum = strtoll([str UTF8String], NULL, 10); if(errno != 0) return NO; else return YES; } + (BOOL)parseString:(NSString *)str intoUInt64:(UInt64 *)pNum { if(str == nil) { *pNum = 0; return NO; } errno = 0; // On both 32-bit and 64-bit machines, unsigned long long = 64 bit *pNum = strtoull([str UTF8String], NULL, 10); if(errno != 0) return NO; else return YES; } + (BOOL)parseString:(NSString *)str intoNSInteger:(NSInteger *)pNum { if(str == nil) { *pNum = 0; return NO; } errno = 0; // On LP64, NSInteger = long = 64 bit // Otherwise, NSInteger = int = long = 32 bit *pNum = strtol([str UTF8String], NULL, 10); if(errno != 0) return NO; else return YES; } + (BOOL)parseString:(NSString *)str intoNSUInteger:(NSUInteger *)pNum { if(str == nil) { *pNum = 0; return NO; } errno = 0; // On LP64, NSUInteger = unsigned long = 64 bit // Otherwise, NSUInteger = unsigned int = unsigned long = 32 bit *pNum = strtoul([str UTF8String], NULL, 10); if(errno != 0) return NO; else return YES; } @end
007xsq-sadsad
Core/Categories/DDNumber.m
Objective-C
bsd
1,327
#import "DDData.h" #import <CommonCrypto/CommonDigest.h> @implementation NSData (DDData) static char encodingTable[64] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' }; - (NSData *)md5Digest { unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5([self bytes], (CC_LONG)[self length], result); return [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH]; } - (NSData *)sha1Digest { unsigned char result[CC_SHA1_DIGEST_LENGTH]; CC_SHA1([self bytes], (CC_LONG)[self length], result); return [NSData dataWithBytes:result length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)hexStringValue { NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:([self length] * 2)]; const unsigned char *dataBuffer = [self bytes]; int i; for (i = 0; i < [self length]; ++i) { [stringBuffer appendFormat:@"%02x", (unsigned long)dataBuffer[i]]; } return [[stringBuffer copy] autorelease]; } - (NSString *)base64Encoded { const unsigned char *bytes = [self bytes]; NSMutableString *result = [NSMutableString stringWithCapacity:[self length]]; unsigned long ixtext = 0; unsigned long lentext = [self length]; long ctremaining = 0; unsigned char inbuf[3], outbuf[4]; unsigned short i = 0; unsigned short charsonline = 0, ctcopy = 0; unsigned long ix = 0; while( YES ) { ctremaining = lentext - ixtext; if( ctremaining <= 0 ) break; for( i = 0; i < 3; i++ ) { ix = ixtext + i; if( ix < lentext ) inbuf[i] = bytes[ix]; else inbuf [i] = 0; } outbuf [0] = (inbuf [0] & 0xFC) >> 2; outbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4); outbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6); outbuf [3] = inbuf [2] & 0x3F; ctcopy = 4; switch( ctremaining ) { case 1: ctcopy = 2; break; case 2: ctcopy = 3; break; } for( i = 0; i < ctcopy; i++ ) [result appendFormat:@"%c", encodingTable[outbuf[i]]]; for( i = ctcopy; i < 4; i++ ) [result appendString:@"="]; ixtext += 3; charsonline += 4; } return [NSString stringWithString:result]; } - (NSData *)base64Decoded { const unsigned char *bytes = [self bytes]; NSMutableData *result = [NSMutableData dataWithCapacity:[self length]]; unsigned long ixtext = 0; unsigned long lentext = [self length]; unsigned char ch = 0; unsigned char inbuf[4], outbuf[3]; short i = 0, ixinbuf = 0; BOOL flignore = NO; BOOL flendtext = NO; while( YES ) { if( ixtext >= lentext ) break; ch = bytes[ixtext++]; flignore = NO; if( ( ch >= 'A' ) && ( ch <= 'Z' ) ) ch = ch - 'A'; else if( ( ch >= 'a' ) && ( ch <= 'z' ) ) ch = ch - 'a' + 26; else if( ( ch >= '0' ) && ( ch <= '9' ) ) ch = ch - '0' + 52; else if( ch == '+' ) ch = 62; else if( ch == '=' ) flendtext = YES; else if( ch == '/' ) ch = 63; else flignore = YES; if( ! flignore ) { short ctcharsinbuf = 3; BOOL flbreak = NO; if( flendtext ) { if( ! ixinbuf ) break; if( ( ixinbuf == 1 ) || ( ixinbuf == 2 ) ) ctcharsinbuf = 1; else ctcharsinbuf = 2; ixinbuf = 3; flbreak = YES; } inbuf [ixinbuf++] = ch; if( ixinbuf == 4 ) { ixinbuf = 0; outbuf [0] = ( inbuf[0] << 2 ) | ( ( inbuf[1] & 0x30) >> 4 ); outbuf [1] = ( ( inbuf[1] & 0x0F ) << 4 ) | ( ( inbuf[2] & 0x3C ) >> 2 ); outbuf [2] = ( ( inbuf[2] & 0x03 ) << 6 ) | ( inbuf[3] & 0x3F ); for( i = 0; i < ctcharsinbuf; i++ ) [result appendBytes:&outbuf[i] length:1]; } if( flbreak ) break; } } return [NSData dataWithData:result]; } @end
007xsq-sadsad
Core/Categories/DDData.m
Objective-C
bsd
3,819
#import "HTTPRedirectResponse.h" #import "HTTPLogging.h" // Log levels : off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_OFF; // | HTTP_LOG_FLAG_TRACE; @implementation HTTPRedirectResponse - (id)initWithPath:(NSString *)path { if ((self = [super init])) { HTTPLogTrace(); redirectPath = [path copy]; } return self; } - (UInt64)contentLength { return 0; } - (UInt64)offset { return 0; } - (void)setOffset:(UInt64)offset { // Nothing to do } - (NSData *)readDataOfLength:(NSUInteger)length { HTTPLogTrace(); return nil; } - (BOOL)isDone { return YES; } - (NSDictionary *)httpHeaders { HTTPLogTrace(); return [NSDictionary dictionaryWithObject:redirectPath forKey:@"Location"]; } - (NSInteger)status { HTTPLogTrace(); return 302; } - (void)dealloc { HTTPLogTrace(); [redirectPath release]; [super dealloc]; } @end
007xsq-sadsad
Core/Responses/HTTPRedirectResponse.m
Objective-C
bsd
909
#import <Foundation/Foundation.h> #import "HTTPResponse.h" @class HTTPConnection; /** * This is an asynchronous version of HTTPFileResponse. * It reads data from the given file asynchronously via GCD. * * It may be overriden to allow custom post-processing of the data that has been read from the file. * An example of this is the HTTPDynamicFileResponse class. **/ @interface HTTPAsyncFileResponse : NSObject <HTTPResponse> { HTTPConnection *connection; NSString *filePath; UInt64 fileLength; UInt64 fileOffset; // File offset as pertains to data given to connection UInt64 readOffset; // File offset as pertains to data read from file (but maybe not returned to connection) BOOL aborted; NSData *data; int fileFD; void *readBuffer; NSUInteger readBufferSize; // Malloced size of readBuffer NSUInteger readBufferOffset; // Offset within readBuffer where the end of existing data is NSUInteger readRequestLength; dispatch_queue_t readQueue; dispatch_source_t readSource; BOOL readSourceSuspended; } - (id)initWithFilePath:(NSString *)filePath forConnection:(HTTPConnection *)connection; - (NSString *)filePath; @end /** * Explanation of Variables (excluding those that are obvious) * * fileOffset * This is the number of bytes that have been returned to the connection via the readDataOfLength method. * If 1KB of data has been read from the file, but none of that data has yet been returned to the connection, * then the fileOffset variable remains at zero. * This variable is used in the calculation of the isDone method. * Only after all data has been returned to the connection are we actually done. * * readOffset * Represents the offset of the file descriptor. * In other words, the file position indidcator for our read stream. * It might be easy to think of it as the total number of bytes that have been read from the file. * However, this isn't entirely accurate, as the setOffset: method may have caused us to * jump ahead in the file (lseek). * * readBuffer * Malloc'd buffer to hold data read from the file. * * readBufferSize * Total allocation size of malloc'd buffer. * * readBufferOffset * Represents the position in the readBuffer where we should store new bytes. * * readRequestLength * The total number of bytes that were requested from the connection. * It's OK if we return a lesser number of bytes to the connection. * It's NOT OK if we return a greater number of bytes to the connection. * Doing so would disrupt proper support for range requests. * If, however, the response is chunked then we don't need to worry about this. * Chunked responses inheritly don't support range requests. **/
007xsq-sadsad
Core/Responses/HTTPAsyncFileResponse.h
Objective-C
bsd
2,734
#import <Foundation/Foundation.h> #import "HTTPResponse.h" @interface HTTPRedirectResponse : NSObject <HTTPResponse> { NSString *redirectPath; } - (id)initWithPath:(NSString *)redirectPath; @end
007xsq-sadsad
Core/Responses/HTTPRedirectResponse.h
Objective-C
bsd
200
#import "HTTPDynamicFileResponse.h" #import "HTTPConnection.h" #import "HTTPLogging.h" // Log levels : off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; #define NULL_FD -1 @implementation HTTPDynamicFileResponse - (id)initWithFilePath:(NSString *)fpath forConnection:(HTTPConnection *)parent separator:(NSString *)separatorStr replacementDictionary:(NSDictionary *)dict { if ((self = [super initWithFilePath:fpath forConnection:parent])) { HTTPLogTrace(); separator = [[separatorStr dataUsingEncoding:NSUTF8StringEncoding] retain]; replacementDict = [dict retain]; } return self; } - (BOOL)isChunked { HTTPLogTrace(); return YES; } - (UInt64)contentLength { // This method shouldn't be called since we're using a chunked response. // We override it just to be safe. HTTPLogTrace(); return 0; } - (void)setOffset:(UInt64)offset { // This method shouldn't be called since we're using a chunked response. // We override it just to be safe. HTTPLogTrace(); } - (BOOL)isDone { BOOL result = (readOffset == fileLength) && (readBufferOffset == 0); HTTPLogTrace2(@"%@[%p]: isDone - %@", THIS_FILE, self, (result ? @"YES" : @"NO")); return result; } - (void)processReadBuffer { HTTPLogTrace(); // At this point, the readBuffer has readBufferOffset bytes available. // This method is in charge of updating the readBufferOffset. NSUInteger bufLen = readBufferOffset; NSUInteger sepLen = [separator length]; // We're going to start looking for the separator at the beginning of the buffer, // and stop when we get to the point where the separator would no longer fit in the buffer. NSUInteger offset = 0; NSUInteger stopOffset = (bufLen > sepLen) ? bufLen - sepLen + 1 : 0; // In order to do the replacement, we need to find the starting and ending separator. // For example: // // %%USER_NAME%% // // Where "%%" is the separator. BOOL found1 = NO; BOOL found2 = NO; NSUInteger s1 = 0; NSUInteger s2 = 0; const void *sep = [separator bytes]; while (offset < stopOffset) { const void *subBuffer = readBuffer + offset; if (memcmp(subBuffer, sep, sepLen) == 0) { if (!found1) { // Found the first separator found1 = YES; s1 = offset; offset += sepLen; HTTPLogVerbose(@"%@[%p]: Found s1 at %lu", THIS_FILE, self, (unsigned long)s1); } else { // Found the second separator found2 = YES; s2 = offset; offset += sepLen; HTTPLogVerbose(@"%@[%p]: Found s2 at %lu", THIS_FILE, self, (unsigned long)s2); } if (found1 && found2) { // We found our separators. // Now extract the string between the two separators. NSRange fullRange = NSMakeRange(s1, (s2 - s1 + sepLen)); NSRange strRange = NSMakeRange(s1 + sepLen, (s2 - s1 - sepLen)); // Wish we could use the simple subdataWithRange method. // But that method copies the bytes... // So for performance reasons, we need to use the methods that don't copy the bytes. void *strBuf = readBuffer + strRange.location; NSUInteger strLen = strRange.length; NSString *key = [[NSString alloc] initWithBytes:strBuf length:strLen encoding:NSUTF8StringEncoding]; if (key) { // Is there a given replacement for this key? id value = [replacementDict objectForKey:key]; if (value) { // Found the replacement value. // Now perform the replacement in the buffer. HTTPLogVerbose(@"%@[%p]: key(%@) -> value(%@)", THIS_FILE, self, key, value); NSData *v = [[value description] dataUsingEncoding:NSUTF8StringEncoding]; NSUInteger vLength = [v length]; if (fullRange.length == vLength) { // Replacement is exactly the same size as what it is replacing // memcpy(void *restrict dst, const void *restrict src, size_t n); memcpy(readBuffer + fullRange.location, [v bytes], vLength); } else // (fullRange.length != vLength) { NSInteger diff = (NSInteger)vLength - (NSInteger)fullRange.length; if (diff > 0) { // Replacement is bigger than what it is replacing. // Make sure there is room in the buffer for the replacement. if (diff > (readBufferSize - bufLen)) { NSUInteger inc = MAX(diff, 256); readBufferSize += inc; readBuffer = reallocf(readBuffer, readBufferSize); } } // Move the data that comes after the replacement. // // If replacement is smaller than what it is replacing, // then we are shifting the data toward the beginning of the buffer. // // If replacement is bigger than what it is replacing, // then we are shifting the data toward the end of the buffer. // // memmove(void *dst, const void *src, size_t n); // // The memmove() function copies n bytes from src to dst. // The two areas may overlap; the copy is always done in a non-destructive manner. void *src = readBuffer + fullRange.location + fullRange.length; void *dst = readBuffer + fullRange.location + vLength; NSUInteger remaining = bufLen - (fullRange.location + fullRange.length); memmove(dst, src, remaining); // Now copy the replacement into its location. // // memcpy(void *restrict dst, const void *restrict src, size_t n) // // The memcpy() function copies n bytes from src to dst. // If the two areas overlap, behavior is undefined. memcpy(readBuffer + fullRange.location, [v bytes], vLength); // And don't forget to update our indices. bufLen += diff; offset += diff; stopOffset += diff; } } [key release]; } found1 = found2 = NO; } } else { offset++; } } // We've gone through our buffer now, and performed all the replacements that we could. // It's now time to update the amount of available data we have. if (readOffset == fileLength) { // We've read in the entire file. // So there can be no more replacements. data = [[NSData alloc] initWithBytes:readBuffer length:bufLen]; readBufferOffset = 0; } else { // There are a couple different situations that we need to take into account here. // // Imagine the following file: // My name is %%USER_NAME%% // // Situation 1: // The first chunk of data we read was "My name is %%". // So we found the first separator, but not the second. // In this case we can only return the data that precedes the first separator. // // Situation 2: // The first chunk of data we read was "My name is %". // So we didn't find any separators, but part of a separator may be included in our buffer. NSUInteger available; if (found1) { // Situation 1 available = s1; } else { // Situation 2 available = stopOffset; } // Copy available data data = [[NSData alloc] initWithBytes:readBuffer length:available]; // Remove the copied data from the buffer. // We do this by shifting the remaining data toward the beginning of the buffer. NSUInteger remaining = bufLen - available; memmove(readBuffer, readBuffer + available, remaining); readBufferOffset = remaining; } [connection responseHasAvailableData:self]; } - (void)dealloc { HTTPLogTrace(); [separator release]; [replacementDict release]; [super dealloc]; } @end
007xsq-sadsad
Core/Responses/HTTPDynamicFileResponse.m
Objective-C
bsd
7,702
#import <Foundation/Foundation.h> #import "HTTPResponse.h" #import "HTTPAsyncFileResponse.h" /** * This class is designed to assist with dynamic content. * Imagine you have a file that you want to make dynamic: * * <html> * <body> * <h1>ComputerName Control Panel</h1> * ... * <li>System Time: SysTime</li> * </body> * </html> * * Now you could generate the entire file in Objective-C, * but this would be a horribly tedious process. * Beside, you want to design the file with professional tools to make it look pretty. * * So all you have to do is escape your dynamic content like this: * * ... * <h1>%%ComputerName%% Control Panel</h1> * ... * <li>System Time: %%SysTime%%</li> * * And then you create an instance of this class with: * * - separator = @"%%" * - replacementDictionary = { "ComputerName"="Black MacBook", "SysTime"="2010-04-30 03:18:24" } * * This class will then perform the replacements for you, on the fly, as it reads the file data. * This class is also asynchronous, so it will perform the file IO using its own GCD queue. * * All keys for the replacementDictionary must be NSString's. * Values for the replacementDictionary may be NSString's, or any object that * returns what you want when its description method is invoked. **/ @interface HTTPDynamicFileResponse : HTTPAsyncFileResponse { NSData *separator; NSDictionary *replacementDict; } - (id)initWithFilePath:(NSString *)filePath forConnection:(HTTPConnection *)connection separator:(NSString *)separatorStr replacementDictionary:(NSDictionary *)dictionary; @end
007xsq-sadsad
Core/Responses/HTTPDynamicFileResponse.h
Objective-C
bsd
1,623
#import "HTTPDataResponse.h" #import "HTTPLogging.h" // Log levels : off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_OFF; // | HTTP_LOG_FLAG_TRACE; @implementation HTTPDataResponse - (id)initWithData:(NSData *)dataParam { if((self = [super init])) { HTTPLogTrace(); offset = 0; data = [dataParam retain]; } return self; } - (void)dealloc { HTTPLogTrace(); [data release]; [super dealloc]; } - (UInt64)contentLength { UInt64 result = (UInt64)[data length]; HTTPLogTrace2(@"%@[%p]: contentLength - %llu", THIS_FILE, self, result); return result; } - (UInt64)offset { HTTPLogTrace(); return offset; } - (void)setOffset:(UInt64)offsetParam { HTTPLogTrace2(@"%@[%p]: setOffset:%llu", THIS_FILE, self, offset); offset = (NSUInteger)offsetParam; } - (NSData *)readDataOfLength:(NSUInteger)lengthParameter { HTTPLogTrace2(@"%@[%p]: readDataOfLength:%lu", THIS_FILE, self, (unsigned long)lengthParameter); NSUInteger remaining = [data length] - offset; NSUInteger length = lengthParameter < remaining ? lengthParameter : remaining; void *bytes = (void *)([data bytes] + offset); offset += length; return [NSData dataWithBytesNoCopy:bytes length:length freeWhenDone:NO]; } - (BOOL)isDone { BOOL result = (offset == [data length]); HTTPLogTrace2(@"%@[%p]: isDone - %@", THIS_FILE, self, (result ? @"YES" : @"NO")); return result; } @end
007xsq-sadsad
Core/Responses/HTTPDataResponse.m
Objective-C
bsd
1,444
#import <Foundation/Foundation.h> #import "HTTPResponse.h" @interface HTTPDataResponse : NSObject <HTTPResponse> { NSUInteger offset; NSData *data; } - (id)initWithData:(NSData *)data; @end
007xsq-sadsad
Core/Responses/HTTPDataResponse.h
Objective-C
bsd
196
#import "HTTPFileResponse.h" #import "HTTPConnection.h" #import "HTTPLogging.h" #import <unistd.h> #import <fcntl.h> // Log levels : off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; #define NULL_FD -1 @implementation HTTPFileResponse - (id)initWithFilePath:(NSString *)fpath forConnection:(HTTPConnection *)parent { if((self = [super init])) { HTTPLogTrace(); connection = parent; // Parents retain children, children do NOT retain parents fileFD = NULL_FD; filePath = [fpath copy]; if (filePath == nil) { HTTPLogWarn(@"%@: Init failed - Nil filePath", THIS_FILE); [self release]; return nil; } NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; if (fileAttributes == nil) { HTTPLogWarn(@"%@: Init failed - Unable to get file attributes. filePath: %@", THIS_FILE, filePath); [self release]; return nil; } fileLength = (UInt64)[[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue]; fileOffset = 0; aborted = NO; // We don't bother opening the file here. // If this is a HEAD request we only need to know the fileLength. } return self; } - (void)abort { HTTPLogTrace(); [connection responseDidAbort:self]; aborted = YES; } - (BOOL)openFile { HTTPLogTrace(); fileFD = open([filePath UTF8String], O_RDONLY); if (fileFD == NULL_FD) { HTTPLogError(@"%@[%p]: Unable to open file. filePath: %@", THIS_FILE, self, filePath); [self abort]; return NO; } HTTPLogVerbose(@"%@[%p]: Open fd[%i] -> %@", THIS_FILE, self, fileFD, filePath); return YES; } - (BOOL)openFileIfNeeded { if (aborted) { // The file operation has been aborted. // This could be because we failed to open the file, // or the reading process failed. return NO; } if (fileFD != NULL_FD) { // File has already been opened. return YES; } return [self openFile]; } - (UInt64)contentLength { HTTPLogTrace(); return fileLength; } - (UInt64)offset { HTTPLogTrace(); return fileOffset; } - (void)setOffset:(UInt64)offset { HTTPLogTrace2(@"%@[%p]: setOffset:%llu", THIS_FILE, self, offset); if (![self openFileIfNeeded]) { // File opening failed, // or response has been aborted due to another error. return; } fileOffset = offset; off_t result = lseek(fileFD, (off_t)offset, SEEK_SET); if (result == -1) { HTTPLogError(@"%@[%p]: lseek failed - errno(%i) filePath(%@)", THIS_FILE, self, errno, filePath); [self abort]; } } - (NSData *)readDataOfLength:(NSUInteger)length { HTTPLogTrace2(@"%@[%p]: readDataOfLength:%lu", THIS_FILE, self, (unsigned long)length); if (![self openFileIfNeeded]) { // File opening failed, // or response has been aborted due to another error. return nil; } // Determine how much data we should read. // // It is OK if we ask to read more bytes than exist in the file. // It is NOT OK to over-allocate the buffer. UInt64 bytesLeftInFile = fileLength - fileOffset; NSUInteger bytesToRead = (NSUInteger)MIN(length, bytesLeftInFile); // Make sure buffer is big enough for read request. // Do not over-allocate. if (buffer == NULL || bufferSize < bytesToRead) { bufferSize = bytesToRead; buffer = reallocf(buffer, (size_t)bufferSize); if (buffer == NULL) { HTTPLogError(@"%@[%p]: Unable to allocate buffer", THIS_FILE, self); [self abort]; return nil; } } // Perform the read HTTPLogVerbose(@"%@[%p]: Attempting to read %lu bytes from file", THIS_FILE, self, bytesToRead); ssize_t result = read(fileFD, buffer, bytesToRead); // Check the results if (result < 0) { HTTPLogError(@"%@: Error(%i) reading file(%@)", THIS_FILE, errno, filePath); [self abort]; return nil; } else if (result == 0) { HTTPLogError(@"%@: Read EOF on file(%@)", THIS_FILE, filePath); [self abort]; return nil; } else // (result > 0) { HTTPLogVerbose(@"%@[%p]: Read %d bytes from file", THIS_FILE, self, result); fileOffset += result; return [NSData dataWithBytes:buffer length:result]; } } - (BOOL)isDone { BOOL result = (fileOffset == fileLength); HTTPLogTrace2(@"%@[%p]: isDone - %@", THIS_FILE, self, (result ? @"YES" : @"NO")); return result; } - (NSString *)filePath { return filePath; } - (void)dealloc { HTTPLogTrace(); if (fileFD != NULL_FD) { HTTPLogVerbose(@"%@[%p]: Close fd[%i]", THIS_FILE, self, fileFD); close(fileFD); } if (buffer) free(buffer); [filePath release]; [super dealloc]; } @end
007xsq-sadsad
Core/Responses/HTTPFileResponse.m
Objective-C
bsd
4,627
#import "HTTPAsyncFileResponse.h" #import "HTTPConnection.h" #import "HTTPLogging.h" #import <unistd.h> #import <fcntl.h> // Log levels : off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; #define NULL_FD -1 /** * Architecure overview: * * HTTPConnection will invoke our readDataOfLength: method to fetch data. * We will return nil, and then proceed to read the data via our readSource on our readQueue. * Once the requested amount of data has been read, we then pause our readSource, * and inform the connection of the available data. * * While our read is in progress, we don't have to worry about the connection calling any other methods, * except the connectionDidClose method, which would be invoked if the remote end closed the socket connection. * To safely handle this, we do a synchronous dispatch on the readQueue, * and nilify the connection as well as cancel our readSource. * * In order to minimize resource consumption during a HEAD request, * we don't open the file until we have to (until the connection starts requesting data). **/ @implementation HTTPAsyncFileResponse - (id)initWithFilePath:(NSString *)fpath forConnection:(HTTPConnection *)parent { if ((self = [super init])) { HTTPLogTrace(); connection = parent; // Parents retain children, children do NOT retain parents fileFD = NULL_FD; filePath = [fpath copy]; if (filePath == nil) { HTTPLogWarn(@"%@: Init failed - Nil filePath", THIS_FILE); [self release]; return nil; } NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL]; if (fileAttributes == nil) { HTTPLogWarn(@"%@: Init failed - Unable to get file attributes. filePath: %@", THIS_FILE, filePath); [self release]; return nil; } fileLength = (UInt64)[[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue]; fileOffset = 0; aborted = NO; // We don't bother opening the file here. // If this is a HEAD request we only need to know the fileLength. } return self; } - (void)abort { HTTPLogTrace(); [connection responseDidAbort:self]; aborted = YES; } - (void)processReadBuffer { // This method is here to allow superclasses to perform post-processing of the data. // For an example, see the HTTPDynamicFileResponse class. // // At this point, the readBuffer has readBufferOffset bytes available. // This method is in charge of updating the readBufferOffset. // Failure to do so will cause the readBuffer to grow to fileLength. (Imagine a 1 GB file...) // Copy the data out of the temporary readBuffer. data = [[NSData alloc] initWithBytes:readBuffer length:readBufferOffset]; // Reset the read buffer. readBufferOffset = 0; // Notify the connection that we have data available for it. [connection responseHasAvailableData:self]; } - (void)pauseReadSource { if (!readSourceSuspended) { HTTPLogVerbose(@"%@[%p]: Suspending readSource", THIS_FILE, self); readSourceSuspended = YES; dispatch_suspend(readSource); } } - (void)resumeReadSource { if (readSourceSuspended) { HTTPLogVerbose(@"%@[%p]: Resuming readSource", THIS_FILE, self); readSourceSuspended = NO; dispatch_resume(readSource); } } - (void)cancelReadSource { HTTPLogVerbose(@"%@[%p]: Canceling readSource", THIS_FILE, self); dispatch_source_cancel(readSource); // Cancelling a dispatch source doesn't // invoke the cancel handler if the dispatch source is paused. if (readSourceSuspended) { readSourceSuspended = NO; dispatch_resume(readSource); } } - (BOOL)openFileAndSetupReadSource { HTTPLogTrace(); fileFD = open([filePath UTF8String], (O_RDONLY | O_NONBLOCK)); if (fileFD == NULL_FD) { HTTPLogError(@"%@: Unable to open file. filePath: %@", THIS_FILE, filePath); return NO; } HTTPLogVerbose(@"%@[%p]: Open fd[%i] -> %@", THIS_FILE, self, fileFD, filePath); readQueue = dispatch_queue_create("HTTPAsyncFileResponse", NULL); readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fileFD, 0, readQueue); dispatch_source_set_event_handler(readSource, ^{ HTTPLogTrace2(@"%@: eventBlock - fd[%i]", THIS_FILE, fileFD); // Determine how much data we should read. // // It is OK if we ask to read more bytes than exist in the file. // It is NOT OK to over-allocate the buffer. unsigned long long _bytesAvailableOnFD = dispatch_source_get_data(readSource); UInt64 _bytesLeftInFile = fileLength - readOffset; NSUInteger bytesAvailableOnFD; NSUInteger bytesLeftInFile; bytesAvailableOnFD = (_bytesAvailableOnFD > NSUIntegerMax) ? NSUIntegerMax : (NSUInteger)_bytesAvailableOnFD; bytesLeftInFile = (_bytesLeftInFile > NSUIntegerMax) ? NSUIntegerMax : (NSUInteger)_bytesLeftInFile; NSUInteger bytesLeftInRequest = readRequestLength - readBufferOffset; NSUInteger bytesLeft = MIN(bytesLeftInRequest, bytesLeftInFile); NSUInteger bytesToRead = MIN(bytesAvailableOnFD, bytesLeft); // Make sure buffer is big enough for read request. // Do not over-allocate. if (readBuffer == NULL || bytesToRead > (readBufferSize - readBufferOffset)) { readBufferSize = bytesToRead; readBuffer = reallocf(readBuffer, (size_t)bytesToRead); if (readBuffer == NULL) { HTTPLogError(@"%@[%p]: Unable to allocate buffer", THIS_FILE, self); [self pauseReadSource]; [self abort]; return; } } // Perform the read HTTPLogVerbose(@"%@[%p]: Attempting to read %lu bytes from file", THIS_FILE, self, bytesToRead); ssize_t result = read(fileFD, readBuffer + readBufferOffset, (size_t)bytesToRead); // Check the results if (result < 0) { HTTPLogError(@"%@: Error(%i) reading file(%@)", THIS_FILE, errno, filePath); [self pauseReadSource]; [self abort]; } else if (result == 0) { HTTPLogError(@"%@: Read EOF on file(%@)", THIS_FILE, filePath); [self pauseReadSource]; [self abort]; } else // (result > 0) { HTTPLogVerbose(@"%@[%p]: Read %d bytes from file", THIS_FILE, self, result); readOffset += result; readBufferOffset += result; [self pauseReadSource]; [self processReadBuffer]; } }); int theFileFD = fileFD; dispatch_source_t theReadSource = readSource; dispatch_source_set_cancel_handler(readSource, ^{ // Do not access self from within this block in any way, shape or form. // // Note: You access self if you reference an iVar. HTTPLogTrace2(@"%@: cancelBlock - Close fd[%i]", THIS_FILE, theFileFD); dispatch_release(theReadSource); close(theFileFD); }); readSourceSuspended = YES; return YES; } - (BOOL)openFileIfNeeded { if (aborted) { // The file operation has been aborted. // This could be because we failed to open the file, // or the reading process failed. return NO; } if (fileFD != NULL_FD) { // File has already been opened. return YES; } return [self openFileAndSetupReadSource]; } - (UInt64)contentLength { HTTPLogTrace2(@"%@[%p]: contentLength - %llu", THIS_FILE, self, fileLength); return fileLength; } - (UInt64)offset { HTTPLogTrace(); return fileOffset; } - (void)setOffset:(UInt64)offset { HTTPLogTrace2(@"%@[%p]: setOffset:%llu", THIS_FILE, self, offset); if (![self openFileIfNeeded]) { // File opening failed, // or response has been aborted due to another error. return; } fileOffset = offset; readOffset = offset; off_t result = lseek(fileFD, (off_t)offset, SEEK_SET); if (result == -1) { HTTPLogError(@"%@[%p]: lseek failed - errno(%i) filePath(%@)", THIS_FILE, self, errno, filePath); [self abort]; } } - (NSData *)readDataOfLength:(NSUInteger)length { HTTPLogTrace2(@"%@[%p]: readDataOfLength:%lu", THIS_FILE, self, (unsigned long)length); if (data) { NSUInteger dataLength = [data length]; HTTPLogVerbose(@"%@[%p]: Returning data of length %lu", THIS_FILE, self, dataLength); fileOffset += dataLength; NSData *result = data; data = nil; return [result autorelease]; } else { if (![self openFileIfNeeded]) { // File opening failed, // or response has been aborted due to another error. return nil; } dispatch_sync(readQueue, ^{ NSAssert(readSourceSuspended, @"Invalid logic - perhaps HTTPConnection has changed."); readRequestLength = length; [self resumeReadSource]; }); return nil; } } - (BOOL)isDone { BOOL result = (fileOffset == fileLength); HTTPLogTrace2(@"%@[%p]: isDone - %@", THIS_FILE, self, (result ? @"YES" : @"NO")); return result; } - (NSString *)filePath { return filePath; } - (BOOL)isAsynchronous { HTTPLogTrace(); return YES; } - (void)connectionDidClose { HTTPLogTrace(); if (fileFD != NULL_FD) { dispatch_sync(readQueue, ^{ // Prevent any further calls to the connection connection = nil; // Cancel the readSource. // We do this here because the readSource's eventBlock has retained self. // In other words, if we don't cancel the readSource, we will never get deallocated. [self cancelReadSource]; }); } } - (void)dealloc { HTTPLogTrace(); if (readQueue) dispatch_release(readQueue); if (readBuffer) free(readBuffer); [filePath release]; [data release]; [super dealloc]; } @end
007xsq-sadsad
Core/Responses/HTTPAsyncFileResponse.m
Objective-C
bsd
9,401
#import <Foundation/Foundation.h> #import "HTTPResponse.h" @class HTTPConnection; @interface HTTPFileResponse : NSObject <HTTPResponse> { HTTPConnection *connection; NSString *filePath; UInt64 fileLength; UInt64 fileOffset; BOOL aborted; int fileFD; void *buffer; NSUInteger bufferSize; } - (id)initWithFilePath:(NSString *)filePath forConnection:(HTTPConnection *)connection; - (NSString *)filePath; @end
007xsq-sadsad
Core/Responses/HTTPFileResponse.h
Objective-C
bsd
425
#import "HTTPServer.h" #import "GCDAsyncSocket.h" #import "HTTPConnection.h" #import "WebSocket.h" #import "HTTPLogging.h" // Log levels: off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_INFO; // | HTTP_LOG_FLAG_TRACE; @interface HTTPServer (PrivateAPI) - (void)unpublishBonjour; - (void)publishBonjour; + (void)startBonjourThreadIfNeeded; + (void)performBonjourBlock:(dispatch_block_t)block; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation HTTPServer /** * Standard Constructor. * Instantiates an HTTP server, but does not start it. **/ - (id)init { if ((self = [super init])) { HTTPLogTrace(); // Initialize underlying dispatch queue and GCD based tcp socket serverQueue = dispatch_queue_create("HTTPServer", NULL); asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:serverQueue]; // Use default connection class of HTTPConnection connectionQueue = dispatch_queue_create("HTTPConnection", NULL); connectionClass = [HTTPConnection self]; // By default bind on all available interfaces, en1, wifi etc interface = nil; // Use a default port of 0 // This will allow the kernel to automatically pick an open port for us port = 0; // Configure default values for bonjour service // Bonjour domain. Use the local domain by default domain = @"local."; // If using an empty string ("") for the service name when registering, // the system will automatically use the "Computer Name". // Passing in an empty string will also handle name conflicts // by automatically appending a digit to the end of the name. name = @""; // Initialize arrays to hold all the HTTP and webSocket connections connections = [[NSMutableArray alloc] init]; webSockets = [[NSMutableArray alloc] init]; connectionsLock = [[NSLock alloc] init]; webSocketsLock = [[NSLock alloc] init]; // Register for notifications of closed connections [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionDidDie:) name:HTTPConnectionDidDieNotification object:nil]; // Register for notifications of closed websocket connections [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(webSocketDidDie:) name:WebSocketDidDieNotification object:nil]; isRunning = NO; } return self; } /** * Standard Deconstructor. * Stops the server, and clients, and releases any resources connected with this instance. **/ - (void)dealloc { HTTPLogTrace(); // Remove notification observer [[NSNotificationCenter defaultCenter] removeObserver:self]; // Stop the server if it's running [self stop]; // Release all instance variables dispatch_release(serverQueue); dispatch_release(connectionQueue); [asyncSocket setDelegate:nil delegateQueue:NULL]; [asyncSocket release]; [documentRoot release]; [interface release]; [netService release]; [domain release]; [name release]; [type release]; [txtRecordDictionary release]; [connections release]; [webSockets release]; [connectionsLock release]; [webSocketsLock release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Server Configuration //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * The document root is filesystem root for the webserver. * Thus requests for /index.html will be referencing the index.html file within the document root directory. * All file requests are relative to this document root. **/ - (NSString *)documentRoot { __block NSString *result; dispatch_sync(serverQueue, ^{ result = [documentRoot retain]; }); return [result autorelease]; } - (void)setDocumentRoot:(NSString *)value { HTTPLogTrace(); // Document root used to be of type NSURL. // Add type checking for early warning to developers upgrading from older versions. if (value && ![value isKindOfClass:[NSString class]]) { HTTPLogWarn(@"%@: %@ - Expecting NSString parameter, received %@ parameter", THIS_FILE, THIS_METHOD, NSStringFromClass([value class])); return; } NSString *valueCopy = [value copy]; dispatch_async(serverQueue, ^{ [documentRoot release]; documentRoot = [valueCopy retain]; }); [valueCopy release]; } /** * The connection class is the class that will be used to handle connections. * That is, when a new connection is created, an instance of this class will be intialized. * The default connection class is HTTPConnection. * If you use a different connection class, it is assumed that the class extends HTTPConnection **/ - (Class)connectionClass { __block Class result; dispatch_sync(serverQueue, ^{ result = connectionClass; }); return result; } - (void)setConnectionClass:(Class)value { HTTPLogTrace(); dispatch_async(serverQueue, ^{ connectionClass = value; }); } /** * What interface to bind the listening socket to. **/ - (NSString *)interface { __block NSString *result; dispatch_sync(serverQueue, ^{ result = [interface retain]; }); return [result autorelease]; } - (void)setInterface:(NSString *)value { NSString *valueCopy = [value copy]; dispatch_async(serverQueue, ^{ [interface release]; interface = [valueCopy retain]; }); [valueCopy release]; } /** * The port to listen for connections on. * By default this port is initially set to zero, which allows the kernel to pick an available port for us. * After the HTTP server has started, the port being used may be obtained by this method. **/ - (UInt16)port { __block UInt16 result; dispatch_sync(serverQueue, ^{ result = port; }); return result; } - (UInt16)listeningPort { __block UInt16 result; dispatch_sync(serverQueue, ^{ if (isRunning) result = [asyncSocket localPort]; else result = 0; }); return result; } - (void)setPort:(UInt16)value { HTTPLogTrace(); dispatch_async(serverQueue, ^{ port = value; }); } /** * Domain on which to broadcast this service via Bonjour. * The default domain is @"local". **/ - (NSString *)domain { __block NSString *result; dispatch_sync(serverQueue, ^{ result = [domain retain]; }); return [domain autorelease]; } - (void)setDomain:(NSString *)value { HTTPLogTrace(); NSString *valueCopy = [value copy]; dispatch_async(serverQueue, ^{ [domain release]; domain = [valueCopy retain]; }); [valueCopy release]; } /** * The name to use for this service via Bonjour. * The default name is an empty string, * which should result in the published name being the host name of the computer. **/ - (NSString *)name { __block NSString *result; dispatch_sync(serverQueue, ^{ result = [name retain]; }); return [name autorelease]; } - (NSString *)publishedName { __block NSString *result; dispatch_sync(serverQueue, ^{ if (netService == nil) { result = nil; } else { dispatch_block_t bonjourBlock = ^{ result = [[netService name] copy]; }; [[self class] performBonjourBlock:bonjourBlock]; } }); return [result autorelease]; } - (void)setName:(NSString *)value { NSString *valueCopy = [value copy]; dispatch_async(serverQueue, ^{ [name release]; name = [valueCopy retain]; }); [valueCopy release]; } /** * The type of service to publish via Bonjour. * No type is set by default, and one must be set in order for the service to be published. **/ - (NSString *)type { __block NSString *result; dispatch_sync(serverQueue, ^{ result = [type retain]; }); return [result autorelease]; } - (void)setType:(NSString *)value { NSString *valueCopy = [value copy]; dispatch_async(serverQueue, ^{ [type release]; type = [valueCopy retain]; }); [valueCopy release]; } /** * The extra data to use for this service via Bonjour. **/ - (NSDictionary *)TXTRecordDictionary { __block NSDictionary *result; dispatch_sync(serverQueue, ^{ result = [txtRecordDictionary retain]; }); return [result autorelease]; } - (void)setTXTRecordDictionary:(NSDictionary *)value { HTTPLogTrace(); NSDictionary *valueCopy = [value copy]; dispatch_async(serverQueue, ^{ [txtRecordDictionary release]; txtRecordDictionary = [valueCopy retain]; // Update the txtRecord of the netService if it has already been published if (netService) { NSNetService *theNetService = netService; NSData *txtRecordData = nil; if (txtRecordDictionary) txtRecordData = [NSNetService dataFromTXTRecordDictionary:txtRecordDictionary]; dispatch_block_t bonjourBlock = ^{ [theNetService setTXTRecordData:txtRecordData]; }; [[self class] performBonjourBlock:bonjourBlock]; } }); [valueCopy release]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Server Control //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)start:(NSError **)errPtr { HTTPLogTrace(); __block BOOL success = YES; __block NSError *err = nil; dispatch_sync(serverQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; success = [asyncSocket acceptOnInterface:interface port:port error:&err]; if (success) { HTTPLogInfo(@"%@: Started HTTP server on port %hu", THIS_FILE, [asyncSocket localPort]); isRunning = YES; [self publishBonjour]; } else { HTTPLogError(@"%@: Failed to start HTTP Server: %@", THIS_FILE, err); [err retain]; } [pool drain]; }); if (errPtr) *errPtr = [err autorelease]; else [err release]; return success; } - (void)stop { [self stop:NO]; } - (void)stop:(BOOL)keepExistingConnections { HTTPLogTrace(); dispatch_sync(serverQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // First stop publishing the service via bonjour [self unpublishBonjour]; // Stop listening / accepting incoming connections [asyncSocket disconnect]; isRunning = NO; if (!keepExistingConnections) { // Stop all HTTP connections the server owns [connectionsLock lock]; for (HTTPConnection *connection in connections) { [connection stop]; } [connections removeAllObjects]; [connectionsLock unlock]; // Stop all WebSocket connections the server owns [webSocketsLock lock]; for (WebSocket *webSocket in webSockets) { [webSocket stop]; } [webSockets removeAllObjects]; [webSocketsLock unlock]; } [pool drain]; }); } - (BOOL)isRunning { __block BOOL result; dispatch_sync(serverQueue, ^{ result = isRunning; }); return result; } - (void)addWebSocket:(WebSocket *)ws { [webSocketsLock lock]; HTTPLogTrace(); [webSockets addObject:ws]; [webSocketsLock unlock]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Server Status //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns the number of http client connections that are currently connected to the server. **/ - (NSUInteger)numberOfHTTPConnections { NSUInteger result = 0; [connectionsLock lock]; result = [connections count]; [connectionsLock unlock]; return result; } /** * Returns the number of websocket client connections that are currently connected to the server. **/ - (NSUInteger)numberOfWebSocketConnections { NSUInteger result = 0; [webSocketsLock lock]; result = [webSockets count]; [webSocketsLock unlock]; return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Incoming Connections //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (HTTPConfig *)config { // Override me if you want to provide a custom config to the new connection. // // Generally this involves overriding the HTTPConfig class to include any custom settings, // and then having this method return an instance of 'MyHTTPConfig'. // Note: Think you can make the server faster by putting each connection on its own queue? // Then benchmark it before and after and discover for yourself the shocking truth! // // Try the apache benchmark tool (already installed on your Mac): // $ ab -n 1000 -c 1 http://localhost:<port>/some_path.html return [[[HTTPConfig alloc] initWithServer:self documentRoot:documentRoot queue:connectionQueue] autorelease]; } - (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket { HTTPConnection *newConnection = (HTTPConnection *)[[connectionClass alloc] initWithAsyncSocket:newSocket configuration:[self config]]; [connectionsLock lock]; [connections addObject:newConnection]; [connectionsLock unlock]; [newConnection start]; [newConnection release]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Bonjour //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)publishBonjour { HTTPLogTrace(); NSAssert(dispatch_get_current_queue() == serverQueue, @"Invalid queue"); if (type) { netService = [[NSNetService alloc] initWithDomain:domain type:type name:name port:[asyncSocket localPort]]; [netService setDelegate:self]; NSNetService *theNetService = netService; NSData *txtRecordData = nil; if (txtRecordDictionary) txtRecordData = [NSNetService dataFromTXTRecordDictionary:txtRecordDictionary]; dispatch_block_t bonjourBlock = ^{ [theNetService removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; [theNetService scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [theNetService publish]; // Do not set the txtRecordDictionary prior to publishing!!! // This will cause the OS to crash!!! if (txtRecordData) { [theNetService setTXTRecordData:txtRecordData]; } }; [[self class] startBonjourThreadIfNeeded]; [[self class] performBonjourBlock:bonjourBlock]; } } - (void)unpublishBonjour { HTTPLogTrace(); NSAssert(dispatch_get_current_queue() == serverQueue, @"Invalid queue"); if (netService) { NSNetService *theNetService = netService; dispatch_block_t bonjourBlock = ^{ [theNetService stop]; [theNetService release]; }; [[self class] performBonjourBlock:bonjourBlock]; netService = nil; } } /** * Republishes the service via bonjour if the server is running. * If the service was not previously published, this method will publish it (if the server is running). **/ - (void)republishBonjour { HTTPLogTrace(); dispatch_async(serverQueue, ^{ [self unpublishBonjour]; [self publishBonjour]; }); } /** * Called when our bonjour service has been successfully published. * This method does nothing but output a log message telling us about the published service. **/ - (void)netServiceDidPublish:(NSNetService *)ns { // Override me to do something here... // // Note: This method is invoked on our bonjour thread. HTTPLogInfo(@"Bonjour Service Published: domain(%@) type(%@) name(%@)", [ns domain], [ns type], [ns name]); } /** * Called if our bonjour service failed to publish itself. * This method does nothing but output a log message telling us about the published service. **/ - (void)netService:(NSNetService *)ns didNotPublish:(NSDictionary *)errorDict { // Override me to do something here... // // Note: This method in invoked on our bonjour thread. HTTPLogWarn(@"Failed to Publish Service: domain(%@) type(%@) name(%@) - %@", [ns domain], [ns type], [ns name], errorDict); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Notifications //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method is automatically called when a notification of type HTTPConnectionDidDieNotification is posted. * It allows us to remove the connection from our array. **/ - (void)connectionDidDie:(NSNotification *)notification { // Note: This method is called on the connection queue that posted the notification [connectionsLock lock]; HTTPLogTrace(); [connections removeObject:[notification object]]; [connectionsLock unlock]; } /** * This method is automatically called when a notification of type WebSocketDidDieNotification is posted. * It allows us to remove the websocket from our array. **/ - (void)webSocketDidDie:(NSNotification *)notification { // Note: This method is called on the connection queue that posted the notification [webSocketsLock lock]; HTTPLogTrace(); [webSockets removeObject:[notification object]]; [webSocketsLock unlock]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Bonjour Thread //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * NSNetService is runloop based, so it requires a thread with a runloop. * This gives us two options: * * - Use the main thread * - Setup our own dedicated thread * * Since we have various blocks of code that need to synchronously access the netservice objects, * using the main thread becomes troublesome and a potential for deadlock. **/ static NSThread *bonjourThread; + (void)startBonjourThreadIfNeeded { HTTPLogTrace(); static dispatch_once_t predicate; dispatch_once(&predicate, ^{ HTTPLogVerbose(@"%@: Starting bonjour thread...", THIS_FILE); bonjourThread = [[NSThread alloc] initWithTarget:self selector:@selector(bonjourThread) object:nil]; [bonjourThread start]; }); } + (void)bonjourThread { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; HTTPLogVerbose(@"%@: BonjourThread: Started", THIS_FILE); // We can't run the run loop unless it has an associated input source or a timer. // So we'll just create a timer that will never fire - unless the server runs for 10,000 years. [NSTimer scheduledTimerWithTimeInterval:DBL_MAX target:self selector:@selector(ignore:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] run]; HTTPLogVerbose(@"%@: BonjourThread: Aborted", THIS_FILE); [pool drain]; } + (void)executeBonjourBlock:(dispatch_block_t)block { HTTPLogTrace(); NSAssert([NSThread currentThread] == bonjourThread, @"Executed on incorrect thread"); block(); } + (void)performBonjourBlock:(dispatch_block_t)block { HTTPLogTrace(); [self performSelector:@selector(executeBonjourBlock:) onThread:bonjourThread withObject:block waitUntilDone:YES]; } @end
007xsq-sadsad
Core/HTTPServer.m
Objective-C
bsd
19,783
#import <Foundation/Foundation.h> #if TARGET_OS_IPHONE // Note: You may need to add the CFNetwork Framework to your project #import <CFNetwork/CFNetwork.h> #endif @class HTTPMessage; @interface HTTPAuthenticationRequest : NSObject { BOOL isBasic; BOOL isDigest; NSString *base64Credentials; NSString *username; NSString *realm; NSString *nonce; NSString *uri; NSString *qop; NSString *nc; NSString *cnonce; NSString *response; } - (id)initWithRequest:(HTTPMessage *)request; - (BOOL)isBasic; - (BOOL)isDigest; // Basic - (NSString *)base64Credentials; // Digest - (NSString *)username; - (NSString *)realm; - (NSString *)nonce; - (NSString *)uri; - (NSString *)qop; - (NSString *)nc; - (NSString *)cnonce; - (NSString *)response; @end
007xsq-sadsad
Core/HTTPAuthenticationRequest.h
Objective-C
bsd
762
#import <Foundation/Foundation.h> @class GCDAsyncSocket; @class WebSocket; #if TARGET_OS_IPHONE #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000 // iPhone 4.0 #define IMPLEMENTED_PROTOCOLS <NSNetServiceDelegate> #else #define IMPLEMENTED_PROTOCOLS #endif #else #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 // Mac OS X 10.6 #define IMPLEMENTED_PROTOCOLS <NSNetServiceDelegate> #else #define IMPLEMENTED_PROTOCOLS #endif #endif @interface HTTPServer : NSObject IMPLEMENTED_PROTOCOLS { // Underlying asynchronous TCP/IP socket dispatch_queue_t serverQueue; dispatch_queue_t connectionQueue; GCDAsyncSocket *asyncSocket; // HTTP server configuration NSString *documentRoot; Class connectionClass; NSString *interface; UInt16 port; // NSNetService and related variables NSNetService *netService; NSString *domain; NSString *type; NSString *name; NSString *publishedName; NSDictionary *txtRecordDictionary; // Connection management NSMutableArray *connections; NSMutableArray *webSockets; NSLock *connectionsLock; NSLock *webSocketsLock; BOOL isRunning; } /** * Specifies the document root to serve files from. * For example, if you set this to "/Users/<your_username>/Sites", * then it will serve files out of the local Sites directory (including subdirectories). * * The default value is nil. * The default server configuration will not serve any files until this is set. * * If you change the documentRoot while the server is running, * the change will affect future incoming http connections. **/ - (NSString *)documentRoot; - (void)setDocumentRoot:(NSString *)value; /** * The connection class is the class used to handle incoming HTTP connections. * * The default value is [HTTPConnection class]. * You can override HTTPConnection, and then set this to [MyHTTPConnection class]. * * If you change the connectionClass while the server is running, * the change will affect future incoming http connections. **/ - (Class)connectionClass; - (void)setConnectionClass:(Class)value; /** * Set what interface you'd like the server to listen on. * By default this is nil, which causes the server to listen on all available interfaces like en1, wifi etc. * * The interface may be specified by name (e.g. "en1" or "lo0") or by IP address (e.g. "192.168.4.34"). * You may also use the special strings "localhost" or "loopback" to specify that * the socket only accept connections from the local machine. **/ - (NSString *)interface; - (void)setInterface:(NSString *)value; /** * The port number to run the HTTP server on. * * The default port number is zero, meaning the server will automatically use any available port. * This is the recommended port value, as it avoids possible port conflicts with other applications. * Technologies such as Bonjour can be used to allow other applications to automatically discover the port number. * * Note: As is common on most OS's, you need root privledges to bind to port numbers below 1024. * * You can change the port property while the server is running, but it won't affect the running server. * To actually change the port the server is listening for connections on you'll need to restart the server. * * The listeningPort method will always return the port number the running server is listening for connections on. * If the server is not running this method returns 0. **/ - (UInt16)port; - (UInt16)listeningPort; - (void)setPort:(UInt16)value; /** * Bonjour domain for publishing the service. * The default value is "local.". * * Note: Bonjour publishing requires you set a type. * * If you change the domain property after the bonjour service has already been published (server already started), * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service. **/ - (NSString *)domain; - (void)setDomain:(NSString *)value; /** * Bonjour name for publishing the service. * The default value is "". * * If using an empty string ("") for the service name when registering, * the system will automatically use the "Computer Name". * Using an empty string will also handle name conflicts * by automatically appending a digit to the end of the name. * * Note: Bonjour publishing requires you set a type. * * If you change the name after the bonjour service has already been published (server already started), * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service. * * The publishedName method will always return the actual name that was published via the bonjour service. * If the service is not running this method returns nil. **/ - (NSString *)name; - (NSString *)publishedName; - (void)setName:(NSString *)value; /** * Bonjour type for publishing the service. * The default value is nil. * The service will not be published via bonjour unless the type is set. * * If you wish to publish the service as a traditional HTTP server, you should set the type to be "_http._tcp.". * * If you change the type after the bonjour service has already been published (server already started), * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service. **/ - (NSString *)type; - (void)setType:(NSString *)value; /** * Republishes the service via bonjour if the server is running. * If the service was not previously published, this method will publish it (if the server is running). **/ - (void)republishBonjour; /** * **/ - (NSDictionary *)TXTRecordDictionary; - (void)setTXTRecordDictionary:(NSDictionary *)dict; /** * Attempts to starts the server on the configured port, interface, etc. * * If an error occurs, this method returns NO and sets the errPtr (if given). * Otherwise returns YES on success. * * Some examples of errors that might occur: * - You specified the server listen on a port which is already in use by another application. * - You specified the server listen on a port number below 1024, which requires root priviledges. * * Code Example: * * NSError *err = nil; * if (![httpServer start:&err]) * { * NSLog(@"Error starting http server: %@", err); * } **/ - (BOOL)start:(NSError **)errPtr; /** * Stops the server, preventing it from accepting any new connections. * You may specify whether or not you want to close the existing client connections. * * The default stop method (with no arguments) will close any existing connections. (It invokes [self stop:NO]) **/ - (void)stop; - (void)stop:(BOOL)keepExistingConnections; - (BOOL)isRunning; - (void)addWebSocket:(WebSocket *)ws; - (NSUInteger)numberOfHTTPConnections; - (NSUInteger)numberOfWebSocketConnections; @end
007xsq-sadsad
Core/HTTPServer.h
Objective-C
bsd
6,709
#import "HTTPMessage.h" @implementation HTTPMessage - (id)initEmptyRequest { if ((self = [super init])) { message = CFHTTPMessageCreateEmpty(NULL, YES); } return self; } - (id)initRequestWithMethod:(NSString *)method URL:(NSURL *)url version:(NSString *)version { if ((self = [super init])) { message = CFHTTPMessageCreateRequest(NULL, (CFStringRef)method, (CFURLRef)url, (CFStringRef)version); } return self; } - (id)initResponseWithStatusCode:(NSInteger)code description:(NSString *)description version:(NSString *)version { if ((self = [super init])) { message = CFHTTPMessageCreateResponse(NULL, (CFIndex)code, (CFStringRef)description, (CFStringRef)version); } return self; } - (void)dealloc { if (message) { CFRelease(message); } [super dealloc]; } - (BOOL)appendData:(NSData *)data { return CFHTTPMessageAppendBytes(message, [data bytes], [data length]); } - (BOOL)isHeaderComplete { return CFHTTPMessageIsHeaderComplete(message); } - (NSString *)version { return [NSMakeCollectable(CFHTTPMessageCopyVersion(message)) autorelease]; } - (NSString *)method { return [NSMakeCollectable(CFHTTPMessageCopyRequestMethod(message)) autorelease]; } - (NSURL *)url { return [NSMakeCollectable(CFHTTPMessageCopyRequestURL(message)) autorelease]; } - (NSInteger)statusCode { return (NSInteger)CFHTTPMessageGetResponseStatusCode(message); } - (NSDictionary *)allHeaderFields { return [NSMakeCollectable(CFHTTPMessageCopyAllHeaderFields(message)) autorelease]; } - (NSString *)headerField:(NSString *)headerField { return [NSMakeCollectable(CFHTTPMessageCopyHeaderFieldValue(message, (CFStringRef)headerField)) autorelease]; } - (void)setHeaderField:(NSString *)headerField value:(NSString *)headerFieldValue { CFHTTPMessageSetHeaderFieldValue(message, (CFStringRef)headerField, (CFStringRef)headerFieldValue); } - (NSData *)messageData { return [NSMakeCollectable(CFHTTPMessageCopySerializedMessage(message)) autorelease]; } - (NSData *)body { return [NSMakeCollectable(CFHTTPMessageCopyBody(message)) autorelease]; } - (void)setBody:(NSData *)body { CFHTTPMessageSetBody(message, (CFDataRef)body); } @end
007xsq-sadsad
Core/HTTPMessage.m
Objective-C
bsd
2,155
#import <Foundation/Foundation.h> @class HTTPMessage; @class GCDAsyncSocket; #define WebSocketDidDieNotification @"WebSocketDidDie" @interface WebSocket : NSObject { dispatch_queue_t websocketQueue; HTTPMessage *request; GCDAsyncSocket *asyncSocket; NSData *term; BOOL isStarted; BOOL isOpen; BOOL isVersion76; id delegate; } + (BOOL)isWebSocketRequest:(HTTPMessage *)request; - (id)initWithRequest:(HTTPMessage *)request socket:(GCDAsyncSocket *)socket; /** * Delegate option. * * In most cases it will be easier to subclass WebSocket, * but some circumstances may lead one to prefer standard delegate callbacks instead. **/ @property (/* atomic */ assign) id delegate; /** * The WebSocket class is thread-safe, generally via it's GCD queue. * All public API methods are thread-safe, * and the subclass API methods are thread-safe as they are all invoked on the same GCD queue. **/ @property (nonatomic, readonly) dispatch_queue_t websocketQueue; /** * Public API * * These methods are automatically called by the HTTPServer. * You may invoke the stop method yourself to close the WebSocket manually. **/ - (void)start; - (void)stop; /** * Public API * * Sends a message over the WebSocket. * This method is thread-safe. **/ - (void)sendMessage:(NSString *)msg; /** * Subclass API * * These methods are designed to be overriden by subclasses. **/ - (void)didOpen; - (void)didReceiveMessage:(NSString *)msg; - (void)didClose; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * There are two ways to create your own custom WebSocket: * * - Subclass it and override the methods you're interested in. * - Use traditional delegate paradigm along with your own custom class. * * They both exist to allow for maximum flexibility. * In most cases it will be easier to subclass WebSocket. * However some circumstances may lead one to prefer standard delegate callbacks instead. * One such example, you're already subclassing another class, so subclassing WebSocket isn't an option. **/ @protocol WebSocketDelegate @optional - (void)webSocketDidOpen:(WebSocket *)ws; - (void)webSocket:(WebSocket *)ws didReceiveMessage:(NSString *)msg; - (void)webSocketDidClose:(WebSocket *)ws; @end
007xsq-sadsad
Core/WebSocket.h
Objective-C
bsd
2,460
/** * The HTTPMessage class is a simple Objective-C wrapper around Apple's CFHTTPMessage class. **/ #import <Foundation/Foundation.h> #if TARGET_OS_IPHONE // Note: You may need to add the CFNetwork Framework to your project #import <CFNetwork/CFNetwork.h> #endif #define HTTPVersion1_0 ((NSString *)kCFHTTPVersion1_0) #define HTTPVersion1_1 ((NSString *)kCFHTTPVersion1_1) @interface HTTPMessage : NSObject { CFHTTPMessageRef message; } - (id)initEmptyRequest; - (id)initRequestWithMethod:(NSString *)method URL:(NSURL *)url version:(NSString *)version; - (id)initResponseWithStatusCode:(NSInteger)code description:(NSString *)description version:(NSString *)version; - (BOOL)appendData:(NSData *)data; - (BOOL)isHeaderComplete; - (NSString *)version; - (NSString *)method; - (NSURL *)url; - (NSInteger)statusCode; - (NSDictionary *)allHeaderFields; - (NSString *)headerField:(NSString *)headerField; - (void)setHeaderField:(NSString *)headerField value:(NSString *)headerFieldValue; - (NSData *)messageData; - (NSData *)body; - (void)setBody:(NSData *)body; @end
007xsq-sadsad
Core/HTTPMessage.h
Objective-C
bsd
1,090
/** * In order to provide fast and flexible logging, this project uses Cocoa Lumberjack. * * The Google Code page has a wealth of documentation if you have any questions. * http://code.google.com/p/cocoalumberjack/ * * Here's what you need to know concerning how logging is setup for CocoaHTTPServer: * * There are 4 log levels: * - Error * - Warning * - Info * - Verbose * * In addition to this, there is a Trace flag that can be enabled. * When tracing is enabled, it spits out the methods that are being called. * * Please note that tracing is separate from the log levels. * For example, one could set the log level to warning, and enable tracing. * * All logging is asynchronous, except errors. * To use logging within your own custom files, follow the steps below. * * Step 1: * Import this header in your implementation file: * * #import "HTTPLogging.h" * * Step 2: * Define your logging level in your implementation file: * * // Log levels: off, error, warn, info, verbose * static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE; * * If you wish to enable tracing, you could do something like this: * * // Debug levels: off, error, warn, info, verbose * static const int httpLogLevel = HTTP_LOG_LEVEL_INFO | HTTP_LOG_FLAG_TRACE; * * Step 3: * Replace your NSLog statements with HTTPLog statements according to the severity of the message. * * NSLog(@"Fatal error, no dohickey found!"); -> HTTPLogError(@"Fatal error, no dohickey found!"); * * HTTPLog works exactly the same as NSLog. * This means you can pass it multiple variables just like NSLog. **/ #import "DDLog.h" // Define logging context for every log message coming from the HTTP server. // The logging context can be extracted from the DDLogMessage from within the logging framework, // which gives loggers, formatters, and filters the ability to optionally process them differently. #define HTTP_LOG_CONTEXT 80 // Configure log levels. #define HTTP_LOG_FLAG_ERROR (1 << 0) // 0...00001 #define HTTP_LOG_FLAG_WARN (1 << 1) // 0...00010 #define HTTP_LOG_FLAG_INFO (1 << 2) // 0...00100 #define HTTP_LOG_FLAG_VERBOSE (1 << 3) // 0...01000 #define HTTP_LOG_LEVEL_OFF 0 // 0...00000 #define HTTP_LOG_LEVEL_ERROR (HTTP_LOG_LEVEL_OFF | HTTP_LOG_FLAG_ERROR) // 0...00001 #define HTTP_LOG_LEVEL_WARN (HTTP_LOG_LEVEL_ERROR | HTTP_LOG_FLAG_WARN) // 0...00011 #define HTTP_LOG_LEVEL_INFO (HTTP_LOG_LEVEL_WARN | HTTP_LOG_FLAG_INFO) // 0...00111 #define HTTP_LOG_LEVEL_VERBOSE (HTTP_LOG_LEVEL_INFO | HTTP_LOG_FLAG_VERBOSE) // 0...01111 // Setup fine grained logging. // The first 4 bits are being used by the standard log levels (0 - 3) // // We're going to add tracing, but NOT as a log level. // Tracing can be turned on and off independently of log level. #define HTTP_LOG_FLAG_TRACE (1 << 4) // 0...10000 // Setup the usual boolean macros. #define HTTP_LOG_ERROR (httpLogLevel & HTTP_LOG_FLAG_ERROR) #define HTTP_LOG_WARN (httpLogLevel & HTTP_LOG_FLAG_WARN) #define HTTP_LOG_INFO (httpLogLevel & HTTP_LOG_FLAG_INFO) #define HTTP_LOG_VERBOSE (httpLogLevel & HTTP_LOG_FLAG_VERBOSE) #define HTTP_LOG_TRACE (httpLogLevel & HTTP_LOG_FLAG_TRACE) // Configure asynchronous logging. // We follow the default configuration, // but we reserve a special macro to easily disable asynchronous logging for debugging purposes. #define HTTP_LOG_ASYNC_ENABLED YES #define HTTP_LOG_ASYNC_ERROR ( NO && HTTP_LOG_ASYNC_ENABLED) #define HTTP_LOG_ASYNC_WARN (YES && HTTP_LOG_ASYNC_ENABLED) #define HTTP_LOG_ASYNC_INFO (YES && HTTP_LOG_ASYNC_ENABLED) #define HTTP_LOG_ASYNC_VERBOSE (YES && HTTP_LOG_ASYNC_ENABLED) #define HTTP_LOG_ASYNC_TRACE (YES && HTTP_LOG_ASYNC_ENABLED) // Define logging primitives. #define HTTPLogError(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_ERROR, httpLogLevel, HTTP_LOG_FLAG_ERROR, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogWarn(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_WARN, httpLogLevel, HTTP_LOG_FLAG_WARN, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogInfo(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_INFO, httpLogLevel, HTTP_LOG_FLAG_INFO, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogVerbose(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_VERBOSE, httpLogLevel, HTTP_LOG_FLAG_VERBOSE, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogTrace() LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ HTTP_LOG_CONTEXT, @"%@[%p]: %@", THIS_FILE, self, THIS_METHOD) #define HTTPLogTrace2(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCError(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_ERROR, httpLogLevel, HTTP_LOG_FLAG_ERROR, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCWarn(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_WARN, httpLogLevel, HTTP_LOG_FLAG_WARN, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCInfo(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_INFO, httpLogLevel, HTTP_LOG_FLAG_INFO, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCVerbose(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_VERBOSE, httpLogLevel, HTTP_LOG_FLAG_VERBOSE, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCTrace() LOG_C_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ HTTP_LOG_CONTEXT, @"%@[%p]: %@", THIS_FILE, self, __FUNCTION__) #define HTTPLogCTrace2(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)
007xsq-sadsad
Core/HTTPLogging.h
Objective-C
bsd
6,296
#import <Foundation/Foundation.h> @protocol HTTPResponse /** * Returns the length of the data in bytes. * If you don't know the length in advance, implement the isChunked method and have it return YES. **/ - (UInt64)contentLength; /** * The HTTP server supports range requests in order to allow things like * file download resumption and optimized streaming on mobile devices. **/ - (UInt64)offset; - (void)setOffset:(UInt64)offset; /** * Returns the data for the response. * You do not have to return data of the exact length that is given. * You may optionally return data of a lesser length. * However, you must never return data of a greater length than requested. * Doing so could disrupt proper support for range requests. * * To support asynchronous responses, read the discussion at the bottom of this header. **/ - (NSData *)readDataOfLength:(NSUInteger)length; /** * Should only return YES after the HTTPConnection has read all available data. * That is, all data for the response has been returned to the HTTPConnection via the readDataOfLength method. **/ - (BOOL)isDone; @optional /** * If you need time to calculate any part of the HTTP response headers (status code or header fields), * this method allows you to delay sending the headers so that you may asynchronously execute the calculations. * Simply implement this method and return YES until you have everything you need concerning the headers. * * This method ties into the asynchronous response architecture of the HTTPConnection. * You should read the full discussion at the bottom of this header. * * If you return YES from this method, * the HTTPConnection will wait for you to invoke the responseHasAvailableData method. * After you do, the HTTPConnection will again invoke this method to see if the response is ready to send the headers. * * You should only delay sending the headers until you have everything you need concerning just the headers. * Asynchronously generating the body of the response is not an excuse to delay sending the headers. * Instead you should tie into the asynchronous response architecture, and use techniques such as the isChunked method. * * Important: You should read the discussion at the bottom of this header. **/ - (BOOL)delayResponeHeaders; /** * Status code for response. * Allows for responses such as redirect (301), etc. **/ - (NSInteger)status; /** * If you want to add any extra HTTP headers to the response, * simply return them in a dictionary in this method. **/ - (NSDictionary *)httpHeaders; /** * If you don't know the content-length in advance, * implement this method in your custom response class and return YES. * * Important: You should read the discussion at the bottom of this header. **/ - (BOOL)isChunked; /** * This method is called from the HTTPConnection class when the connection is closed, * or when the connection is finished with the response. * If your response is asynchronous, you should implement this method so you know not to * invoke any methods on the HTTPConnection after this method is called (as the connection may be deallocated). **/ - (void)connectionDidClose; @end /** * Important notice to those implementing custom asynchronous and/or chunked responses: * * HTTPConnection supports asynchronous responses. All you have to do in your custom response class is * asynchronously generate the response, and invoke HTTPConnection's responseHasAvailableData method. * You don't have to wait until you have all of the response ready to invoke this method. For example, if you * generate the response in incremental chunks, you could call responseHasAvailableData after generating * each chunk. Please see the HTTPAsyncFileResponse class for an example of how to do this. * * The normal flow of events for an HTTPConnection while responding to a request is like this: * - Send http resopnse headers * - Get data from response via readDataOfLength method. * - Add data to asyncSocket's write queue. * - Wait for asyncSocket to notify it that the data has been sent. * - Get more data from response via readDataOfLength method. * - ... continue this cycle until the entire response has been sent. * * With an asynchronous response, the flow is a little different. * * First the HTTPResponse is given the opportunity to postpone sending the HTTP response headers. * This allows the response to asynchronously execute any code needed to calculate a part of the header. * An example might be the response needs to generate some custom header fields, * or perhaps the response needs to look for a resource on network-attached storage. * Since the network-attached storage may be slow, the response doesn't know whether to send a 200 or 404 yet. * In situations such as this, the HTTPResponse simply implements the delayResponseHeaders method and returns YES. * After returning YES from this method, the HTTPConnection will wait until the response invokes its * responseHasAvailableData method. After this occurs, the HTTPConnection will again query the delayResponseHeaders * method to see if the response is ready to send the headers. * This cycle will continue until the delayResponseHeaders method returns NO. * * You should only delay sending the response headers until you have everything you need concerning just the headers. * Asynchronously generating the body of the response is not an excuse to delay sending the headers. * * After the response headers have been sent, the HTTPConnection calls your readDataOfLength method. * You may or may not have any available data at this point. If you don't, then simply return nil. * You should later invoke HTTPConnection's responseHasAvailableData when you have data to send. * * You don't have to keep track of when you return nil in the readDataOfLength method, or how many times you've invoked * responseHasAvailableData. Just simply call responseHasAvailableData whenever you've generated new data, and * return nil in your readDataOfLength whenever you don't have any available data in the requested range. * HTTPConnection will automatically detect when it should be requesting new data and will act appropriately. * * It's important that you also keep in mind that the HTTP server supports range requests. * The setOffset method is mandatory, and should not be ignored. * Make sure you take into account the offset within the readDataOfLength method. * You should also be aware that the HTTPConnection automatically sorts any range requests. * So if your setOffset method is called with a value of 100, then you can safely release bytes 0-99. * * HTTPConnection can also help you keep your memory footprint small. * Imagine you're dynamically generating a 10 MB response. You probably don't want to load all this data into * RAM, and sit around waiting for HTTPConnection to slowly send it out over the network. All you need to do * is pay attention to when HTTPConnection requests more data via readDataOfLength. This is because HTTPConnection * will never allow asyncSocket's write queue to get much bigger than READ_CHUNKSIZE bytes. You should * consider how you might be able to take advantage of this fact to generate your asynchronous response on demand, * while at the same time keeping your memory footprint small, and your application lightning fast. * * If you don't know the content-length in advanced, you should also implement the isChunked method. * This means the response will not include a Content-Length header, and will instead use "Transfer-Encoding: chunked". * There's a good chance that if your response is asynchronous and dynamic, it's also chunked. * If your response is chunked, you don't need to worry about range requests. **/
007xsq-sadsad
Core/HTTPResponse.h
Objective-C
bsd
7,802
#import "WebSocket.h" #import "HTTPMessage.h" #import "GCDAsyncSocket.h" #import "DDNumber.h" #import "DDData.h" #import "HTTPLogging.h" // Log levels: off, error, warn, info, verbose // Other flags : trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; #define TIMEOUT_NONE -1 #define TIMEOUT_REQUEST_BODY 10 #define TAG_HTTP_REQUEST_BODY 100 #define TAG_HTTP_RESPONSE_HEADERS 200 #define TAG_HTTP_RESPONSE_BODY 201 #define TAG_PREFIX 300 #define TAG_MSG_PLUS_SUFFIX 301 @interface WebSocket (PrivateAPI) - (void)readRequestBody; - (void)sendResponseBody; - (void)sendResponseHeaders; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation WebSocket + (BOOL)isWebSocketRequest:(HTTPMessage *)request { // Request (Draft 75): // // GET /demo HTTP/1.1 // Upgrade: WebSocket // Connection: Upgrade // Host: example.com // Origin: http://example.com // WebSocket-Protocol: sample // // // Request (Draft 76): // // GET /demo HTTP/1.1 // Upgrade: WebSocket // Connection: Upgrade // Host: example.com // Origin: http://example.com // Sec-WebSocket-Protocol: sample // Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5 // Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 // // ^n:ds[4U // Look for Upgrade: and Connection: headers. // If we find them, and they have the proper value, // we can safely assume this is a websocket request. NSString *upgradeHeaderValue = [request headerField:@"Upgrade"]; NSString *connectionHeaderValue = [request headerField:@"Connection"]; BOOL isWebSocket = YES; if (!upgradeHeaderValue || !connectionHeaderValue) { isWebSocket = NO; } else if (![upgradeHeaderValue caseInsensitiveCompare:@"WebSocket"] == NSOrderedSame) { isWebSocket = NO; } else if (![connectionHeaderValue caseInsensitiveCompare:@"Upgrade"] == NSOrderedSame) { isWebSocket = NO; } HTTPLogTrace2(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, (isWebSocket ? @"YES" : @"NO")); return isWebSocket; } + (BOOL)isVersion76Request:(HTTPMessage *)request { NSString *key1 = [request headerField:@"Sec-WebSocket-Key1"]; NSString *key2 = [request headerField:@"Sec-WebSocket-Key2"]; BOOL isVersion76; if (!key1 || !key2) { isVersion76 = NO; } else { isVersion76 = YES; } HTTPLogTrace2(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, (isVersion76 ? @"YES" : @"NO")); return isVersion76; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Setup and Teardown //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @synthesize websocketQueue; - (id)initWithRequest:(HTTPMessage *)aRequest socket:(GCDAsyncSocket *)socket { HTTPLogTrace(); if (aRequest == nil) { [self release]; return nil; } if ((self = [super init])) { if (HTTP_LOG_VERBOSE) { NSData *requestHeaders = [aRequest messageData]; NSString *temp = [[NSString alloc] initWithData:requestHeaders encoding:NSUTF8StringEncoding]; HTTPLogVerbose(@"%@[%p] Request Headers:\n%@", THIS_FILE, self, temp); [temp release]; } websocketQueue = dispatch_queue_create("WebSocket", NULL); request = [aRequest retain]; asyncSocket = [socket retain]; [asyncSocket setDelegate:self delegateQueue:websocketQueue]; isOpen = NO; isVersion76 = [[self class] isVersion76Request:request]; term = [[NSData alloc] initWithBytes:"\xFF" length:1]; } return self; } - (void)dealloc { HTTPLogTrace(); dispatch_release(websocketQueue); [request release]; [asyncSocket setDelegate:nil delegateQueue:NULL]; [asyncSocket disconnect]; [asyncSocket release]; [super dealloc]; } - (id)delegate { __block id result = nil; dispatch_sync(websocketQueue, ^{ result = delegate; }); return result; } - (void)setDelegate:(id)newDelegate { dispatch_async(websocketQueue, ^{ delegate = newDelegate; }); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Start and Stop //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Starting point for the WebSocket after it has been fully initialized (including subclasses). * This method is called by the HTTPConnection it is spawned from. **/ - (void)start { // This method is not exactly designed to be overriden. // Subclasses are encouraged to override the didOpen method instead. dispatch_async(websocketQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (isStarted) return; isStarted = YES; if (isVersion76) { [self readRequestBody]; } else { [self sendResponseHeaders]; [self didOpen]; } [pool drain]; }); } /** * This method is called by the HTTPServer if it is asked to stop. * The server, in turn, invokes stop on each WebSocket instance. **/ - (void)stop { // This method is not exactly designed to be overriden. // Subclasses are encouraged to override the didClose method instead. dispatch_async(websocketQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [asyncSocket disconnect]; [pool drain]; }); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark HTTP Response //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)readRequestBody { HTTPLogTrace(); NSAssert(isVersion76, @"WebSocket version 75 doesn't contain a request body"); [asyncSocket readDataToLength:8 withTimeout:TIMEOUT_NONE tag:TAG_HTTP_REQUEST_BODY]; } - (NSString *)originResponseHeaderValue { HTTPLogTrace(); NSString *origin = [request headerField:@"Origin"]; if (origin == nil) { NSString *port = [NSString stringWithFormat:@"%hu", [asyncSocket localPort]]; return [NSString stringWithFormat:@"http://localhost:%@", port]; } else { return origin; } } - (NSString *)locationResponseHeaderValue { HTTPLogTrace(); NSString *location; NSString *scheme = [asyncSocket isSecure] ? @"wss" : @"ws"; NSString *host = [request headerField:@"Host"]; NSString *requestUri = [[request url] relativeString]; if (host == nil) { NSString *port = [NSString stringWithFormat:@"%hu", [asyncSocket localPort]]; location = [NSString stringWithFormat:@"%@://localhost:%@%@", scheme, port, requestUri]; } else { location = [NSString stringWithFormat:@"%@://%@%@", scheme, host, requestUri]; } return location; } - (void)sendResponseHeaders { HTTPLogTrace(); // Request (Draft 75): // // GET /demo HTTP/1.1 // Upgrade: WebSocket // Connection: Upgrade // Host: example.com // Origin: http://example.com // WebSocket-Protocol: sample // // // Request (Draft 76): // // GET /demo HTTP/1.1 // Upgrade: WebSocket // Connection: Upgrade // Host: example.com // Origin: http://example.com // Sec-WebSocket-Protocol: sample // Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 // Sec-WebSocket-Key1: 4 @1 46546xW%0l 1 5 // // ^n:ds[4U // Response (Draft 75): // // HTTP/1.1 101 Web Socket Protocol Handshake // Upgrade: WebSocket // Connection: Upgrade // WebSocket-Origin: http://example.com // WebSocket-Location: ws://example.com/demo // WebSocket-Protocol: sample // // // Response (Draft 76): // // HTTP/1.1 101 WebSocket Protocol Handshake // Upgrade: WebSocket // Connection: Upgrade // Sec-WebSocket-Origin: http://example.com // Sec-WebSocket-Location: ws://example.com/demo // Sec-WebSocket-Protocol: sample // // 8jKS'y:G*Co,Wxa- HTTPMessage *wsResponse = [[HTTPMessage alloc] initResponseWithStatusCode:101 description:@"Web Socket Protocol Handshake" version:HTTPVersion1_1]; [wsResponse setHeaderField:@"Upgrade" value:@"WebSocket"]; [wsResponse setHeaderField:@"Connection" value:@"Upgrade"]; // Note: It appears that WebSocket-Origin and WebSocket-Location // are required for Google's Chrome implementation to work properly. // // If we don't send either header, Chrome will never report the WebSocket as open. // If we only send one of the two, Chrome will immediately close the WebSocket. // // In addition to this it appears that Chrome's implementation is very picky of the values of the headers. // They have to match exactly with what Chrome sent us or it will close the WebSocket. NSString *originValue = [self originResponseHeaderValue]; NSString *locationValue = [self locationResponseHeaderValue]; NSString *originField = isVersion76 ? @"Sec-WebSocket-Origin" : @"WebSocket-Origin"; NSString *locationField = isVersion76 ? @"Sec-WebSocket-Location" : @"WebSocket-Location"; [wsResponse setHeaderField:originField value:originValue]; [wsResponse setHeaderField:locationField value:locationValue]; NSData *responseHeaders = [wsResponse messageData]; [wsResponse release]; if (HTTP_LOG_VERBOSE) { NSString *temp = [[NSString alloc] initWithData:responseHeaders encoding:NSUTF8StringEncoding]; HTTPLogVerbose(@"%@[%p] Response Headers:\n%@", THIS_FILE, self, temp); [temp release]; } [asyncSocket writeData:responseHeaders withTimeout:TIMEOUT_NONE tag:TAG_HTTP_RESPONSE_HEADERS]; } - (NSData *)processKey:(NSString *)key { HTTPLogTrace(); unichar c; NSUInteger i; NSUInteger length = [key length]; // Concatenate the digits into a string, // and count the number of spaces. NSMutableString *numStr = [NSMutableString stringWithCapacity:10]; long long numSpaces = 0; for (i = 0; i < length; i++) { c = [key characterAtIndex:i]; if (c >= '0' && c <= '9') { [numStr appendFormat:@"%C", c]; } else if (c == ' ') { numSpaces++; } } long long num = strtoll([numStr UTF8String], NULL, 10); long long resultHostNum; if (numSpaces == 0) resultHostNum = 0; else resultHostNum = num / numSpaces; HTTPLogVerbose(@"key(%@) -> %qi / %qi = %qi", key, num, numSpaces, resultHostNum); // Convert result to 4 byte big-endian (network byte order) // and then convert to raw data. UInt32 result = OSSwapHostToBigInt32((uint32_t)resultHostNum); return [NSData dataWithBytes:&result length:4]; } - (void)sendResponseBody:(NSData *)d3 { HTTPLogTrace(); NSAssert(isVersion76, @"WebSocket version 75 doesn't contain a response body"); NSAssert([d3 length] == 8, @"Invalid requestBody length"); NSString *key1 = [request headerField:@"Sec-WebSocket-Key1"]; NSString *key2 = [request headerField:@"Sec-WebSocket-Key2"]; NSData *d1 = [self processKey:key1]; NSData *d2 = [self processKey:key2]; // Concatenated d1, d2 & d3 NSMutableData *d0 = [NSMutableData dataWithCapacity:(4+4+8)]; [d0 appendData:d1]; [d0 appendData:d2]; [d0 appendData:d3]; // Hash the data using MD5 NSData *responseBody = [d0 md5Digest]; [asyncSocket writeData:responseBody withTimeout:TIMEOUT_NONE tag:TAG_HTTP_RESPONSE_BODY]; if (HTTP_LOG_VERBOSE) { NSString *s1 = [[NSString alloc] initWithData:d1 encoding:NSASCIIStringEncoding]; NSString *s2 = [[NSString alloc] initWithData:d2 encoding:NSASCIIStringEncoding]; NSString *s3 = [[NSString alloc] initWithData:d3 encoding:NSASCIIStringEncoding]; NSString *s0 = [[NSString alloc] initWithData:d0 encoding:NSASCIIStringEncoding]; NSString *sH = [[NSString alloc] initWithData:responseBody encoding:NSASCIIStringEncoding]; HTTPLogVerbose(@"key1 result : raw(%@) str(%@)", d1, s1); HTTPLogVerbose(@"key2 result : raw(%@) str(%@)", d2, s2); HTTPLogVerbose(@"key3 passed : raw(%@) str(%@)", d3, s3); HTTPLogVerbose(@"key0 concat : raw(%@) str(%@)", d0, s0); HTTPLogVerbose(@"responseBody: raw(%@) str(%@)", responseBody, sH); [s1 release]; [s2 release]; [s3 release]; [s0 release]; [sH release]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Core Functionality //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)didOpen { HTTPLogTrace(); // Override me to perform any custom actions once the WebSocket has been opened. // This method is invoked on the websocketQueue. // // Don't forget to invoke [super didOpen] in your method. // Start reading for messages [asyncSocket readDataToLength:1 withTimeout:TIMEOUT_NONE tag:TAG_PREFIX]; // Notify delegate if ([delegate respondsToSelector:@selector(webSocketDidOpen:)]) { [delegate webSocketDidOpen:self]; } } - (void)sendMessage:(NSString *)msg { HTTPLogTrace(); NSData *msgData = [msg dataUsingEncoding:NSUTF8StringEncoding]; NSMutableData *data = [NSMutableData dataWithCapacity:([msgData length] + 2)]; [data appendBytes:"\x00" length:1]; [data appendData:msgData]; [data appendBytes:"\xFF" length:1]; // Remember: GCDAsyncSocket is thread-safe [asyncSocket writeData:data withTimeout:TIMEOUT_NONE tag:0]; } - (void)didReceiveMessage:(NSString *)msg { HTTPLogTrace(); // Override me to process incoming messages. // This method is invoked on the websocketQueue. // // For completeness, you should invoke [super didReceiveMessage:msg] in your method. // Notify delegate if ([delegate respondsToSelector:@selector(webSocket:didReceiveMessage:)]) { [delegate webSocket:self didReceiveMessage:msg]; } } - (void)didClose { HTTPLogTrace(); // Override me to perform any cleanup when the socket is closed // This method is invoked on the websocketQueue. // // Don't forget to invoke [super didClose] at the end of your method. // Notify delegate if ([delegate respondsToSelector:@selector(webSocketDidClose:)]) { [delegate webSocketDidClose:self]; } // Notify HTTPServer [[NSNotificationCenter defaultCenter] postNotificationName:WebSocketDidDieNotification object:self]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark AsyncSocket Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { HTTPLogTrace(); if (tag == TAG_HTTP_REQUEST_BODY) { [self sendResponseHeaders]; [self sendResponseBody:data]; [self didOpen]; } else if (tag == TAG_PREFIX) { UInt8 *pFrame = (UInt8 *)[data bytes]; UInt8 frame = *pFrame; if (frame <= 0x7F) { [asyncSocket readDataToData:term withTimeout:TIMEOUT_NONE tag:TAG_MSG_PLUS_SUFFIX]; } else { // Unsupported frame type [self didClose]; } } else { NSUInteger msgLength = [data length] - 1; // Excluding ending 0xFF frame NSString *msg = [[NSString alloc] initWithBytes:[data bytes] length:msgLength encoding:NSUTF8StringEncoding]; [self didReceiveMessage:msg]; [msg release]; // Read next message [asyncSocket readDataToLength:1 withTimeout:TIMEOUT_NONE tag:TAG_PREFIX]; } } - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)error { HTTPLogTrace2(@"%@[%p]: socketDidDisconnect:withError: %@", THIS_FILE, self, error); [self didClose]; } @end
007xsq-sadsad
Core/WebSocket.m
Objective-C
bsd
15,693
#import "HTTPAuthenticationRequest.h" #import "HTTPMessage.h" @interface HTTPAuthenticationRequest (PrivateAPI) - (NSString *)quotedSubHeaderFieldValue:(NSString *)param fromHeaderFieldValue:(NSString *)header; - (NSString *)nonquotedSubHeaderFieldValue:(NSString *)param fromHeaderFieldValue:(NSString *)header; @end @implementation HTTPAuthenticationRequest - (id)initWithRequest:(HTTPMessage *)request { if ((self = [super init])) { NSString *authInfo = [request headerField:@"Authorization"]; isBasic = NO; if ([authInfo length] >= 6) { isBasic = [[authInfo substringToIndex:6] caseInsensitiveCompare:@"Basic "] == NSOrderedSame; } isDigest = NO; if ([authInfo length] >= 7) { isDigest = [[authInfo substringToIndex:7] caseInsensitiveCompare:@"Digest "] == NSOrderedSame; } if (isBasic) { NSMutableString *temp = [[[authInfo substringFromIndex:6] mutableCopy] autorelease]; CFStringTrimWhitespace((CFMutableStringRef)temp); base64Credentials = [temp copy]; } if (isDigest) { username = [[self quotedSubHeaderFieldValue:@"username" fromHeaderFieldValue:authInfo] retain]; realm = [[self quotedSubHeaderFieldValue:@"realm" fromHeaderFieldValue:authInfo] retain]; nonce = [[self quotedSubHeaderFieldValue:@"nonce" fromHeaderFieldValue:authInfo] retain]; uri = [[self quotedSubHeaderFieldValue:@"uri" fromHeaderFieldValue:authInfo] retain]; // It appears from RFC 2617 that the qop is to be given unquoted // Tests show that Firefox performs this way, but Safari does not // Thus we'll attempt to retrieve the value as nonquoted, but we'll verify it doesn't start with a quote qop = [self nonquotedSubHeaderFieldValue:@"qop" fromHeaderFieldValue:authInfo]; if(qop && ([qop characterAtIndex:0] == '"')) { qop = [self quotedSubHeaderFieldValue:@"qop" fromHeaderFieldValue:authInfo]; } [qop retain]; nc = [[self nonquotedSubHeaderFieldValue:@"nc" fromHeaderFieldValue:authInfo] retain]; cnonce = [[self quotedSubHeaderFieldValue:@"cnonce" fromHeaderFieldValue:authInfo] retain]; response = [[self quotedSubHeaderFieldValue:@"response" fromHeaderFieldValue:authInfo] retain]; } } return self; } - (void)dealloc { [base64Credentials release]; [username release]; [realm release]; [nonce release]; [uri release]; [qop release]; [nc release]; [cnonce release]; [response release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Accessors: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)isBasic { return isBasic; } - (BOOL)isDigest { return isDigest; } - (NSString *)base64Credentials { return base64Credentials; } - (NSString *)username { return username; } - (NSString *)realm { return realm; } - (NSString *)nonce { return nonce; } - (NSString *)uri { return uri; } - (NSString *)qop { return qop; } - (NSString *)nc { return nc; } - (NSString *)cnonce { return cnonce; } - (NSString *)response { return response; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Private API: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Retrieves a "Sub Header Field Value" from a given header field value. * The sub header field is expected to be quoted. * * In the following header field: * Authorization: Digest username="Mufasa", qop=auth, response="6629fae4939" * The sub header field titled 'username' is quoted, and this method would return the value @"Mufasa". **/ - (NSString *)quotedSubHeaderFieldValue:(NSString *)param fromHeaderFieldValue:(NSString *)header { NSRange startRange = [header rangeOfString:[NSString stringWithFormat:@"%@=\"", param]]; if(startRange.location == NSNotFound) { // The param was not found anywhere in the header return nil; } NSUInteger postStartRangeLocation = startRange.location + startRange.length; NSUInteger postStartRangeLength = [header length] - postStartRangeLocation; NSRange postStartRange = NSMakeRange(postStartRangeLocation, postStartRangeLength); NSRange endRange = [header rangeOfString:@"\"" options:0 range:postStartRange]; if(endRange.location == NSNotFound) { // The ending double-quote was not found anywhere in the header return nil; } NSRange subHeaderRange = NSMakeRange(postStartRangeLocation, endRange.location - postStartRangeLocation); return [header substringWithRange:subHeaderRange]; } /** * Retrieves a "Sub Header Field Value" from a given header field value. * The sub header field is expected to not be quoted. * * In the following header field: * Authorization: Digest username="Mufasa", qop=auth, response="6629fae4939" * The sub header field titled 'qop' is nonquoted, and this method would return the value @"auth". **/ - (NSString *)nonquotedSubHeaderFieldValue:(NSString *)param fromHeaderFieldValue:(NSString *)header { NSRange startRange = [header rangeOfString:[NSString stringWithFormat:@"%@=", param]]; if(startRange.location == NSNotFound) { // The param was not found anywhere in the header return nil; } NSUInteger postStartRangeLocation = startRange.location + startRange.length; NSUInteger postStartRangeLength = [header length] - postStartRangeLocation; NSRange postStartRange = NSMakeRange(postStartRangeLocation, postStartRangeLength); NSRange endRange = [header rangeOfString:@"," options:0 range:postStartRange]; if(endRange.location == NSNotFound) { // The ending comma was not found anywhere in the header // However, if the nonquoted param is at the end of the string, there would be no comma // This is only possible if there are no spaces anywhere NSRange endRange2 = [header rangeOfString:@" " options:0 range:postStartRange]; if(endRange2.location != NSNotFound) { return nil; } else { return [header substringWithRange:postStartRange]; } } else { NSRange subHeaderRange = NSMakeRange(postStartRangeLocation, endRange.location - postStartRangeLocation); return [header substringWithRange:subHeaderRange]; } } @end
007xsq-sadsad
Core/HTTPAuthenticationRequest.m
Objective-C
bsd
6,336
#import <Cocoa/Cocoa.h> #import "HTTPConnection.h" @interface MyHTTPConnection : HTTPConnection { } @end
007xsq-sadsad
Samples/SecureHTTPServer/MyHTTPConnection.h
Objective-C
bsd
109
#import <Cocoa/Cocoa.h> #import <Security/Security.h> @interface DDKeychain : NSObject { } + (NSString *)passwordForHTTPServer; + (BOOL)setPasswordForHTTPServer:(NSString *)password; + (void)createNewIdentity; + (NSArray *)SSLIdentityAndCertificates; + (NSString *)applicationTemporaryDirectory; + (NSString *)stringForSecExternalFormat:(SecExternalFormat)extFormat; + (NSString *)stringForSecExternalItemType:(SecExternalItemType)itemType; + (NSString *)stringForSecKeychainAttrType:(SecKeychainAttrType)attrType; @end
007xsq-sadsad
Samples/SecureHTTPServer/DDKeychain.h
Objective-C
bsd
527
#import <Cocoa/Cocoa.h> @class HTTPServer; @interface AppDelegate : NSObject { HTTPServer *httpServer; } @end
007xsq-sadsad
Samples/SecureHTTPServer/AppDelegate.h
Objective-C
bsd
115
// // main.m // SecureHTTPServer // // Created by Robbie Hanson on 5/19/09. // Copyright Deusty Designs, LLC. 2009. All rights reserved. // #import <Cocoa/Cocoa.h> int main(int argc, char *argv[]) { return NSApplicationMain(argc, (const char **) argv); }
007xsq-sadsad
Samples/SecureHTTPServer/main.m
Objective-C
bsd
266
#import "AppDelegate.h" #import "HTTPServer.h" #import "MyHTTPConnection.h" #import "DDLog.h" #import "DDTTYLogger.h" // Log levels: off, error, warn, info, verbose static const int ddLogLevel = LOG_LEVEL_VERBOSE; @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Configure our logging framework. // To keep things simple and fast, we're just going to log to the Xcode console. [DDLog addLogger:[DDTTYLogger sharedInstance]]; // Initalize our http server httpServer = [[HTTPServer alloc] init]; // Tell the server to broadcast its presence via Bonjour. // This allows browsers such as Safari to automatically discover our service. // [httpServer setType:@"_http._tcp."]; // Note: Clicking the bonjour service in Safari won't work because Safari will use http and not https. // Just change the url to https for proper access. // Normally there's no need to run our server on any specific port. // Technologies like Bonjour allow clients to dynamically discover the server's port at runtime. // However, for easy testing you may want force a certain port so you can just hit the refresh button. [httpServer setPort:12345]; // We're going to extend the base HTTPConnection class with our MyHTTPConnection class. // This allows us to customize the server for things such as SSL and password-protection. [httpServer setConnectionClass:[MyHTTPConnection class]]; // Serve files from the standard Sites folder NSString *docRoot = [@"~/Sites" stringByExpandingTildeInPath]; DDLogInfo(@"Setting document root: %@", docRoot); [httpServer setDocumentRoot:docRoot]; NSError *error = nil; if(![httpServer start:&error]) { DDLogError(@"Error starting HTTP Server: %@", error); } } @end
007xsq-sadsad
Samples/SecureHTTPServer/AppDelegate.m
Objective-C
bsd
1,772
#import "MyHTTPConnection.h" #import "HTTPLogging.h" #import "DDKeychain.h" // Log levels: off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; @implementation MyHTTPConnection /** * Overrides HTTPConnection's method **/ - (BOOL)isSecureServer { HTTPLogTrace(); // Create an HTTPS server (all connections will be secured via SSL/TLS) return YES; } /** * Overrides HTTPConnection's method * * This method is expected to returns an array appropriate for use in kCFStreamSSLCertificates SSL Settings. * It should be an array of SecCertificateRefs except for the first element in the array, which is a SecIdentityRef. **/ - (NSArray *)sslIdentityAndCertificates { HTTPLogTrace(); NSArray *result = [DDKeychain SSLIdentityAndCertificates]; if([result count] == 0) { [DDKeychain createNewIdentity]; return [DDKeychain SSLIdentityAndCertificates]; } return result; } @end
007xsq-sadsad
Samples/SecureHTTPServer/MyHTTPConnection.m
Objective-C
bsd
974
#import <Cocoa/Cocoa.h> @class HTTPServer; @interface SecureWebSocketServerAppDelegate : NSObject <NSApplicationDelegate> { @private HTTPServer *httpServer; NSWindow *window; } @property (assign) IBOutlet NSWindow *window; @end
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/SecureWebSocketServerAppDelegate.h
Objective-C
bsd
235
<html> <head> <title>SimpleWebSocketServer</title> <script type="text/javascript" src="WebSocketTest.js"></script> <script type="text/javascript" src="WebSocketTest2.js"></script> </head> <body bgcolor="#FFFFFF"> <a href="javascript:WebSocketTest()">Does my browser support WebSockets?</a><br/> <br/> <br/> <a>Server Time</a> <a id='updateme'>not updated yet</a> <script type="text/javascript">init();</script> </body> </html>
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/Web/index.html
HTML
bsd
468
var ws; var t; function init() { document.getElementById('updateme').innerHTML = "connecting to websocket"; OpenWebSocket(); } function OpenWebSocket() { if ("WebSocket" in window) { ws = new WebSocket("%%WEBSOCKET_URL%%"); ws.onopen = function() { // Web Socket is connected document.getElementById('updateme').innerHTML = "websocket is open"; t=setTimeout("SendMessage()",1000); }; ws.onmessage = function(evt) { document.getElementById('updateme').innerHTML = evt.data; }; ws.onclose = function() { document.getElementById('updateme').innerHTML = "websocket is closed"; OpenWebSocket(); }; ws.onerror = function(evt) { alert("onerror: " + evt); }; } else { alert("Browser doesn't support WebSocket!"); } } function SendMessage() { if ("WebSocket" in window) { ws.send("time"); t=setTimeout("SendMessage()",1000); } else { alert("Browser doesn't support WebSocket!"); } }
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/Web/WebSocketTest2.js
JavaScript
bsd
983
function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket supported here! :)\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } else { // Browser doesn't support WebSocket alert("WebSocket NOT supported here! :(\r\n\r\nBrowser: " + navigator.appName + " " + navigator.appVersion + "\r\n\r\n(based on Google sample code)"); } }
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/Web/WebSocketTest.js
JavaScript
bsd
417
#import <Foundation/Foundation.h> #import "HTTPConnection.h" @class MyWebSocket; @interface MyHTTPConnection : HTTPConnection { MyWebSocket *ws; } @end
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/MyHTTPConnection.h
Objective-C
bsd
156
#import <Cocoa/Cocoa.h> #import <Security/Security.h> @interface DDKeychain : NSObject { } + (NSString *)passwordForHTTPServer; + (BOOL)setPasswordForHTTPServer:(NSString *)password; + (void)createNewIdentity; + (NSArray *)SSLIdentityAndCertificates; + (NSString *)applicationTemporaryDirectory; + (NSString *)stringForSecExternalFormat:(SecExternalFormat)extFormat; + (NSString *)stringForSecExternalItemType:(SecExternalItemType)itemType; + (NSString *)stringForSecKeychainAttrType:(SecKeychainAttrType)attrType; @end
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/DDKeychain.h
Objective-C
bsd
527
{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;} {\colortbl;\red255\green255\blue255;} \paperw9840\paperh8400 \pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural \f0\b\fs24 \cf0 Engineering: \b0 \ Some people\ \ \b Human Interface Design: \b0 \ Some other people\ \ \b Testing: \b0 \ Hopefully not nobody\ \ \b Documentation: \b0 \ Whoever\ \ \b With special thanks to: \b0 \ Mom\ }
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/en.lproj/Credits.rtf
Rich Text Format
bsd
436
#import "SecureWebSocketServerAppDelegate.h" #import "HTTPServer.h" #import "MyHTTPConnection.h" #import "DDLog.h" #import "DDTTYLogger.h" // Log levels: off, error, warn, info, verbose static const int ddLogLevel = LOG_LEVEL_VERBOSE; @implementation SecureWebSocketServerAppDelegate @synthesize window; - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Configure our logging framework. // To keep things simple and fast, we're just going to log to the Xcode console. [DDLog addLogger:[DDTTYLogger sharedInstance]]; // Create server using our custom MyHTTPServer class httpServer = [[HTTPServer alloc] init]; // Tell server to use our custom MyHTTPConnection class. [httpServer setConnectionClass:[MyHTTPConnection class]]; // Tell the server to broadcast its presence via Bonjour. // This allows browsers such as Safari to automatically discover our service. [httpServer setType:@"_http._tcp."]; // Normally there's no need to run our server on any specific port. // Technologies like Bonjour allow clients to dynamically discover the server's port at runtime. // However, for easy testing you may want force a certain port so you can just hit the refresh button. [httpServer setPort:12345]; // Serve files from our embedded Web folder NSString *webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Web"]; DDLogInfo(@"Setting document root: %@", webPath); [httpServer setDocumentRoot:webPath]; // Start the server (and check for problems) NSError *error; if(![httpServer start:&error]) { DDLogError(@"Error starting HTTP Server: %@", error); } } @end
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/SecureWebSocketServerAppDelegate.m
Objective-C
bsd
1,652
#import "MyWebSocket.h" #import "HTTPLogging.h" // Log levels: off, error, warn, info, verbose // Other flags : trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN | HTTP_LOG_FLAG_TRACE; @implementation MyWebSocket - (void)didOpen { HTTPLogTrace(); [super didOpen]; } - (void)didReceiveMessage:(NSString *)msg { HTTPLogTrace2(@"%@[%p]: didReceiveMessage: %@", THIS_FILE, self, msg); [self sendMessage:[NSString stringWithFormat:@"%@", [NSDate date]]]; } - (void)didClose { HTTPLogTrace(); [super didClose]; } @end
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/MyWebSocket.m
Objective-C
bsd
539
// // main.m // SecureWebSocketServer // // Created by Robbie Hanson on 6/3/11. // Copyright 2011 Voalte. All rights reserved. // #import <Cocoa/Cocoa.h> int main(int argc, char *argv[]) { return NSApplicationMain(argc, (const char **)argv); }
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/main.m
Objective-C
bsd
251
#import <Foundation/Foundation.h> #import "WebSocket.h" @interface MyWebSocket : WebSocket { } @end
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/MyWebSocket.h
Objective-C
bsd
105
#import "MyHTTPConnection.h" #import "HTTPMessage.h" #import "HTTPResponse.h" #import "HTTPDynamicFileResponse.h" #import "GCDAsyncSocket.h" #import "MyWebSocket.h" #import "HTTPLogging.h" #import "DDKeychain.h" // Log levels: off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; @implementation MyHTTPConnection /** * Overrides HTTPConnection's method **/ - (BOOL)isSecureServer { HTTPLogTrace(); // Create an HTTPS server (all connections will be secured via SSL/TLS) return YES; } /** * Overrides HTTPConnection's method * * This method is expected to returns an array appropriate for use in kCFStreamSSLCertificates SSL Settings. * It should be an array of SecCertificateRefs except for the first element in the array, which is a SecIdentityRef. **/ - (NSArray *)sslIdentityAndCertificates { HTTPLogTrace(); NSArray *result = [DDKeychain SSLIdentityAndCertificates]; if([result count] == 0) { HTTPLogInfo(@"sslIdentityAndCertificates: Creating New Identity..."); [DDKeychain createNewIdentity]; return [DDKeychain SSLIdentityAndCertificates]; } return result; } - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path { HTTPLogTrace(); if ([path isEqualToString:@"/WebSocketTest2.js"]) { // The socket.js file contains a URL template that needs to be completed: // // ws = new WebSocket("%%WEBSOCKET_URL%%"); // // We need to replace "%%WEBSOCKET_URL%%" with whatever URL the server is running on. // We can accomplish this easily with the HTTPDynamicFileResponse class, // which takes a dictionary of replacement key-value pairs, // and performs replacements on the fly as it uploads the file. NSString *wsLocation; NSString *scheme = [asyncSocket isSecure] ? @"wss" : @"ws"; NSString *wsHost = [request headerField:@"Host"]; if (wsHost == nil) { NSString *port = [NSString stringWithFormat:@"%hu", [asyncSocket localPort]]; wsLocation = [NSString stringWithFormat:@"%@://localhost:%@%/service", scheme, port]; } else { wsLocation = [NSString stringWithFormat:@"%@://%@/service", scheme, wsHost]; } NSDictionary *replacementDict = [NSDictionary dictionaryWithObject:wsLocation forKey:@"WEBSOCKET_URL"]; return [[[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path] forConnection:self separator:@"%%" replacementDictionary:replacementDict] autorelease]; } return [super httpResponseForMethod:method URI:path]; } - (WebSocket *)webSocketForURI:(NSString *)path { HTTPLogTrace2(@"%@[%p]: webSocketForURI: %@", THIS_FILE, self, path); if([path isEqualToString:@"/service"]) { HTTPLogInfo(@"MyHTTPConnection: Creating MyWebSocket..."); return [[[MyWebSocket alloc] initWithRequest:request socket:asyncSocket] autorelease]; } return [super webSocketForURI:path]; } @end
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/MyHTTPConnection.m
Objective-C
bsd
3,070
#import "DDKeychain.h" @implementation DDKeychain //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Server: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Retrieves the password stored in the keychain for the HTTP server. **/ + (NSString *)passwordForHTTPServer { NSString *password = nil; const char *service = [@"HTTP Server" UTF8String]; const char *account = [@"Deusty" UTF8String]; UInt32 passwordLength = 0; void *passwordBytes = nil; OSStatus status; status = SecKeychainFindGenericPassword(NULL, // default keychain (UInt32)strlen(service), // length of service name service, // service name (UInt32)strlen(account), // length of account name account, // account name &passwordLength, // length of password &passwordBytes, // pointer to password data NULL); // keychain item reference (NULL if unneeded) if(status == noErr) { NSData *passwordData = [NSData dataWithBytesNoCopy:passwordBytes length:passwordLength freeWhenDone:NO]; password = [[[NSString alloc] initWithData:passwordData encoding:NSUTF8StringEncoding] autorelease]; } // SecKeychainItemFreeContent(attrList, data) // attrList - previously returned attributes // data - previously returned password if(passwordBytes) SecKeychainItemFreeContent(NULL, passwordBytes); return password; } /** * This method sets the password for the HTTP server. **/ + (BOOL)setPasswordForHTTPServer:(NSString *)password { const char *service = [@"HTTP Server" UTF8String]; const char *account = [@"Deusty" UTF8String]; const char *kind = [@"Deusty password" UTF8String]; const char *passwd = [password UTF8String]; SecKeychainItemRef itemRef = NULL; // The first thing we need to do is check to see a password for the library already exists in the keychain OSStatus status; status = SecKeychainFindGenericPassword(NULL, // default keychain (UInt32)strlen(service), // length of service name service, // service name (UInt32)strlen(account), // length of account name account, // account name NULL, // length of password (NULL if unneeded) NULL, // pointer to password data (NULL if unneeded) &itemRef); // the keychain item reference if(status == errSecItemNotFound) { // Setup the attributes the for the keychain item SecKeychainAttribute attrs[] = { { kSecServiceItemAttr, (UInt32)strlen(service), (char *)service }, { kSecAccountItemAttr, (UInt32)strlen(account), (char *)account }, { kSecDescriptionItemAttr, (UInt32)strlen(kind), (char *)kind } }; SecKeychainAttributeList attributes = { sizeof(attrs) / sizeof(attrs[0]), attrs }; status = SecKeychainItemCreateFromContent(kSecGenericPasswordItemClass, // class of item to create &attributes, // pointer to the list of attributes (UInt32)strlen(passwd), // length of password passwd, // pointer to password data NULL, // default keychain NULL, // access list (NULL if this app only) &itemRef); // the keychain item reference } else if(status == noErr) { // A keychain item for the library already exists // All we need to do is update it with the new password status = SecKeychainItemModifyAttributesAndData(itemRef, // the keychain item reference NULL, // no change to attributes (UInt32)strlen(passwd), // length of password passwd); // pointer to password data } // Don't forget to release anything we create if(itemRef) CFRelease(itemRef); return (status == noErr); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Identity: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method creates a new identity, and adds it to the keychain. * An identity is simply a certificate (public key and public information) along with a matching private key. * This method generates a new private key, and then uses the private key to generate a new self-signed certificate. **/ + (void)createNewIdentity { // Declare any Carbon variables we may create // We do this here so it's easier to compare to the bottom of this method where we release them all SecKeychainRef keychain = NULL; CFArrayRef outItems = NULL; // Configure the paths where we'll create all of our identity files NSString *basePath = [DDKeychain applicationTemporaryDirectory]; NSString *privateKeyPath = [basePath stringByAppendingPathComponent:@"private.pem"]; NSString *reqConfPath = [basePath stringByAppendingPathComponent:@"req.conf"]; NSString *certificatePath = [basePath stringByAppendingPathComponent:@"certificate.crt"]; NSString *certWrapperPath = [basePath stringByAppendingPathComponent:@"certificate.p12"]; // You can generate your own private key by running the following command in the terminal: // openssl genrsa -out private.pem 1024 // // Where 1024 is the size of the private key. // You may used a bigger number. // It is probably a good recommendation to use at least 1024... NSArray *privateKeyArgs = [NSArray arrayWithObjects:@"genrsa", @"-out", privateKeyPath, @"1024", nil]; NSTask *genPrivateKeyTask = [[[NSTask alloc] init] autorelease]; [genPrivateKeyTask setLaunchPath:@"/usr/bin/openssl"]; [genPrivateKeyTask setArguments:privateKeyArgs]; [genPrivateKeyTask launch]; // Don't use waitUntilExit - I've had too many problems with it in the past do { [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]]; } while([genPrivateKeyTask isRunning]); // Now we want to create a configuration file for our certificate // This is an optional step, but we do it so people who are browsing their keychain // know exactly where the certificate came from, and don't delete it. NSMutableString *mStr = [NSMutableString stringWithCapacity:500]; [mStr appendFormat:@"%@\n", @"[ req ]"]; [mStr appendFormat:@"%@\n", @"distinguished_name = req_distinguished_name"]; [mStr appendFormat:@"%@\n", @"prompt = no"]; [mStr appendFormat:@"%@\n", @""]; [mStr appendFormat:@"%@\n", @"[ req_distinguished_name ]"]; [mStr appendFormat:@"%@\n", @"C = US"]; [mStr appendFormat:@"%@\n", @"ST = Missouri"]; [mStr appendFormat:@"%@\n", @"L = Springfield"]; [mStr appendFormat:@"%@\n", @"O = Deusty Designs, LLC"]; [mStr appendFormat:@"%@\n", @"OU = Open Source"]; [mStr appendFormat:@"%@\n", @"CN = SecureHTTPServer"]; [mStr appendFormat:@"%@\n", @"emailAddress = robbiehanson@deusty.com"]; [mStr writeToFile:reqConfPath atomically:NO encoding:NSUTF8StringEncoding error:nil]; // You can generate your own certificate by running the following command in the terminal: // openssl req -new -x509 -key private.pem -out certificate.crt -text -days 365 -batch // // You can optionally create a configuration file, and pass an extra command to use it: // -config req.conf NSArray *certificateArgs = [NSArray arrayWithObjects:@"req", @"-new", @"-x509", @"-key", privateKeyPath, @"-config", reqConfPath, @"-out", certificatePath, @"-text", @"-days", @"365", @"-batch", nil]; NSTask *genCertificateTask = [[[NSTask alloc] init] autorelease]; [genCertificateTask setLaunchPath:@"/usr/bin/openssl"]; [genCertificateTask setArguments:certificateArgs]; [genCertificateTask launch]; // Don't use waitUntilExit - I've had too many problems with it in the past do { [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]]; } while([genCertificateTask isRunning]); // Mac OS X has problems importing private keys, so we wrap everything in PKCS#12 format // You can create a p12 wrapper by running the following command in the terminal: // openssl pkcs12 -export -in certificate.crt -inkey private.pem // -passout pass:password -out certificate.p12 -name "Open Source" NSArray *certWrapperArgs = [NSArray arrayWithObjects:@"pkcs12", @"-export", @"-export", @"-in", certificatePath, @"-inkey", privateKeyPath, @"-passout", @"pass:password", @"-out", certWrapperPath, @"-name", @"SecureHTTPServer", nil]; NSTask *genCertWrapperTask = [[[NSTask alloc] init] autorelease]; [genCertWrapperTask setLaunchPath:@"/usr/bin/openssl"]; [genCertWrapperTask setArguments:certWrapperArgs]; [genCertWrapperTask launch]; // Don't use waitUntilExit - I've had too many problems with it in the past do { [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.05]]; } while([genCertWrapperTask isRunning]); // At this point we've created all the identity files that we need // Our next step is to import the identity into the keychain // We can do this by using the SecKeychainItemImport() method. // But of course this method is "Frozen in Carbonite"... // So it's going to take us 100 lines of code to build up the parameters needed to make the method call NSData *certData = [NSData dataWithContentsOfFile:certWrapperPath]; /* SecKeyImportExportFlags - typedef uint32_t * Defines values for the flags field of the import/export parameters. * * enum * { * kSecKeyImportOnlyOne = 0x00000001, * kSecKeySecurePassphrase = 0x00000002, * kSecKeyNoAccessControl = 0x00000004 * }; * * kSecKeyImportOnlyOne * Prevents the importing of more than one private key by the SecKeychainItemImport function. * If the importKeychain parameter is NULL, this bit is ignored. Otherwise, if this bit is set and there is * more than one key in the incoming external representation, * no items are imported to the specified keychain and the error errSecMultipleKeys is returned. * kSecKeySecurePassphrase * When set, the password for import or export is obtained by user prompt. Otherwise, you must provide the * password in the passphrase field of the SecKeyImportExportParameters structure. * A user-supplied password is preferred, because it avoids having the cleartext password appear in the * application’s address space at any time. * kSecKeyNoAccessControl * When set, imported private keys have no access object attached to them. In the absence of both this bit and * the accessRef field in SecKeyImportExportParameters, imported private keys are given default access controls **/ SecKeyImportExportFlags importFlags = kSecKeyImportOnlyOne; /* SecKeyImportExportParameters - typedef struct * * FOR IMPORT AND EXPORT: * uint32_t version * The version of this structure; the current value is SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION. * SecKeyImportExportFlags flags * A set of flag bits, defined in "Keychain Item Import/Export Parameter Flags". * CFTypeRef passphrase * A password, used for kSecFormatPKCS12 and kSecFormatWrapped formats only... * IE - kSecFormatWrappedOpenSSL, kSecFormatWrappedSSH, or kSecFormatWrappedPKCS8 * CFStringRef alertTitle * Title of secure password alert panel. * When importing or exporting a key, if you set the kSecKeySecurePassphrase flag bit, * you can optionally use this field to specify a string for the password panel’s title bar. * CFStringRef alertPrompt * Prompt in secure password alert panel. * When importing or exporting a key, if you set the kSecKeySecurePassphrase flag bit, * you can optionally use this field to specify a string for the prompt that appears in the password panel. * * FOR IMPORT ONLY: * SecAccessRef accessRef * Specifies the initial access controls of imported private keys. * If more than one private key is being imported, all private keys get the same initial access controls. * If this field is NULL when private keys are being imported, then the access object for the keychain item * for an imported private key depends on the kSecKeyNoAccessControl bit in the flags parameter. * If this bit is 0 (or keyParams is NULL), the default access control is used. * If this bit is 1, no access object is attached to the keychain item for imported private keys. * CSSM_KEYUSE keyUsage * A word of bits constituting the low-level use flags for imported keys as defined in cssmtype.h. * If this field is 0 or keyParams is NULL, the default value is CSSM_KEYUSE_ANY. * CSSM_KEYATTR_FLAGS keyAttributes * The following are valid values for these flags: * CSSM_KEYATTR_PERMANENT, CSSM_KEYATTR_SENSITIVE, and CSSM_KEYATTR_EXTRACTABLE. * The default value is CSSM_KEYATTR_SENSITIVE | CSSM_KEYATTR_EXTRACTABLE * The CSSM_KEYATTR_SENSITIVE bit indicates that the key can only be extracted in wrapped form. * Important: If you do not set the CSSM_KEYATTR_EXTRACTABLE bit, * you cannot extract the imported key from the keychain in any form, including in wrapped form. **/ SecKeyImportExportParameters importParameters; importParameters.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION; importParameters.flags = importFlags; importParameters.passphrase = CFSTR("password"); importParameters.accessRef = NULL; importParameters.keyUsage = CSSM_KEYUSE_ANY; importParameters.keyAttributes = CSSM_KEYATTR_SENSITIVE | CSSM_KEYATTR_EXTRACTABLE; /* SecKeychainItemImport - Imports one or more certificates, keys, or identities and adds them to a keychain. * * Parameters: * CFDataRef importedData * The external representation of the items to import. * CFStringRef fileNameOrExtension * The name or extension of the file from which the external representation was obtained. * Pass NULL if you don’t know the name or extension. * SecExternalFormat *inputFormat * On input, points to the format of the external representation. * Pass kSecFormatUnknown if you do not know the exact format. * On output, points to the format that the function has determined the external representation to be in. * Pass NULL if you don’t know the format and don’t want the format returned to you. * SecExternalItemType *itemType * On input, points to the item type of the item or items contained in the external representation. * Pass kSecItemTypeUnknown if you do not know the item type. * On output, points to the item type that the function has determined the external representation to contain. * Pass NULL if you don’t know the item type and don’t want the type returned to you. * SecItemImportExportFlags flags * Unused; pass in 0. * const SecKeyImportExportParameters *keyParams * A pointer to a structure containing a set of input parameters for the function. * If no key items are being imported, these parameters are optional * and you can set the keyParams parameter to NULL. * SecKeychainRef importKeychain * A keychain object indicating the keychain to which the key or certificate should be imported. * If you pass NULL, the item is not imported. * Use the SecKeychainCopyDefault function to get a reference to the default keychain. * If the kSecKeyImportOnlyOne bit is set and there is more than one key in the * incoming external representation, no items are imported to the specified keychain and the * error errSecMultiplePrivKeys is returned. * CFArrayRef *outItems * On output, points to an array of SecKeychainItemRef objects for the imported items. * You must provide a valid pointer to a CFArrayRef object to receive this information. * If you pass NULL for this parameter, the function does not return the imported items. * Release this object by calling the CFRelease function when you no longer need it. **/ SecExternalFormat inputFormat = kSecFormatPKCS12; SecExternalItemType itemType = kSecItemTypeUnknown; SecKeychainCopyDefault(&keychain); OSStatus err = 0; err = SecKeychainItemImport((CFDataRef)certData, // CFDataRef importedData NULL, // CFStringRef fileNameOrExtension &inputFormat, // SecExternalFormat *inputFormat &itemType, // SecExternalItemType *itemType 0, // SecItemImportExportFlags flags (Unused) &importParameters, // const SecKeyImportExportParameters *keyParams keychain, // SecKeychainRef importKeychain &outItems); // CFArrayRef *outItems NSLog(@"OSStatus: %i", err); NSLog(@"SecExternalFormat: %@", [DDKeychain stringForSecExternalFormat:inputFormat]); NSLog(@"SecExternalItemType: %@", [DDKeychain stringForSecExternalItemType:itemType]); NSLog(@"outItems: %@", (NSArray *)outItems); // Don't forget to delete the temporary files [[NSFileManager defaultManager] removeItemAtPath:privateKeyPath error:nil]; [[NSFileManager defaultManager] removeItemAtPath:reqConfPath error:nil]; [[NSFileManager defaultManager] removeItemAtPath:certificatePath error:nil]; [[NSFileManager defaultManager] removeItemAtPath:certWrapperPath error:nil]; // Don't forget to release anything we may have created if(keychain) CFRelease(keychain); if(outItems) CFRelease(outItems); } /** * Returns an array of SecCertificateRefs except for the first element in the array, which is a SecIdentityRef. * Currently this method is designed to return the identity created in the method above. * You will most likely alter this method to return a proper identity based on what it is you're trying to do. **/ + (NSArray *)SSLIdentityAndCertificates { // Declare any Carbon variables we may create // We do this here so it's easier to compare to the bottom of this method where we release them all SecKeychainRef keychain = NULL; SecIdentitySearchRef searchRef = NULL; // Create array to hold the results NSMutableArray *result = [NSMutableArray array]; /* SecKeychainAttribute - typedef struct * Contains keychain attributes. * * struct SecKeychainAttribute * { * SecKeychainAttrType tag; * UInt32 length; * void *data; * }; * * Fields: * tag * A 4-byte attribute tag. See “Keychain Item Attribute Constants” for valid attribute types. * length * The length of the buffer pointed to by data. * data * A pointer to the attribute data. **/ /* SecKeychainAttributeList - typedef struct * Represents a list of keychain attributes. * * struct SecKeychainAttributeList * { * UInt32 count; * SecKeychainAttribute *attr; * }; * * Fields: * count * An unsigned 32-bit integer that represents the number of keychain attributes in the array. * attr * A pointer to the first keychain attribute in the array. **/ SecKeychainCopyDefault(&keychain); SecIdentitySearchCreate(keychain, CSSM_KEYUSE_ANY, &searchRef); SecIdentityRef currentIdentityRef = NULL; while(searchRef && (SecIdentitySearchCopyNext(searchRef, &currentIdentityRef) != errSecItemNotFound)) { // Extract the private key from the identity, and examine it to see if it will work for us SecKeyRef privateKeyRef = NULL; SecIdentityCopyPrivateKey(currentIdentityRef, &privateKeyRef); if(privateKeyRef) { // Get the name attribute of the private key // We're looking for a private key with the name of "Mojo User" SecItemAttr itemAttributes[] = {kSecKeyPrintName}; SecExternalFormat externalFormats[] = {kSecFormatUnknown}; int itemAttributesSize = sizeof(itemAttributes) / sizeof(*itemAttributes); int externalFormatsSize = sizeof(externalFormats) / sizeof(*externalFormats); NSAssert(itemAttributesSize == externalFormatsSize, @"Arrays must have identical counts!"); SecKeychainAttributeInfo info = {itemAttributesSize, (void *)&itemAttributes, (void *)&externalFormats}; SecKeychainAttributeList *privateKeyAttributeList = NULL; SecKeychainItemCopyAttributesAndData((SecKeychainItemRef)privateKeyRef, &info, NULL, &privateKeyAttributeList, NULL, NULL); if(privateKeyAttributeList) { SecKeychainAttribute nameAttribute = privateKeyAttributeList->attr[0]; NSString *name = [[[NSString alloc] initWithBytes:nameAttribute.data length:(nameAttribute.length) encoding:NSUTF8StringEncoding] autorelease]; // Ugly Hack // For some reason, name sometimes contains odd characters at the end of it // I'm not sure why, and I don't know of a proper fix, thus the use of the hasPrefix: method if([name hasPrefix:@"SecureHTTPServer"]) { // It's possible for there to be more than one private key with the above prefix // But we're only allowed to have one identity, so we make sure to only add one to the array if([result count] == 0) { [result addObject:(id)currentIdentityRef]; } } SecKeychainItemFreeAttributesAndData(privateKeyAttributeList, NULL); } CFRelease(privateKeyRef); } CFRelease(currentIdentityRef); } if(keychain) CFRelease(keychain); if(searchRef) CFRelease(searchRef); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Utilities: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Creates (if necessary) and returns a temporary directory for the application. * * A general temporary directory is provided for each user by the OS. * This prevents conflicts between the same application running on multiple user accounts. * We take this a step further by putting everything inside another subfolder, identified by our application name. **/ + (NSString *)applicationTemporaryDirectory { NSString *userTempDir = NSTemporaryDirectory(); NSString *appTempDir = [userTempDir stringByAppendingPathComponent:@"SecureHTTPServer"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if([fileManager fileExistsAtPath:appTempDir] == NO) { [fileManager createDirectoryAtPath:appTempDir withIntermediateDirectories:YES attributes:nil error:nil]; } return appTempDir; } /** * Simple utility class to convert a SecExternalFormat into a string suitable for printing/logging. **/ + (NSString *)stringForSecExternalFormat:(SecExternalFormat)extFormat { switch(extFormat) { case kSecFormatUnknown : return @"kSecFormatUnknown"; /* Asymmetric Key Formats */ case kSecFormatOpenSSL : return @"kSecFormatOpenSSL"; case kSecFormatSSH : return @"kSecFormatSSH - Not Supported"; case kSecFormatBSAFE : return @"kSecFormatBSAFE"; /* Symmetric Key Formats */ case kSecFormatRawKey : return @"kSecFormatRawKey"; /* Formats for wrapped symmetric and private keys */ case kSecFormatWrappedPKCS8 : return @"kSecFormatWrappedPKCS8"; case kSecFormatWrappedOpenSSL : return @"kSecFormatWrappedOpenSSL"; case kSecFormatWrappedSSH : return @"kSecFormatWrappedSSH - Not Supported"; case kSecFormatWrappedLSH : return @"kSecFormatWrappedLSH - Not Supported"; /* Formats for certificates */ case kSecFormatX509Cert : return @"kSecFormatX509Cert"; /* Aggregate Types */ case kSecFormatPEMSequence : return @"kSecFormatPEMSequence"; case kSecFormatPKCS7 : return @"kSecFormatPKCS7"; case kSecFormatPKCS12 : return @"kSecFormatPKCS12"; case kSecFormatNetscapeCertSequence : return @"kSecFormatNetscapeCertSequence"; default : return @"Unknown"; } } /** * Simple utility class to convert a SecExternalItemType into a string suitable for printing/logging. **/ + (NSString *)stringForSecExternalItemType:(SecExternalItemType)itemType { switch(itemType) { case kSecItemTypeUnknown : return @"kSecItemTypeUnknown"; case kSecItemTypePrivateKey : return @"kSecItemTypePrivateKey"; case kSecItemTypePublicKey : return @"kSecItemTypePublicKey"; case kSecItemTypeSessionKey : return @"kSecItemTypeSessionKey"; case kSecItemTypeCertificate : return @"kSecItemTypeCertificate"; case kSecItemTypeAggregate : return @"kSecItemTypeAggregate"; default : return @"Unknown"; } } /** * Simple utility class to convert a SecKeychainAttrType into a string suitable for printing/logging. **/ + (NSString *)stringForSecKeychainAttrType:(SecKeychainAttrType)attrType { switch(attrType) { case kSecCreationDateItemAttr : return @"kSecCreationDateItemAttr"; case kSecModDateItemAttr : return @"kSecModDateItemAttr"; case kSecDescriptionItemAttr : return @"kSecDescriptionItemAttr"; case kSecCommentItemAttr : return @"kSecCommentItemAttr"; case kSecCreatorItemAttr : return @"kSecCreatorItemAttr"; case kSecTypeItemAttr : return @"kSecTypeItemAttr"; case kSecScriptCodeItemAttr : return @"kSecScriptCodeItemAttr"; case kSecLabelItemAttr : return @"kSecLabelItemAttr"; case kSecInvisibleItemAttr : return @"kSecInvisibleItemAttr"; case kSecNegativeItemAttr : return @"kSecNegativeItemAttr"; case kSecCustomIconItemAttr : return @"kSecCustomIconItemAttr"; case kSecAccountItemAttr : return @"kSecAccountItemAttr"; case kSecServiceItemAttr : return @"kSecServiceItemAttr"; case kSecGenericItemAttr : return @"kSecGenericItemAttr"; case kSecSecurityDomainItemAttr : return @"kSecSecurityDomainItemAttr"; case kSecServerItemAttr : return @"kSecServerItemAttr"; case kSecAuthenticationTypeItemAttr : return @"kSecAuthenticationTypeItemAttr"; case kSecPortItemAttr : return @"kSecPortItemAttr"; case kSecPathItemAttr : return @"kSecPathItemAttr"; case kSecVolumeItemAttr : return @"kSecVolumeItemAttr"; case kSecAddressItemAttr : return @"kSecAddressItemAttr"; case kSecSignatureItemAttr : return @"kSecSignatureItemAttr"; case kSecProtocolItemAttr : return @"kSecProtocolItemAttr"; case kSecCertificateType : return @"kSecCertificateType"; case kSecCertificateEncoding : return @"kSecCertificateEncoding"; case kSecCrlType : return @"kSecCrlType"; case kSecCrlEncoding : return @"kSecCrlEncoding"; case kSecAlias : return @"kSecAlias"; default : return @"Unknown"; } } @end
007xsq-sadsad
Samples/SecureWebSocketServer/SecureWebSocketServer/DDKeychain.m
Objective-C
bsd
28,301
#import <Cocoa/Cocoa.h> @class HTTPServer; @interface AppDelegate : NSObject { @private HTTPServer* _httpServer; } @end
007xsq-sadsad
Samples/WebDAVServer/AppDelegate.h
Objective-C
bsd
124
#import <Cocoa/Cocoa.h> int main(int argc, char* argv[]) { return NSApplicationMain(argc, (const char**)argv); }
007xsq-sadsad
Samples/WebDAVServer/main.m
Objective-C
bsd
116
#import "AppDelegate.h" #import "DDLog.h" #import "DDTTYLogger.h" #import "HTTPServer.h" #import "DAVConnection.h" static const int ddLogLevel = LOG_LEVEL_VERBOSE; @implementation AppDelegate - (void) applicationDidFinishLaunching:(NSNotification*)notification { // Configure logging system [DDLog addLogger:[DDTTYLogger sharedInstance]]; // Create DAV server _httpServer = [[HTTPServer alloc] init]; [_httpServer setConnectionClass:[DAVConnection class]]; [_httpServer setPort:8080]; // Enable Bonjour [_httpServer setType:@"_http._tcp."]; // Set document root [_httpServer setDocumentRoot:[@"~/Sites" stringByExpandingTildeInPath]]; // Start DAV server NSError* error = nil; if (![_httpServer start:&error]) { DDLogError(@"Error starting HTTP Server: %@", error); } } - (void) applicationWillTerminate:(NSNotification*)notification { // Stop DAV server [_httpServer stop]; [_httpServer release]; _httpServer = nil; } @end
007xsq-sadsad
Samples/WebDAVServer/AppDelegate.m
Objective-C
bsd
981
<html> <body> <form action="post.html" method="post"> What is 5 + 5 ? : <input type="text" name="answer" size="4"><br/> <input type="submit" value="Check Answer"> </form> </body> </html>
007xsq-sadsad
Samples/PostHTTPServer/Web/index.html
HTML
bsd
190
#import <Cocoa/Cocoa.h> #import "HTTPConnection.h" @interface MyHTTPConnection : HTTPConnection @end
007xsq-sadsad
Samples/PostHTTPServer/MyHTTPConnection.h
Objective-C
bsd
103
#import <Cocoa/Cocoa.h> @class HTTPServer; @interface AppDelegate : NSObject { HTTPServer *httpServer; } @end
007xsq-sadsad
Samples/PostHTTPServer/AppDelegate.h
Objective-C
bsd
115
// // main.m // PostHTTPServer // // Created by Robbie Hanson on 11/20/08. // Copyright Deusty Designs, LLC. 2008. All rights reserved. // #import <Cocoa/Cocoa.h> int main(int argc, char *argv[]) { return NSApplicationMain(argc, (const char **) argv); }
007xsq-sadsad
Samples/PostHTTPServer/main.m
Objective-C
bsd
265
#import "AppDelegate.h" #import "HTTPServer.h" #import "MyHTTPConnection.h" #import "DDLog.h" #import "DDTTYLogger.h" // Log levels: off, error, warn, info, verbose static const int ddLogLevel = LOG_LEVEL_VERBOSE; @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Configure our logging framework. // To keep things simple and fast, we're just going to log to the Xcode console. [DDLog addLogger:[DDTTYLogger sharedInstance]]; // Initalize our http server httpServer = [[HTTPServer alloc] init]; // Tell the server to broadcast its presence via Bonjour. // This allows browsers such as Safari to automatically discover our service. [httpServer setType:@"_http._tcp."]; // Normally there's no need to run our server on any specific port. // Technologies like Bonjour allow clients to dynamically discover the server's port at runtime. // However, for easy testing you may want force a certain port so you can just hit the refresh button. // [httpServer setPort:12345]; // We're going to extend the base HTTPConnection class with our MyHTTPConnection class. // This allows us to do all kinds of customizations. [httpServer setConnectionClass:[MyHTTPConnection class]]; // Serve files from our embedded Web folder NSString *webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Web"]; DDLogInfo(@"Setting document root: %@", webPath); [httpServer setDocumentRoot:webPath]; NSError *error = nil; if(![httpServer start:&error]) { DDLogError(@"Error starting HTTP Server: %@", error); } } @end
007xsq-sadsad
Samples/PostHTTPServer/AppDelegate.m
Objective-C
bsd
1,612
#import "MyHTTPConnection.h" #import "HTTPMessage.h" #import "HTTPDataResponse.h" #import "DDNumber.h" #import "HTTPLogging.h" // Log levels : off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; /** * All we have to do is override appropriate methods in HTTPConnection. **/ @implementation MyHTTPConnection - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path { HTTPLogTrace(); // Add support for POST if ([method isEqualToString:@"POST"]) { if ([path isEqualToString:@"/post.html"]) { // Let's be extra cautious, and make sure the upload isn't 5 gigs return requestContentLength < 50; } } return [super supportsMethod:method atPath:path]; } - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path { HTTPLogTrace(); // Inform HTTP server that we expect a body to accompany a POST request if([method isEqualToString:@"POST"]) return YES; return [super expectsRequestBodyFromMethod:method atPath:path]; } - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path { HTTPLogTrace(); if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/post.html"]) { HTTPLogVerbose(@"%@[%p]: postContentLength: %qu", THIS_FILE, self, requestContentLength); NSString *postStr = nil; NSData *postData = [request body]; if (postData) { postStr = [[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding] autorelease]; } HTTPLogVerbose(@"%@[%p]: postStr: %@", THIS_FILE, self, postStr); // Result will be of the form "answer=..." int answer = [[postStr substringFromIndex:7] intValue]; NSData *response = nil; if(answer == 10) { response = [@"<html><body>Correct<body></html>" dataUsingEncoding:NSUTF8StringEncoding]; } else { response = [@"<html><body>Sorry - Try Again<body></html>" dataUsingEncoding:NSUTF8StringEncoding]; } return [[[HTTPDataResponse alloc] initWithData:response] autorelease]; } return [super httpResponseForMethod:method URI:path]; } - (void)prepareForBodyWithSize:(UInt64)contentLength { HTTPLogTrace(); // If we supported large uploads, // we might use this method to create/open files, allocate memory, etc. } - (void)processBodyData:(NSData *)postDataChunk { HTTPLogTrace(); // Remember: In order to support LARGE POST uploads, the data is read in chunks. // This prevents a 50 MB upload from being stored in RAM. // The size of the chunks are limited by the POST_CHUNKSIZE definition. // Therefore, this method may be called multiple times for the same POST request. BOOL result = [request appendData:postDataChunk]; if (!result) { HTTPLogError(@"%@[%p]: %@ - Couldn't append bytes!", THIS_FILE, self, THIS_METHOD); } } @end
007xsq-sadsad
Samples/PostHTTPServer/MyHTTPConnection.m
Objective-C
bsd
2,849
#import <Cocoa/Cocoa.h> #import "HTTPConnection.h" @interface MyHTTPConnection : HTTPConnection { } @end
007xsq-sadsad
Samples/PasswdHTTPServer/MyHTTPConnection.h
Objective-C
bsd
109
#import <Cocoa/Cocoa.h> @class HTTPServer; @interface AppDelegate : NSObject { HTTPServer *httpServer; } @end
007xsq-sadsad
Samples/PasswdHTTPServer/AppDelegate.h
Objective-C
bsd
115
// // main.m // PasswdHTTPServer // // Created by Robbie Hanson on 5/19/09. // Copyright Deusty Designs, LLC. 2009. All rights reserved. // #import <Cocoa/Cocoa.h> int main(int argc, char *argv[]) { return NSApplicationMain(argc, (const char **) argv); }
007xsq-sadsad
Samples/PasswdHTTPServer/main.m
Objective-C
bsd
266
#import "AppDelegate.h" #import "HTTPServer.h" #import "MyHTTPConnection.h" #import "DDLog.h" #import "DDTTYLogger.h" // Log levels: off, error, warn, info, verbose static const int ddLogLevel = LOG_LEVEL_VERBOSE; @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Configure our logging framework. // To keep things simple and fast, we're just going to log to the Xcode console. [DDLog addLogger:[DDTTYLogger sharedInstance]]; // Initalize our http server httpServer = [[HTTPServer alloc] init]; // Tell the server to broadcast its presence via Bonjour. // This allows browsers such as Safari to automatically discover our service. [httpServer setType:@"_http._tcp."]; // Normally there's no need to run our server on any specific port. // Technologies like Bonjour allow clients to dynamically discover the server's port at runtime. // However, for easy testing you may want force a certain port so you can just hit the refresh button. // [httpServer setPort:12345]; // We're going to extend the base HTTPConnection class with our MyHTTPConnection class. // This allows us to do custom password protection on our sensitive directories. [httpServer setConnectionClass:[MyHTTPConnection class]]; // Serve files from the standard Sites folder NSString *docRoot = [@"~/Sites" stringByExpandingTildeInPath]; DDLogInfo(@"Setting document root: %@", docRoot); [httpServer setDocumentRoot:docRoot]; NSError *error = nil; if(![httpServer start:&error]) { DDLogError(@"Error starting HTTP Server: %@", error); } } @end
007xsq-sadsad
Samples/PasswdHTTPServer/AppDelegate.m
Objective-C
bsd
1,605
#import "MyHTTPConnection.h" #import "HTTPLogging.h" // Log levels : off, error, warn, info, verbose // Other flags: trace static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE | HTTP_LOG_FLAG_TRACE; @implementation MyHTTPConnection - (BOOL)isPasswordProtected:(NSString *)path { // We're only going to password protect the "secret" directory. BOOL result = [path hasPrefix:@"/secret"]; HTTPLogTrace2(@"%@[%p]: isPasswordProtected(%@) - %@", THIS_FILE, self, path, (result ? @"YES" : @"NO")); return result; } - (BOOL)useDigestAccessAuthentication { HTTPLogTrace(); // Digest access authentication is the default setting. // Notice in Safari that when you're prompted for your password, // Safari tells you "Your login information will be sent securely." // // If you return NO in this method, the HTTP server will use // basic authentication. Try it and you'll see that Safari // will tell you "Your password will be sent unencrypted", // which is strongly discouraged. return YES; } - (NSString *)passwordForUser:(NSString *)username { HTTPLogTrace(); // You can do all kinds of cool stuff here. // For simplicity, we're not going to check the username, only the password. return @"secret"; } @end
007xsq-sadsad
Samples/PasswdHTTPServer/MyHTTPConnection.m
Objective-C
bsd
1,241
<html> <head> <title>Dynamic Server Example</title> </head> <body bgcolor="#FFFFFF"> <h1> Welcome to <a href="http://code.google.com/p/cocoahttpserver/">CocoaHTTPServer</a>! </h1> <p> Parts of this file are generated dynamically.<br/> This is done via the HTTPDynamicFileResponse class.<br/> It uses a replacement dictionary to automatically replace<br/> tagged strings in the included Web/index.html file.<br/> </p> <p> Computer name: %%COMPUTER_NAME%%<br/> <br/> <!-- Test 1: replacement value length > key length --> The current time is: %%TIME%%<br/> <br/> Tell me a story: %%STORY%%<br/> <br/> <!-- Test 2: replacement value length < key length --> The first letter of the english alphabet: %%ALPHABET%%<br/> <br/> <!-- Test 3: replacement value length == key length --> The sound a duck makes: %%QUACK%%<br/> <br/> <br/> Thank you. Come again. </p> </body> </html>
007xsq-sadsad
Samples/DynamicServer/Web/index.html
HTML
bsd
910
#import <Foundation/Foundation.h> #import "HTTPConnection.h" @interface MyHTTPConnection : HTTPConnection @end
007xsq-sadsad
Samples/DynamicServer/MyHTTPConnection.h
Objective-C
bsd
115